text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LoginWithEmailLinkEvent', () {
group('LoginWithEmailLinkSubmitted', () {
test('supports value comparisons', () {
final emailLink = Uri.https('example.com');
expect(
LoginWithEmailLinkSubmitted(emailLink),
LoginWithEmailLinkSubmitted(emailLink),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 196
} | 971 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/newsletter/newsletter.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('NewsletterEvent', () {
const testEmail = '[email protected]';
group('EmailChanged', () {
test('supports value comparisons', () {
expect(
EmailChanged(email: testEmail),
EmailChanged(email: testEmail),
);
expect(
EmailChanged(email: ''),
isNot(EmailChanged(email: testEmail)),
);
});
});
group('NewsletterSubscribed', () {
test('supports value comparisons', () {
expect(NewsletterSubscribed(), NewsletterSubscribed());
});
});
});
}
| news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 295
} | 972 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_news_example_api/client.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockSearchBloc extends MockBloc<SearchEvent, SearchState>
implements SearchBloc {}
void main() {
late SearchBloc searchBloc;
setUp(() async {
searchBloc = MockSearchBloc();
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [DividerHorizontalBlock()],
searchType: SearchType.popular,
status: SearchStatus.initial,
topics: ['topic'],
),
);
});
group('SearchPage', () {
testWidgets('renders SearchView', (tester) async {
await tester.pumpApp(const SearchPage());
expect(find.byType(SearchView), findsOneWidget);
});
});
group('SearchView', () {
testWidgets('renders filter chips', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.pump();
expect(find.byKey(Key('searchFilterChip_topic')), findsOneWidget);
});
testWidgets(
'when SearchFilterChip clicked adds SearchTermChanged to SearchBloc',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.tap(find.byKey(Key('searchFilterChip_topic')));
verify(() => searchBloc.add(SearchTermChanged(searchTerm: 'topic')))
.called(1);
});
testWidgets('renders articles', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(CategoryFeedItem), findsOneWidget);
});
testWidgets('in SearchType.relevant renders two headline titles',
(tester) async {
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [],
searchType: SearchType.relevant,
status: SearchStatus.initial,
topics: [],
),
);
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(SearchHeadlineText), findsNWidgets(2));
});
testWidgets(
'when SearchTextField changes to non-empty value '
'adds SearchTermChanged to SearchBloc', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.enterText(
find.byKey(Key('searchPage_searchTextField')),
'test',
);
verify(() => searchBloc.add(SearchTermChanged(searchTerm: 'test')))
.called(1);
});
testWidgets(
'when SearchTextField changes to an empty value '
'adds empty SearchTermChanged to SearchBloc', (tester) async {
when(() => searchBloc.state).thenReturn(
const SearchState(
articles: [],
searchType: SearchType.relevant,
status: SearchStatus.initial,
topics: [],
),
);
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
await tester.enterText(
find.byKey(Key('searchPage_searchTextField')),
'',
);
verify(() => searchBloc.add(SearchTermChanged())).called(1);
});
testWidgets('shows snackbar when SearchBloc SearchStatus is failure',
(tester) async {
final expectedStates = [
SearchState.initial(),
SearchState.initial().copyWith(
status: SearchStatus.failure,
),
];
whenListen(searchBloc, Stream.fromIterable(expectedStates));
await tester.pumpApp(
BlocProvider.value(
value: searchBloc,
child: const SearchView(),
),
);
expect(find.byType(SnackBar), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/test/search/view/search_page_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/search/view/search_page_test.dart",
"repo_id": "news_toolkit",
"token_count": 1923
} | 973 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_news_example/terms_of_service/terms_of_service.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
const termsOfServiceBodyTextKey = Key('termsOfServiceBody_text');
group('TermsOfServiceBody', () {
group('renders', () {
testWidgets('SingleChildScrollView', (tester) async {
await tester.pumpApp(
Column(
children: const [
TermsOfServiceBody(),
],
),
);
expect(find.byType(SingleChildScrollView), findsOneWidget);
});
testWidgets('terms of service body text', (tester) async {
await tester.pumpApp(
Column(
children: const [
TermsOfServiceBody(),
],
),
);
expect(find.byKey(termsOfServiceBodyTextKey), findsOneWidget);
});
});
});
}
| news_toolkit/flutter_news_example/test/terms_of_service/widgets/terms_of_service_body_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/terms_of_service/widgets/terms_of_service_body_test.dart",
"repo_id": "news_toolkit",
"token_count": 447
} | 974 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="{{flavors.name}}" type="FlutterRunConfigurationType" factoryName="Flutter" singleton="false">
<option name="additionalArgs" value="--dart-define FLAVOR_DEEP_LINK_DOMAIN={{flavors.deep_link_domain}} --dart-define FLAVOR_DEEP_LINK_PATH=email_login --dart-define TWITTER_API_KEY={{flavors.twitter_api_key}} --dart-define TWITTER_API_SECRET={{flavors.twitter_api_secret}} --dart-define TWITTER_REDIRECT_URI={{project_name.paramCase()}}://" />
<option name="buildFlavor" value="{{flavors.name}}" />
<option name="filePath" value="$PROJECT_DIR$/lib/main/main_{{flavors.name}}.dart" />
<method v="2" />
</configuration>
</component> | news_toolkit/tool/generator/static/intellij_run_configuration.xml/0 | {
"file_path": "news_toolkit/tool/generator/static/intellij_run_configuration.xml",
"repo_id": "news_toolkit",
"token_count": 268
} | 975 |
#!/bin/bash
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set -e
# The name here must match create_simulator.sh
readonly DEVICE_NAME=Flutter-iPhone
# Allow boot to fail; cases like "Unable to boot device in current state: Booted"
# exit with failure.
xcrun simctl boot "$DEVICE_NAME" || :
echo -e ""
xcrun simctl list
| packages/.ci/scripts/boot_simulator.sh/0 | {
"file_path": "packages/.ci/scripts/boot_simulator.sh",
"repo_id": "packages",
"token_count": 131
} | 976 |
#!/bin/bash
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set -e
# The name here must match create_simulator.sh
readonly DEVICE_NAME=Flutter-iPhone
# Allow shutdown to fail; cases like "already shut down" exit with failure.
xcrun simctl shutdown "$DEVICE_NAME" || :
xcrun simctl delete "$DEVICE_NAME"
xcrun simctl list
| packages/.ci/scripts/remove_simulator.sh/0 | {
"file_path": "packages/.ci/scripts/remove_simulator.sh",
"repo_id": "packages",
"token_count": 129
} | 977 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: create all_packages app
script: .ci/scripts/create_all_packages_app.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: build all_packages for Linux debug
script: .ci/scripts/build_all_packages_app.sh
args: ["linux", "debug"]
- name: build all_packages for Linux release
script: .ci/scripts/build_all_packages_app.sh
args: ["linux", "release"]
| packages/.ci/targets/linux_build_all_packages.yaml/0 | {
"file_path": "packages/.ci/targets/linux_build_all_packages.yaml",
"repo_id": "packages",
"token_count": 192
} | 978 |
BasedOnStyle: Google
---
Language: Cpp
DerivePointerAlignment: false
PointerAlignment: Left
---
Language: ObjC
DerivePointerAlignment: false
PointerAlignment: Right
| packages/.clang-format/0 | {
"file_path": "packages/.clang-format",
"repo_id": "packages",
"token_count": 52
} | 979 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.0.11
* Fixes new lint warnings.
## 2.0.10
* Updates minimum supported SDK version to Flutter 3.16/Dart 3.2.
## 2.0.9
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Migrate motion curves to use `Easing` class.
## 2.0.8
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Aligns Dart and Flutter SDK constraints.
## 2.0.7
* Updates screenshots to use webp compressed animations
## 2.0.6
* Adds screenshots to pubspec.yaml
## 2.0.5
* Update `OpenContainer` to use `Visibility` widget internally instead of `Opacity`.
* Update `OpenContainer` to use `FadeTransition` instead of animating an `Opacity`
widget internally.
## 2.0.4
* Updates text theme parameters to avoid deprecation issues.
* Fixes lint warnings.
## 2.0.3
* Updates for non-nullable bindings.
## 2.0.2
* Fixed documentation for `OpenContainer` class; replaced `openBuilder` with `closedBuilder`.
## 2.0.1
* Add links to the spec and codelab.
## 2.0.0
* Migrates to null safety.
* Add `routeSettings` and `filter` option to `showModal`.
## 1.1.2
* Fixes for upcoming changes to the flutter framework.
## 1.1.1
* Hide implementation of `DualTransitionBuilder` as the widget has been implemented in the Flutter framework.
## 1.1.0
* Introduce usage of `DualTransitionBuilder` for all transition widgets, preventing ongoing animations at the start of the transition animation from resetting at the end of the transition animations.
* Fix `FadeScaleTransition` example's `FloatingActionButton` being accessible
and tappable when it is supposed to be hidden.
* `showModal` now defaults to using `FadeScaleTransitionConfiguration` instead of `null`.
* Added const constructors for `FadeScaleTransitionConfiguration` and `ModalConfiguration`.
* Add custom fillColor property to `SharedAxisTransition` and `SharedAxisPageTransitionsBuilder`.
* Fix prefer_const_constructors lint in test and example.
* Add option `useRootNavigator` to `OpenContainer`.
* Add `OpenContainer.onClosed`, which is called with a returned value when the container was popped and has returned to the closed state.
* Fixes a bug with OpenContainer where a crash occurs when the container is dismissed after the container widget itself is removed.
## 1.0.0+5
* Fix override analyzer ignore placement.
## 1.0.0+4
* Fix a typo in the changelog dates
* Revert use of modern Material text style nomenclature in the example app
to be compatible with Flutter's `stable` branch for the time being.
* Add override analyzer ignore in modal.dart for reverseTransitionDuration
until Flutter's stable branch contains
https://github.com/flutter/flutter/pull/48274.
## 1.0.0+3
* Update README.md to better describe Material motion
## 1.0.0+2
* Fixes to pubspec.yaml
## 1.0.0+1
* Fixes to pubspec.yaml
## 1.0.0
* Initial release
| packages/packages/animations/CHANGELOG.md/0 | {
"file_path": "packages/packages/animations/CHANGELOG.md",
"repo_id": "packages",
"token_count": 881
} | 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 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'fade_scale_transition.dart';
/// Signature for a function that creates a widget that builds a
/// transition.
///
/// Used by [PopupRoute].
typedef _ModalTransitionBuilder = Widget Function(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
);
/// Displays a modal above the current contents of the app.
///
/// Content below the modal is dimmed with a [ModalBarrier].
///
/// The `context` argument is used to look up the [Navigator] for the
/// modal. It is only used when the method is called. Its corresponding widget
/// can be safely removed from the tree before the modal is closed.
///
/// The `configuration` argument is used to determine characteristics of the
/// modal route that will be displayed, such as the enter and exit
/// transitions, the duration of the transitions, and modal barrier
/// properties. By default, `configuration` is
/// [FadeScaleTransitionConfiguration].
///
/// The `useRootNavigator` argument is used to determine whether to push the
/// modal to the [Navigator] furthest from or nearest to the given `context`.
/// By default, `useRootNavigator` is `true` and the modal route created by
/// this method is pushed to the root navigator. If the application has
/// multiple [Navigator] objects, it may be necessary to call
/// `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// modal rather than just `Navigator.pop(context, result)`.
///
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the modal was closed.
///
/// See also:
///
/// * [ModalConfiguration], which is the configuration object used to define
/// the modal's characteristics.
Future<T?> showModal<T>({
required BuildContext context,
ModalConfiguration configuration = const FadeScaleTransitionConfiguration(),
bool useRootNavigator = true,
required WidgetBuilder builder,
RouteSettings? routeSettings,
ui.ImageFilter? filter,
}) {
String? barrierLabel = configuration.barrierLabel;
// Avoid looking up [MaterialLocalizations.of(context).modalBarrierDismissLabel]
// if there is no dismissible barrier.
if (configuration.barrierDismissible && configuration.barrierLabel == null) {
barrierLabel = MaterialLocalizations.of(context).modalBarrierDismissLabel;
}
assert(!configuration.barrierDismissible || barrierLabel != null);
return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(
_ModalRoute<T>(
barrierColor: configuration.barrierColor,
barrierDismissible: configuration.barrierDismissible,
barrierLabel: barrierLabel,
transitionBuilder: configuration.transitionBuilder,
transitionDuration: configuration.transitionDuration,
reverseTransitionDuration: configuration.reverseTransitionDuration,
builder: builder,
routeSettings: routeSettings,
filter: filter,
),
);
}
// A modal route that overlays a widget on the current route.
class _ModalRoute<T> extends PopupRoute<T> {
/// Creates a route with general modal route.
///
/// [barrierDismissible] configures whether or not tapping the modal's
/// scrim dismisses the modal. [barrierLabel] sets the semantic label for
/// a dismissible barrier. [barrierDismissible] cannot be null. If
/// [barrierDismissible] is true, the [barrierLabel] cannot be null.
///
/// [transitionBuilder] takes in a function that creates a widget. This
/// widget is typically used to configure the modal's transition.
_ModalRoute({
this.barrierColor,
this.barrierDismissible = true,
this.barrierLabel,
required this.transitionDuration,
required this.reverseTransitionDuration,
required _ModalTransitionBuilder transitionBuilder,
required this.builder,
RouteSettings? routeSettings,
super.filter,
}) : assert(!barrierDismissible || barrierLabel != null),
_transitionBuilder = transitionBuilder,
super(settings: routeSettings);
@override
final Color? barrierColor;
@override
final bool barrierDismissible;
@override
final String? barrierLabel;
@override
final Duration transitionDuration;
@override
final Duration reverseTransitionDuration;
/// The primary contents of the modal.
final WidgetBuilder builder;
final _ModalTransitionBuilder _transitionBuilder;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
final ThemeData theme = Theme.of(context);
return Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: SafeArea(
child: Builder(
builder: (BuildContext context) {
final Widget child = Builder(builder: builder);
return Theme(data: theme, child: child);
},
),
),
);
}
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return _transitionBuilder(
context,
animation,
secondaryAnimation,
child,
);
}
}
/// A configuration object containing the properties needed to implement a
/// modal route.
///
/// The `barrierDismissible` argument is used to determine whether this route
/// can be dismissed by tapping the modal barrier. This argument defaults
/// to true. If `barrierDismissible` is true, a non-null `barrierLabel` must be
/// provided.
///
/// The `barrierLabel` argument is the semantic label used for a dismissible
/// barrier. This argument defaults to "Dismiss".
abstract class ModalConfiguration {
/// Creates a modal configuration object that provides the necessary
/// properties to implement a modal route.
///
/// [barrierDismissible] configures whether or not tapping the modal's
/// scrim dismisses the modal. [barrierLabel] sets the semantic label for
/// a dismissible barrier. [barrierDismissible] cannot be null. If
/// [barrierDismissible] is true, the [barrierLabel] cannot be null.
///
/// [transitionDuration] and [reverseTransitionDuration] determine the
/// duration of the transitions when the modal enters and exits the
/// application. [transitionDuration] and [reverseTransitionDuration]
/// cannot be null.
const ModalConfiguration({
required this.barrierColor,
required this.barrierDismissible,
this.barrierLabel,
required this.transitionDuration,
required this.reverseTransitionDuration,
}) : assert(!barrierDismissible || barrierLabel != null);
/// The color to use for the modal barrier. If this is null, the barrier will
/// be transparent.
final Color barrierColor;
/// Whether you can dismiss this route by tapping the modal barrier.
final bool barrierDismissible;
/// The semantic label used for a dismissible barrier.
final String? barrierLabel;
/// The duration of the transition running forwards.
final Duration transitionDuration;
/// The duration of the transition running in reverse.
final Duration reverseTransitionDuration;
/// A builder that defines how the route arrives on and leaves the screen.
///
/// The [buildTransitions] method is typically used to define transitions
/// that animate the new topmost route's comings and goings. When the
/// [Navigator] pushes a route on the top of its stack, the new route's
/// primary [animation] runs from 0.0 to 1.0. When the [Navigator] pops the
/// topmost route, e.g. because the use pressed the back button, the
/// primary animation runs from 1.0 to 0.0.
Widget transitionBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
);
}
| packages/packages/animations/lib/src/modal.dart/0 | {
"file_path": "packages/packages/animations/lib/src/modal.dart",
"repo_id": "packages",
"token_count": 2330
} | 981 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/camera/camera/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/camera/camera/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 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:async';
import 'dart:collection';
import 'dart:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../camera.dart';
/// Signature for a callback receiving the a camera image.
///
/// This is used by [CameraController.startImageStream].
// TODO(stuartmorgan): Fix this naming the next time there's a breaking change
// to this package.
// ignore: camel_case_types
typedef onLatestImageAvailable = void Function(CameraImage image);
/// Completes with a list of available cameras.
///
/// May throw a [CameraException].
Future<List<CameraDescription>> availableCameras() async {
return CameraPlatform.instance.availableCameras();
}
// TODO(stuartmorgan): Remove this once the package requires 2.10, where the
// dart:async `unawaited` accepts a nullable future.
void _unawaited(Future<void>? future) {}
/// The state of a [CameraController].
class CameraValue {
/// Creates a new camera controller state.
const CameraValue({
required this.isInitialized,
this.errorDescription,
this.previewSize,
required this.isRecordingVideo,
required this.isTakingPicture,
required this.isStreamingImages,
required bool isRecordingPaused,
required this.flashMode,
required this.exposureMode,
required this.focusMode,
required this.exposurePointSupported,
required this.focusPointSupported,
required this.deviceOrientation,
required this.description,
this.lockedCaptureOrientation,
this.recordingOrientation,
this.isPreviewPaused = false,
this.previewPauseOrientation,
}) : _isRecordingPaused = isRecordingPaused;
/// Creates a new camera controller state for an uninitialized controller.
const CameraValue.uninitialized(CameraDescription description)
: this(
isInitialized: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
isRecordingPaused: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
exposurePointSupported: false,
focusMode: FocusMode.auto,
focusPointSupported: false,
deviceOrientation: DeviceOrientation.portraitUp,
isPreviewPaused: false,
description: description,
);
/// True after [CameraController.initialize] has completed successfully.
final bool isInitialized;
/// True when a picture capture request has been sent but as not yet returned.
final bool isTakingPicture;
/// True when the camera is recording (not the same as previewing).
final bool isRecordingVideo;
/// True when images from the camera are being streamed.
final bool isStreamingImages;
final bool _isRecordingPaused;
/// True when the preview widget has been paused manually.
final bool isPreviewPaused;
/// Set to the orientation the preview was paused in, if it is currently paused.
final DeviceOrientation? previewPauseOrientation;
/// True when camera [isRecordingVideo] and recording is paused.
bool get isRecordingPaused => isRecordingVideo && _isRecordingPaused;
/// Description of an error state.
///
/// This is null while the controller is not in an error state.
/// When [hasError] is true this contains the error description.
final String? errorDescription;
/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size? previewSize;
/// Convenience getter for `previewSize.width / previewSize.height`.
///
/// Can only be called when [initialize] is done.
double get aspectRatio => previewSize!.width / previewSize!.height;
/// Whether the controller is in an error state.
///
/// When true [errorDescription] describes the error.
bool get hasError => errorDescription != null;
/// The flash mode the camera is currently set to.
final FlashMode flashMode;
/// The exposure mode the camera is currently set to.
final ExposureMode exposureMode;
/// The focus mode the camera is currently set to.
final FocusMode focusMode;
/// Whether setting the exposure point is supported.
final bool exposurePointSupported;
/// Whether setting the focus point is supported.
final bool focusPointSupported;
/// The current device UI orientation.
final DeviceOrientation deviceOrientation;
/// The currently locked capture orientation.
final DeviceOrientation? lockedCaptureOrientation;
/// Whether the capture orientation is currently locked.
bool get isCaptureOrientationLocked => lockedCaptureOrientation != null;
/// The orientation of the currently running video recording.
final DeviceOrientation? recordingOrientation;
/// The properties of the camera device controlled by this controller.
final CameraDescription description;
/// Creates a modified copy of the object.
///
/// Explicitly specified fields get the specified value, all other fields get
/// the same value of the current object.
CameraValue copyWith({
bool? isInitialized,
bool? isRecordingVideo,
bool? isTakingPicture,
bool? isStreamingImages,
String? errorDescription,
Size? previewSize,
bool? isRecordingPaused,
FlashMode? flashMode,
ExposureMode? exposureMode,
FocusMode? focusMode,
bool? exposurePointSupported,
bool? focusPointSupported,
DeviceOrientation? deviceOrientation,
Optional<DeviceOrientation>? lockedCaptureOrientation,
Optional<DeviceOrientation>? recordingOrientation,
bool? isPreviewPaused,
CameraDescription? description,
Optional<DeviceOrientation>? previewPauseOrientation,
}) {
return CameraValue(
isInitialized: isInitialized ?? this.isInitialized,
errorDescription: errorDescription,
previewSize: previewSize ?? this.previewSize,
isRecordingVideo: isRecordingVideo ?? this.isRecordingVideo,
isTakingPicture: isTakingPicture ?? this.isTakingPicture,
isStreamingImages: isStreamingImages ?? this.isStreamingImages,
isRecordingPaused: isRecordingPaused ?? _isRecordingPaused,
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
exposurePointSupported:
exposurePointSupported ?? this.exposurePointSupported,
focusPointSupported: focusPointSupported ?? this.focusPointSupported,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation: lockedCaptureOrientation == null
? this.lockedCaptureOrientation
: lockedCaptureOrientation.orNull,
recordingOrientation: recordingOrientation == null
? this.recordingOrientation
: recordingOrientation.orNull,
isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused,
description: description ?? this.description,
previewPauseOrientation: previewPauseOrientation == null
? this.previewPauseOrientation
: previewPauseOrientation.orNull,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'CameraValue')}('
'isRecordingVideo: $isRecordingVideo, '
'isInitialized: $isInitialized, '
'errorDescription: $errorDescription, '
'previewSize: $previewSize, '
'isStreamingImages: $isStreamingImages, '
'flashMode: $flashMode, '
'exposureMode: $exposureMode, '
'focusMode: $focusMode, '
'exposurePointSupported: $exposurePointSupported, '
'focusPointSupported: $focusPointSupported, '
'deviceOrientation: $deviceOrientation, '
'lockedCaptureOrientation: $lockedCaptureOrientation, '
'recordingOrientation: $recordingOrientation, '
'isPreviewPaused: $isPreviewPaused, '
'previewPausedOrientation: $previewPauseOrientation, '
'description: $description)';
}
}
/// Controls a device camera.
///
/// Use [availableCameras] to get a list of available cameras.
///
/// Before using a [CameraController] a call to [initialize] must complete.
///
/// To show the camera preview on the screen use a [CameraPreview] widget.
class CameraController extends ValueNotifier<CameraValue> {
/// Creates a new camera controller in an uninitialized state.
CameraController(
CameraDescription description,
this.resolutionPreset, {
this.enableAudio = true,
this.imageFormatGroup,
}) : super(CameraValue.uninitialized(description));
/// The properties of the camera device controlled by this controller.
CameraDescription get description => value.description;
/// The resolution this controller is targeting.
///
/// This resolution preset is not guaranteed to be available on the device,
/// if unavailable a lower resolution will be used.
///
/// See also: [ResolutionPreset].
final ResolutionPreset resolutionPreset;
/// Whether to include audio when recording a video.
final bool enableAudio;
/// The [ImageFormatGroup] describes the output of the raw image format.
///
/// When null the imageFormat will fallback to the platforms default.
final ImageFormatGroup? imageFormatGroup;
/// The id of a camera that hasn't been initialized.
@visibleForTesting
static const int kUninitializedCameraId = -1;
int _cameraId = kUninitializedCameraId;
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
// A Future awaiting an attempt to initialize (e.g. after `initialize` was
// just called). If the controller has not been initialized at least once,
// this value is null.
Future<void>? _initializeFuture;
StreamSubscription<DeviceOrientationChangedEvent>?
_deviceOrientationSubscription;
/// Checks whether [CameraController.dispose] has completed successfully.
///
/// This is a no-op when asserts are disabled.
void debugCheckIsDisposed() {
assert(_isDisposed);
}
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
/// Initializes the camera on the device.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> initialize() => _initializeWithDescription(description);
/// Initializes the camera on the device with the specified description.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> _initializeWithDescription(CameraDescription description) async {
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'initialize was called on a disposed CameraController',
);
}
final Completer<void> initializeCompleter = Completer<void>();
_initializeFuture = initializeCompleter.future;
try {
final Completer<CameraInitializedEvent> initializeCompleter =
Completer<CameraInitializedEvent>();
_deviceOrientationSubscription ??= CameraPlatform.instance
.onDeviceOrientationChanged()
.listen((DeviceOrientationChangedEvent event) {
value = value.copyWith(
deviceOrientation: event.orientation,
);
});
_cameraId = await CameraPlatform.instance.createCamera(
description,
resolutionPreset,
enableAudio: enableAudio,
);
_unawaited(CameraPlatform.instance
.onCameraInitialized(_cameraId)
.first
.then((CameraInitializedEvent event) {
initializeCompleter.complete(event);
}));
await CameraPlatform.instance.initializeCamera(
_cameraId,
imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown,
);
value = value.copyWith(
isInitialized: true,
description: description,
previewSize: await initializeCompleter.future
.then((CameraInitializedEvent event) => Size(
event.previewWidth,
event.previewHeight,
)),
exposureMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.exposureMode),
focusMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusMode),
exposurePointSupported: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposurePointSupported),
focusPointSupported: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusPointSupported),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
} finally {
initializeCompleter.complete();
}
}
/// Prepare the capture session for video recording.
///
/// Use of this method is optional, but it may be called for performance
/// reasons on iOS.
///
/// Preparing audio can cause a minor delay in the CameraPreview view on iOS.
/// If video recording is intended, calling this early eliminates this delay
/// that would otherwise be experienced when video recording is started.
/// This operation is a no-op on Android and Web.
///
/// Throws a [CameraException] if the prepare fails.
Future<void> prepareForVideoRecording() async {
await CameraPlatform.instance.prepareForVideoRecording();
}
/// Pauses the current camera preview
Future<void> pausePreview() async {
if (value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.pausePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: true,
previewPauseOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resumes the current camera preview
Future<void> resumePreview() async {
if (!value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.resumePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: false,
previewPauseOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the description of the camera.
///
/// Throws a [CameraException] if setting the description fails.
Future<void> setDescription(CameraDescription description) async {
if (value.isRecordingVideo) {
await CameraPlatform.instance.setDescriptionWhileRecording(description);
value = value.copyWith(description: description);
} else {
if (_initializeFuture != null) {
await _initializeFuture;
await CameraPlatform.instance.dispose(_cameraId);
}
await _initializeWithDescription(description);
}
}
/// Captures an image and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture fails.
Future<XFile> takePicture() async {
_throwIfNotInitialized('takePicture');
if (value.isTakingPicture) {
throw CameraException(
'Previous capture has not returned yet.',
'takePicture was called before the previous capture returned.',
);
}
try {
value = value.copyWith(isTakingPicture: true);
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
value = value.copyWith(isTakingPicture: false);
return file;
} on PlatformException catch (e) {
value = value.copyWith(isTakingPicture: false);
throw CameraException(e.code, e.message);
}
}
/// Start streaming images from platform camera.
///
/// Settings for capturing images on iOS and Android is set to always use the
/// latest image available from the camera and will drop all other images.
///
/// When running continuously with [CameraPreview] widget, this function runs
/// best with [ResolutionPreset.low]. Running on [ResolutionPreset.high] can
/// have significant frame rate drops for [CameraPreview] on lower end
/// devices.
///
/// Throws a [CameraException] if image streaming or video recording has
/// already started.
///
/// The `startImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
///
// TODO(bmparr): Add settings for resolution and fps.
Future<void> startImageStream(onLatestImageAvailable onAvailable) async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('startImageStream');
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startImageStream was called while a video is being recorded.',
);
}
if (value.isStreamingImages) {
throw CameraException(
'A camera has started streaming images.',
'startImageStream was called while a camera was streaming images.',
);
}
try {
_imageStreamSubscription = CameraPlatform.instance
.onStreamedFrameAvailable(_cameraId)
.listen((CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
});
value = value.copyWith(isStreamingImages: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stop streaming images from platform camera.
///
/// Throws a [CameraException] if image streaming was not started or video
/// recording was started.
///
/// The `stopImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
Future<void> stopImageStream() async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('stopImageStream');
if (!value.isStreamingImages) {
throw CameraException(
'No camera is streaming images',
'stopImageStream was called when no camera is streaming images.',
);
}
try {
value = value.copyWith(isStreamingImages: false);
await _imageStreamSubscription?.cancel();
_imageStreamSubscription = null;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Start a video recording.
///
/// You may optionally pass an [onAvailable] callback to also have the
/// video frames streamed to this callback.
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
Future<void> startVideoRecording(
{onLatestImageAvailable? onAvailable}) async {
_throwIfNotInitialized('startVideoRecording');
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startVideoRecording was called when a recording is already started.',
);
}
void Function(CameraImageData image)? streamCallback;
if (onAvailable != null) {
streamCallback = (CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
};
}
try {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback));
value = value.copyWith(
isRecordingVideo: true,
isRecordingPaused: false,
recordingOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation),
isStreamingImages: onAvailable != null);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stops the video recording and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture failed.
Future<XFile> stopVideoRecording() async {
_throwIfNotInitialized('stopVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'stopVideoRecording was called when no video is recording.',
);
}
if (value.isStreamingImages) {
await stopImageStream();
}
try {
final XFile file =
await CameraPlatform.instance.stopVideoRecording(_cameraId);
value = value.copyWith(
isRecordingVideo: false,
recordingOrientation: const Optional<DeviceOrientation>.absent(),
);
return file;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Pause video recording.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> pauseVideoRecording() async {
_throwIfNotInitialized('pauseVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'pauseVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.pauseVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resume video recording after pausing.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> resumeVideoRecording() async {
_throwIfNotInitialized('resumeVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'resumeVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.resumeVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: false);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Returns a widget showing a live camera preview.
Widget buildPreview() {
_throwIfNotInitialized('buildPreview');
try {
return CameraPlatform.instance.buildPreview(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported zoom level for the selected camera.
Future<double> getMaxZoomLevel() {
_throwIfNotInitialized('getMaxZoomLevel');
try {
return CameraPlatform.instance.getMaxZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported zoom level for the selected camera.
Future<double> getMinZoomLevel() {
_throwIfNotInitialized('getMinZoomLevel');
try {
return CameraPlatform.instance.getMinZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Set the zoom level for the selected camera.
///
/// The supplied [zoom] value should be between 1.0 and the maximum supported
/// zoom level returned by the `getMaxZoomLevel`. Throws an `CameraException`
/// when an illegal zoom level is suplied.
Future<void> setZoomLevel(double zoom) {
_throwIfNotInitialized('setZoomLevel');
try {
return CameraPlatform.instance.setZoomLevel(_cameraId, zoom);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the flash mode for taking pictures.
Future<void> setFlashMode(FlashMode mode) async {
try {
await CameraPlatform.instance.setFlashMode(_cameraId, mode);
value = value.copyWith(flashMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure mode for taking pictures.
Future<void> setExposureMode(ExposureMode mode) async {
try {
await CameraPlatform.instance.setExposureMode(_cameraId, mode);
value = value.copyWith(exposureMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure point for automatically determining the exposure value.
///
/// Supplying a `null` value will reset the exposure point to it's default
/// value.
Future<void> setExposurePoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setExposurePoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported exposure offset for the selected camera in EV units.
Future<double> getMinExposureOffset() async {
_throwIfNotInitialized('getMinExposureOffset');
try {
return CameraPlatform.instance.getMinExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported exposure offset for the selected camera in EV units.
Future<double> getMaxExposureOffset() async {
_throwIfNotInitialized('getMaxExposureOffset');
try {
return CameraPlatform.instance.getMaxExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the supported step size for exposure offset for the selected camera in EV units.
///
/// Returns 0 when the camera supports using a free value without stepping.
Future<double> getExposureOffsetStepSize() async {
_throwIfNotInitialized('getExposureOffsetStepSize');
try {
return CameraPlatform.instance.getExposureOffsetStepSize(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure offset for the selected camera.
///
/// The supplied [offset] value should be in EV units. 1 EV unit represents a
/// doubling in brightness. It should be between the minimum and maximum offsets
/// obtained through `getMinExposureOffset` and `getMaxExposureOffset` respectively.
/// Throws a `CameraException` when an illegal offset is supplied.
///
/// When the supplied [offset] value does not align with the step size obtained
/// through `getExposureStepSize`, it will automatically be rounded to the nearest step.
///
/// Returns the (rounded) offset value that was set.
Future<double> setExposureOffset(double offset) async {
_throwIfNotInitialized('setExposureOffset');
// Check if offset is in range
final List<double> range = await Future.wait(
<Future<double>>[getMinExposureOffset(), getMaxExposureOffset()]);
if (offset < range[0] || offset > range[1]) {
throw CameraException(
'exposureOffsetOutOfBounds',
'The provided exposure offset was outside the supported range for this device.',
);
}
// Round to the closest step if needed
final double stepSize = await getExposureOffsetStepSize();
if (stepSize > 0) {
final double inv = 1.0 / stepSize;
double roundedOffset = (offset * inv).roundToDouble() / inv;
if (roundedOffset > range[1]) {
roundedOffset = (offset * inv).floorToDouble() / inv;
} else if (roundedOffset < range[0]) {
roundedOffset = (offset * inv).ceilToDouble() / inv;
}
offset = roundedOffset;
}
try {
return CameraPlatform.instance.setExposureOffset(_cameraId, offset);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Locks the capture orientation.
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation([DeviceOrientation? orientation]) async {
try {
await CameraPlatform.instance.lockCaptureOrientation(
_cameraId, orientation ?? value.deviceOrientation);
value = value.copyWith(
lockedCaptureOrientation: Optional<DeviceOrientation>.of(
orientation ?? value.deviceOrientation));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus mode for taking pictures.
Future<void> setFocusMode(FocusMode mode) async {
try {
await CameraPlatform.instance.setFocusMode(_cameraId, mode);
value = value.copyWith(focusMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
try {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
value = value.copyWith(
lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus point for automatically determining the focus value.
///
/// Supplying a `null` value will reset the focus point to it's default
/// value.
Future<void> setFocusPoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setFocusPoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Releases the resources of this camera.
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_unawaited(_deviceOrientationSubscription?.cancel());
_isDisposed = true;
super.dispose();
if (_initializeFuture != null) {
await _initializeFuture;
await CameraPlatform.instance.dispose(_cameraId);
}
}
void _throwIfNotInitialized(String functionName) {
if (!value.isInitialized) {
throw CameraException(
'Uninitialized CameraController',
'$functionName() was called on an uninitialized CameraController.',
);
}
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
}
@override
void removeListener(VoidCallback listener) {
// Prevent ValueListenableBuilder in CameraPreview widget from causing an
// exception to be thrown by attempting to remove its own listener after
// the controller has already been disposed.
if (!_isDisposed) {
super.removeListener(listener);
}
}
}
/// A value that might be absent.
///
/// Used to represent [DeviceOrientation]s that are optional but also able
/// to be cleared.
@immutable
class Optional<T> extends IterableBase<T> {
/// Constructs an empty Optional.
const Optional.absent() : _value = null;
/// Constructs an Optional of the given [value].
///
/// Throws [ArgumentError] if [value] is null.
Optional.of(T value) : _value = value {
// TODO(cbracken): Delete and make this ctor const once mixed-mode
// execution is no longer around.
ArgumentError.checkNotNull(value);
}
/// Constructs an Optional of the given [value].
///
/// If [value] is null, returns [absent()].
const Optional.fromNullable(T? value) : _value = value;
final T? _value;
/// True when this optional contains a value.
bool get isPresent => _value != null;
/// True when this optional contains no value.
bool get isNotPresent => _value == null;
/// Gets the Optional value.
///
/// Throws [StateError] if [value] is null.
T get value {
if (_value == null) {
throw StateError('value called on absent Optional.');
}
return _value!;
}
/// Executes a function if the Optional value is present.
void ifPresent(void Function(T value) ifPresent) {
if (isPresent) {
ifPresent(_value as T);
}
}
/// Execution a function if the Optional value is absent.
void ifAbsent(void Function() ifAbsent) {
if (!isPresent) {
ifAbsent();
}
}
/// Gets the Optional value with a default.
///
/// The default is returned if the Optional is [absent()].
///
/// Throws [ArgumentError] if [defaultValue] is null.
T or(T defaultValue) {
return _value ?? defaultValue;
}
/// Gets the Optional value, or `null` if there is none.
T? get orNull => _value;
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.of(transformer(_value as T));
}
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// Returns [absent()] if the transformer returns `null`.
Optional<S> transformNullable<S>(S? Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.fromNullable(transformer(_value as T));
}
@override
Iterator<T> get iterator =>
isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
int get hashCode => _value.hashCode;
/// Delegates to the underlying [value] operator==.
@override
bool operator ==(Object o) => o is Optional<T> && o._value == _value;
@override
String toString() {
return _value == null
? 'Optional { absent }'
: 'Optional { value: $_value }';
}
}
| packages/packages/camera/camera/lib/src/camera_controller.dart/0 | {
"file_path": "packages/packages/camera/camera/lib/src/camera_controller.dart",
"repo_id": "packages",
"token_count": 11250
} | 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.
package io.flutter.plugins.camera;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.camera.features.CameraFeature;
import io.flutter.plugins.camera.features.CameraFeatureFactory;
import io.flutter.plugins.camera.features.CameraFeatures;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature;
import io.flutter.plugins.camera.features.autofocus.FocusMode;
import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature;
import io.flutter.plugins.camera.features.exposurelock.ExposureMode;
import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature;
import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature;
import io.flutter.plugins.camera.features.flash.FlashFeature;
import io.flutter.plugins.camera.features.flash.FlashMode;
import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
import io.flutter.plugins.camera.media.ImageStreamReader;
import io.flutter.plugins.camera.media.MediaRecorderBuilder;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper;
import io.flutter.view.TextureRegistry.SurfaceTextureEntry;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
@FunctionalInterface
interface ErrorCallback {
void onError(String errorCode, String errorMessage);
}
class Camera
implements CameraCaptureCallback.CameraCaptureStateListener,
ImageReader.OnImageAvailableListener {
private static final String TAG = "Camera";
private static final HashMap<String, Integer> supportedImageFormats;
// Current supported outputs.
static {
supportedImageFormats = new HashMap<>();
supportedImageFormats.put("yuv420", ImageFormat.YUV_420_888);
supportedImageFormats.put("jpeg", ImageFormat.JPEG);
supportedImageFormats.put("nv21", ImageFormat.NV21);
}
/**
* Holds all of the camera features/settings and will be used to update the request builder when
* one changes.
*/
CameraFeatures cameraFeatures;
private String imageFormatGroup;
/**
* Takes an input/output surface and orients the recording correctly. This is needed because
* switching cameras while recording causes the wrong orientation.
*/
private VideoRenderer videoRenderer;
/**
* Whether or not the camera aligns with the initial way the camera was facing if the camera was
* flipped.
*/
private int initialCameraFacing;
private final SurfaceTextureEntry flutterTexture;
private final ResolutionPreset resolutionPreset;
private final boolean enableAudio;
private final Context applicationContext;
final DartMessenger dartMessenger;
private CameraProperties cameraProperties;
private final CameraFeatureFactory cameraFeatureFactory;
private final Activity activity;
/** A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture. */
private final CameraCaptureCallback cameraCaptureCallback;
/** A {@link Handler} for running tasks in the background. */
Handler backgroundHandler;
/** An additional thread for running tasks that shouldn't block the UI. */
private HandlerThread backgroundHandlerThread;
CameraDeviceWrapper cameraDevice;
CameraCaptureSession captureSession;
private ImageReader pictureImageReader;
ImageStreamReader imageStreamReader;
/** {@link CaptureRequest.Builder} for the camera preview */
CaptureRequest.Builder previewRequestBuilder;
private MediaRecorder mediaRecorder;
/** True when recording video. */
boolean recordingVideo;
/** True when the preview is paused. */
private boolean pausedPreview;
private File captureFile;
/** Holds the current capture timeouts */
private CaptureTimeoutsWrapper captureTimeouts;
/** Holds the last known capture properties */
private CameraCaptureProperties captureProps;
MethodChannel.Result flutterResult;
/** A CameraDeviceWrapper implementation that forwards calls to a CameraDevice. */
private class DefaultCameraDeviceWrapper implements CameraDeviceWrapper {
private final CameraDevice cameraDevice;
DefaultCameraDeviceWrapper(CameraDevice cameraDevice) {
this.cameraDevice = cameraDevice;
}
@NonNull
@Override
public CaptureRequest.Builder createCaptureRequest(int templateType)
throws CameraAccessException {
return cameraDevice.createCaptureRequest(templateType);
}
@TargetApi(VERSION_CODES.P)
@Override
public void createCaptureSession(SessionConfiguration config) throws CameraAccessException {
cameraDevice.createCaptureSession(config);
}
@SuppressWarnings("deprecation")
@Override
public void createCaptureSession(
@NonNull List<Surface> outputs,
@NonNull CameraCaptureSession.StateCallback callback,
@Nullable Handler handler)
throws CameraAccessException {
cameraDevice.createCaptureSession(outputs, callback, backgroundHandler);
}
@Override
public void close() {
cameraDevice.close();
}
}
public Camera(
final Activity activity,
final SurfaceTextureEntry flutterTexture,
final CameraFeatureFactory cameraFeatureFactory,
final DartMessenger dartMessenger,
final CameraProperties cameraProperties,
final ResolutionPreset resolutionPreset,
final boolean enableAudio) {
if (activity == null) {
throw new IllegalStateException("No activity available!");
}
this.activity = activity;
this.enableAudio = enableAudio;
this.flutterTexture = flutterTexture;
this.dartMessenger = dartMessenger;
this.applicationContext = activity.getApplicationContext();
this.cameraProperties = cameraProperties;
this.cameraFeatureFactory = cameraFeatureFactory;
this.resolutionPreset = resolutionPreset;
this.cameraFeatures =
CameraFeatures.init(
cameraFeatureFactory, cameraProperties, activity, dartMessenger, resolutionPreset);
// Create capture callback.
captureTimeouts = new CaptureTimeoutsWrapper(3000, 3000);
captureProps = new CameraCaptureProperties();
cameraCaptureCallback = CameraCaptureCallback.create(this, captureTimeouts, captureProps);
startBackgroundThread();
}
@Override
public void onConverged() {
takePictureAfterPrecapture();
}
@Override
public void onPrecapture() {
runPrecaptureSequence();
}
/**
* Updates the builder settings with all of the available features.
*
* @param requestBuilder request builder to update.
*/
void updateBuilderSettings(CaptureRequest.Builder requestBuilder) {
for (CameraFeature<?> feature : cameraFeatures.getAllFeatures()) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Updating builder with feature: " + feature.getDebugName());
}
feature.updateBuilder(requestBuilder);
}
}
private void prepareMediaRecorder(String outputFilePath) throws IOException {
Log.i(TAG, "prepareMediaRecorder");
if (mediaRecorder != null) {
mediaRecorder.release();
}
closeRenderer();
final PlatformChannel.DeviceOrientation lockedOrientation =
cameraFeatures.getSensorOrientation().getLockedCaptureOrientation();
MediaRecorderBuilder mediaRecorderBuilder;
// TODO(camsim99): Revert changes that allow legacy code to be used when recordingProfile is null
// once this has largely been fixed on the Android side. https://github.com/flutter/flutter/issues/119668
if (SdkCapabilityChecker.supportsEncoderProfiles() && getRecordingProfile() != null) {
mediaRecorderBuilder = new MediaRecorderBuilder(getRecordingProfile(), outputFilePath);
} else {
mediaRecorderBuilder = new MediaRecorderBuilder(getRecordingProfileLegacy(), outputFilePath);
}
mediaRecorder =
mediaRecorderBuilder
.setEnableAudio(enableAudio)
.setMediaOrientation(
lockedOrientation == null
? getDeviceOrientationManager().getVideoOrientation()
: getDeviceOrientationManager().getVideoOrientation(lockedOrientation))
.build();
}
@SuppressLint("MissingPermission")
public void open(String imageFormatGroup) throws CameraAccessException {
this.imageFormatGroup = imageFormatGroup;
final ResolutionFeature resolutionFeature = cameraFeatures.getResolution();
if (!resolutionFeature.checkIsSupported()) {
// Tell the user that the camera they are trying to open is not supported,
// as its {@link android.media.CamcorderProfile} cannot be fetched due to the name
// not being a valid parsable integer.
dartMessenger.sendCameraErrorEvent(
"Camera with name \""
+ cameraProperties.getCameraName()
+ "\" is not supported by this plugin.");
return;
}
// Always capture using JPEG format.
pictureImageReader =
ImageReader.newInstance(
resolutionFeature.getCaptureSize().getWidth(),
resolutionFeature.getCaptureSize().getHeight(),
ImageFormat.JPEG,
1);
// For image streaming, use the provided image format or fall back to YUV420.
Integer imageFormat = supportedImageFormats.get(imageFormatGroup);
if (imageFormat == null) {
Log.w(TAG, "The selected imageFormatGroup is not supported by Android. Defaulting to yuv420");
imageFormat = ImageFormat.YUV_420_888;
}
imageStreamReader =
new ImageStreamReader(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight(),
imageFormat,
1);
// Open the camera.
CameraManager cameraManager = CameraUtils.getCameraManager(activity);
cameraManager.openCamera(
cameraProperties.getCameraName(),
new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice device) {
cameraDevice = new DefaultCameraDeviceWrapper(device);
try {
startPreview();
if (!recordingVideo) { // only send initialization if we werent already recording and switching cameras
dartMessenger.sendCameraInitializedEvent(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight(),
cameraFeatures.getExposureLock().getValue(),
cameraFeatures.getAutoFocus().getValue(),
cameraFeatures.getExposurePoint().checkIsSupported(),
cameraFeatures.getFocusPoint().checkIsSupported());
}
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.i(TAG, "open | onOpened error: " + e.getMessage());
}
dartMessenger.sendCameraErrorEvent(e.getMessage());
close();
}
}
@Override
public void onClosed(@NonNull CameraDevice camera) {
Log.i(TAG, "open | onClosed");
// Prevents calls to methods that would otherwise result in IllegalStateException
// exceptions.
cameraDevice = null;
closeCaptureSession();
dartMessenger.sendCameraClosingEvent();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
Log.i(TAG, "open | onDisconnected");
close();
dartMessenger.sendCameraErrorEvent("The camera was disconnected.");
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int errorCode) {
Log.i(TAG, "open | onError");
close();
String errorDescription;
switch (errorCode) {
case ERROR_CAMERA_IN_USE:
errorDescription = "The camera device is in use already.";
break;
case ERROR_MAX_CAMERAS_IN_USE:
errorDescription = "Max cameras in use";
break;
case ERROR_CAMERA_DISABLED:
errorDescription = "The camera device could not be opened due to a device policy.";
break;
case ERROR_CAMERA_DEVICE:
errorDescription = "The camera device has encountered a fatal error";
break;
case ERROR_CAMERA_SERVICE:
errorDescription = "The camera service has encountered a fatal error.";
break;
default:
errorDescription = "Unknown camera error";
}
dartMessenger.sendCameraErrorEvent(errorDescription);
}
},
backgroundHandler);
}
@VisibleForTesting
void createCaptureSession(int templateType, Surface... surfaces) throws CameraAccessException {
createCaptureSession(templateType, null, surfaces);
}
private void createCaptureSession(
int templateType, Runnable onSuccessCallback, Surface... surfaces)
throws CameraAccessException {
// Close any existing capture session.
captureSession = null;
// Create a new capture builder.
previewRequestBuilder = cameraDevice.createCaptureRequest(templateType);
// Build Flutter surface to render to.
ResolutionFeature resolutionFeature = cameraFeatures.getResolution();
SurfaceTexture surfaceTexture = flutterTexture.surfaceTexture();
surfaceTexture.setDefaultBufferSize(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight());
Surface flutterSurface = new Surface(surfaceTexture);
previewRequestBuilder.addTarget(flutterSurface);
List<Surface> remainingSurfaces = Arrays.asList(surfaces);
if (templateType != CameraDevice.TEMPLATE_PREVIEW) {
// If it is not preview mode, add all surfaces as targets
// except the surface used for still capture as this should
// not be part of a repeating request.
Surface pictureImageReaderSurface = pictureImageReader.getSurface();
for (Surface surface : remainingSurfaces) {
if (surface == pictureImageReaderSurface) {
continue;
}
previewRequestBuilder.addTarget(surface);
}
}
// Update camera regions.
Size cameraBoundaries =
CameraRegionUtils.getCameraBoundaries(cameraProperties, previewRequestBuilder);
cameraFeatures.getExposurePoint().setCameraBoundaries(cameraBoundaries);
cameraFeatures.getFocusPoint().setCameraBoundaries(cameraBoundaries);
// Prepare the callback.
CameraCaptureSession.StateCallback callback =
new CameraCaptureSession.StateCallback() {
boolean captureSessionClosed = false;
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
Log.i(TAG, "CameraCaptureSession onConfigured");
// Camera was already closed.
if (cameraDevice == null || captureSessionClosed) {
dartMessenger.sendCameraErrorEvent("The camera was closed during configuration.");
return;
}
captureSession = session;
Log.i(TAG, "Updating builder settings");
updateBuilderSettings(previewRequestBuilder);
refreshPreviewCaptureSession(
onSuccessCallback, (code, message) -> dartMessenger.sendCameraErrorEvent(message));
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.i(TAG, "CameraCaptureSession onConfigureFailed");
dartMessenger.sendCameraErrorEvent("Failed to configure camera session.");
}
@Override
public void onClosed(@NonNull CameraCaptureSession session) {
Log.i(TAG, "CameraCaptureSession onClosed");
captureSessionClosed = true;
}
};
// Start the session.
if (SdkCapabilityChecker.supportsSessionConfiguration()) {
// Collect all surfaces to render to.
List<OutputConfiguration> configs = new ArrayList<>();
configs.add(new OutputConfiguration(flutterSurface));
for (Surface surface : remainingSurfaces) {
configs.add(new OutputConfiguration(surface));
}
createCaptureSessionWithSessionConfig(configs, callback);
} else {
// Collect all surfaces to render to.
List<Surface> surfaceList = new ArrayList<>();
surfaceList.add(flutterSurface);
surfaceList.addAll(remainingSurfaces);
createCaptureSession(surfaceList, callback);
}
}
@TargetApi(VERSION_CODES.P)
private void createCaptureSessionWithSessionConfig(
List<OutputConfiguration> outputConfigs, CameraCaptureSession.StateCallback callback)
throws CameraAccessException {
cameraDevice.createCaptureSession(
new SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
outputConfigs,
Executors.newSingleThreadExecutor(),
callback));
}
@SuppressWarnings("deprecation")
private void createCaptureSession(
List<Surface> surfaces, CameraCaptureSession.StateCallback callback)
throws CameraAccessException {
cameraDevice.createCaptureSession(surfaces, callback, backgroundHandler);
}
// Send a repeating request to refresh capture session.
void refreshPreviewCaptureSession(
@Nullable Runnable onSuccessCallback, @NonNull ErrorCallback onErrorCallback) {
Log.i(TAG, "refreshPreviewCaptureSession");
if (captureSession == null) {
Log.i(
TAG,
"refreshPreviewCaptureSession: captureSession not yet initialized, "
+ "skipping preview capture session refresh.");
return;
}
try {
if (!pausedPreview) {
captureSession.setRepeatingRequest(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
}
if (onSuccessCallback != null) {
onSuccessCallback.run();
}
} catch (IllegalStateException e) {
onErrorCallback.onError("cameraAccess", "Camera is closed: " + e.getMessage());
} catch (CameraAccessException e) {
onErrorCallback.onError("cameraAccess", e.getMessage());
}
}
private void startCapture(boolean record, boolean stream) throws CameraAccessException {
List<Surface> surfaces = new ArrayList<>();
Runnable successCallback = null;
if (record) {
surfaces.add(mediaRecorder.getSurface());
successCallback = () -> mediaRecorder.start();
}
if (stream && imageStreamReader != null) {
surfaces.add(imageStreamReader.getSurface());
}
// Add pictureImageReader surface to allow for still capture
// during recording/image streaming.
surfaces.add(pictureImageReader.getSurface());
createCaptureSession(
CameraDevice.TEMPLATE_RECORD, successCallback, surfaces.toArray(new Surface[0]));
}
public void takePicture(@NonNull final Result result) {
// Only take one picture at a time.
if (cameraCaptureCallback.getCameraState() != CameraState.STATE_PREVIEW) {
result.error("captureAlreadyActive", "Picture is currently already being captured", null);
return;
}
flutterResult = result;
// Create temporary file.
final File outputDir = applicationContext.getCacheDir();
try {
captureFile = File.createTempFile("CAP", ".jpg", outputDir);
captureTimeouts.reset();
} catch (IOException | SecurityException e) {
dartMessenger.error(flutterResult, "cannotCreateFile", e.getMessage(), null);
return;
}
// Listen for picture being taken.
pictureImageReader.setOnImageAvailableListener(this, backgroundHandler);
final AutoFocusFeature autoFocusFeature = cameraFeatures.getAutoFocus();
final boolean isAutoFocusSupported = autoFocusFeature.checkIsSupported();
if (isAutoFocusSupported && autoFocusFeature.getValue() == FocusMode.auto) {
runPictureAutoFocus();
} else {
runPrecaptureSequence();
}
}
/**
* Run the precapture sequence for capturing a still image. This method should be called when a
* response is received in {@link #cameraCaptureCallback} from lockFocus().
*/
private void runPrecaptureSequence() {
Log.i(TAG, "runPrecaptureSequence");
try {
// First set precapture state to idle or else it can hang in STATE_WAITING_PRECAPTURE_START.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE);
captureSession.capture(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
// Repeating request to refresh preview session.
refreshPreviewCaptureSession(
null,
(code, message) -> dartMessenger.error(flutterResult, "cameraAccess", message, null));
// Start precapture.
cameraCaptureCallback.setCameraState(CameraState.STATE_WAITING_PRECAPTURE_START);
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
// Trigger one capture to start AE sequence.
captureSession.capture(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Capture a still picture. This method should be called when a response is received {@link
* #cameraCaptureCallback} from both lockFocus().
*/
private void takePictureAfterPrecapture() {
Log.i(TAG, "captureStillPicture");
cameraCaptureCallback.setCameraState(CameraState.STATE_CAPTURING);
if (cameraDevice == null) {
return;
}
// This is the CaptureRequest.Builder that is used to take a picture.
CaptureRequest.Builder stillBuilder;
try {
stillBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
} catch (CameraAccessException e) {
dartMessenger.error(flutterResult, "cameraAccess", e.getMessage(), null);
return;
}
stillBuilder.addTarget(pictureImageReader.getSurface());
// Zoom.
stillBuilder.set(
CaptureRequest.SCALER_CROP_REGION,
previewRequestBuilder.get(CaptureRequest.SCALER_CROP_REGION));
// Have all features update the builder.
updateBuilderSettings(stillBuilder);
// Orientation.
final PlatformChannel.DeviceOrientation lockedOrientation =
cameraFeatures.getSensorOrientation().getLockedCaptureOrientation();
stillBuilder.set(
CaptureRequest.JPEG_ORIENTATION,
lockedOrientation == null
? getDeviceOrientationManager().getPhotoOrientation()
: getDeviceOrientationManager().getPhotoOrientation(lockedOrientation));
CameraCaptureSession.CaptureCallback captureCallback =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(
@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
unlockAutoFocus();
}
};
try {
Log.i(TAG, "sending capture request");
captureSession.capture(stillBuilder.build(), captureCallback, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.error(flutterResult, "cameraAccess", e.getMessage(), null);
}
}
@SuppressWarnings("deprecation")
private Display getDefaultDisplay() {
return activity.getWindowManager().getDefaultDisplay();
}
/** Starts a background thread and its {@link Handler}. */
public void startBackgroundThread() {
if (backgroundHandlerThread != null) {
return;
}
backgroundHandlerThread = HandlerThreadFactory.create("CameraBackground");
try {
backgroundHandlerThread.start();
} catch (IllegalThreadStateException e) {
// Ignore exception in case the thread has already started.
}
backgroundHandler = HandlerFactory.create(backgroundHandlerThread.getLooper());
}
/** Stops the background thread and its {@link Handler}. */
public void stopBackgroundThread() {
if (backgroundHandlerThread != null) {
backgroundHandlerThread.quitSafely();
}
backgroundHandlerThread = null;
backgroundHandler = null;
}
/** Start capturing a picture, doing autofocus first. */
private void runPictureAutoFocus() {
Log.i(TAG, "runPictureAutoFocus");
cameraCaptureCallback.setCameraState(CameraState.STATE_WAITING_FOCUS);
lockAutoFocus();
}
private void lockAutoFocus() {
Log.i(TAG, "lockAutoFocus");
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
// Trigger AF to start.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
try {
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.sendCameraErrorEvent(e.getMessage());
}
}
/** Cancel and reset auto focus state and refresh the preview session. */
void unlockAutoFocus() {
Log.i(TAG, "unlockAutoFocus");
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
try {
// Cancel existing AF state.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
// Set AF state to idle again.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.sendCameraErrorEvent(e.getMessage());
return;
}
refreshPreviewCaptureSession(
null,
(errorCode, errorMessage) ->
dartMessenger.error(flutterResult, errorCode, errorMessage, null));
}
public void startVideoRecording(
@NonNull Result result, @Nullable EventChannel imageStreamChannel) {
prepareRecording(result);
if (imageStreamChannel != null) {
setStreamHandler(imageStreamChannel);
}
initialCameraFacing = cameraProperties.getLensFacing();
recordingVideo = true;
try {
startCapture(true, imageStreamChannel != null);
result.success(null);
} catch (CameraAccessException e) {
recordingVideo = false;
captureFile = null;
result.error("videoRecordingFailed", e.getMessage(), null);
}
}
private void closeRenderer() {
if (videoRenderer != null) {
videoRenderer.close();
videoRenderer = null;
}
}
public void stopVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
// Re-create autofocus feature so it's using continuous capture focus mode now.
cameraFeatures.setAutoFocus(
cameraFeatureFactory.createAutoFocusFeature(cameraProperties, false));
recordingVideo = false;
try {
closeRenderer();
captureSession.abortCaptures();
mediaRecorder.stop();
} catch (CameraAccessException | IllegalStateException e) {
// Ignore exceptions and try to continue (changes are camera session already aborted capture).
}
mediaRecorder.reset();
try {
startPreview();
} catch (CameraAccessException | IllegalStateException | InterruptedException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(captureFile.getAbsolutePath());
captureFile = null;
}
public void pauseVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
try {
if (SdkCapabilityChecker.supportsVideoPause()) {
mediaRecorder.pause();
} else {
result.error("videoRecordingFailed", "pauseVideoRecording requires Android API +24.", null);
return;
}
} catch (IllegalStateException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(null);
}
public void resumeVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
try {
if (SdkCapabilityChecker.supportsVideoPause()) {
mediaRecorder.resume();
} else {
result.error(
"videoRecordingFailed", "resumeVideoRecording requires Android API +24.", null);
return;
}
} catch (IllegalStateException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(null);
}
/**
* Method handler for setting new flash modes.
*
* @param result Flutter result.
* @param newMode new mode.
*/
public void setFlashMode(@NonNull final Result result, @NonNull FlashMode newMode) {
// Save the new flash mode setting.
final FlashFeature flashFeature = cameraFeatures.getFlash();
flashFeature.setValue(newMode);
flashFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setFlashModeFailed", "Could not set flash mode.", null));
}
/**
* Method handler for setting new exposure modes.
*
* @param result Flutter result.
* @param newMode new mode.
*/
public void setExposureMode(@NonNull final Result result, @NonNull ExposureMode newMode) {
final ExposureLockFeature exposureLockFeature = cameraFeatures.getExposureLock();
exposureLockFeature.setValue(newMode);
exposureLockFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) ->
result.error("setExposureModeFailed", "Could not set exposure mode.", null));
}
/**
* Sets new exposure point from dart.
*
* @param result Flutter result.
* @param point The exposure point.
*/
public void setExposurePoint(@NonNull final Result result, @Nullable Point point) {
final ExposurePointFeature exposurePointFeature = cameraFeatures.getExposurePoint();
exposurePointFeature.setValue(point);
exposurePointFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) ->
result.error("setExposurePointFailed", "Could not set exposure point.", null));
}
/** Return the max exposure offset value supported by the camera to dart. */
public double getMaxExposureOffset() {
return cameraFeatures.getExposureOffset().getMaxExposureOffset();
}
/** Return the min exposure offset value supported by the camera to dart. */
public double getMinExposureOffset() {
return cameraFeatures.getExposureOffset().getMinExposureOffset();
}
/** Return the exposure offset step size to dart. */
public double getExposureOffsetStepSize() {
return cameraFeatures.getExposureOffset().getExposureOffsetStepSize();
}
/**
* Sets new focus mode from dart.
*
* @param result Flutter result.
* @param newMode New mode.
*/
public void setFocusMode(final Result result, @NonNull FocusMode newMode) {
final AutoFocusFeature autoFocusFeature = cameraFeatures.getAutoFocus();
autoFocusFeature.setValue(newMode);
autoFocusFeature.updateBuilder(previewRequestBuilder);
/*
* For focus mode an extra step of actually locking/unlocking the
* focus has to be done, in order to ensure it goes into the correct state.
*/
if (!pausedPreview) {
switch (newMode) {
case locked:
// Perform a single focus trigger.
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
lockAutoFocus();
// Set AF state to idle again.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
try {
captureSession.setRepeatingRequest(
previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
if (result != null) {
result.error(
"setFocusModeFailed", "Error setting focus mode: " + e.getMessage(), null);
}
return;
}
break;
case auto:
// Cancel current AF trigger and set AF to idle again.
unlockAutoFocus();
break;
}
}
if (result != null) {
result.success(null);
}
}
/**
* Sets new focus point from dart.
*
* @param result Flutter result.
* @param point the new coordinates.
*/
public void setFocusPoint(@NonNull final Result result, @Nullable Point point) {
final FocusPointFeature focusPointFeature = cameraFeatures.getFocusPoint();
focusPointFeature.setValue(point);
focusPointFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setFocusPointFailed", "Could not set focus point.", null));
this.setFocusMode(null, cameraFeatures.getAutoFocus().getValue());
}
/**
* Sets a new exposure offset from dart. From dart the offset comes as a double, like +1.3 or
* -1.3.
*
* @param result flutter result.
* @param offset new value.
*/
public void setExposureOffset(@NonNull final Result result, double offset) {
final ExposureOffsetFeature exposureOffsetFeature = cameraFeatures.getExposureOffset();
exposureOffsetFeature.setValue(offset);
exposureOffsetFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(exposureOffsetFeature.getValue()),
(code, message) ->
result.error("setExposureOffsetFailed", "Could not set exposure offset.", null));
}
public float getMaxZoomLevel() {
return cameraFeatures.getZoomLevel().getMaximumZoomLevel();
}
public float getMinZoomLevel() {
return cameraFeatures.getZoomLevel().getMinimumZoomLevel();
}
/** Shortcut to get current recording profile. Legacy method provides support for SDK < 31. */
CamcorderProfile getRecordingProfileLegacy() {
return cameraFeatures.getResolution().getRecordingProfileLegacy();
}
EncoderProfiles getRecordingProfile() {
return cameraFeatures.getResolution().getRecordingProfile();
}
/** Shortut to get deviceOrientationListener. */
DeviceOrientationManager getDeviceOrientationManager() {
return cameraFeatures.getSensorOrientation().getDeviceOrientationManager();
}
/**
* Sets zoom level from dart.
*
* @param result Flutter result.
* @param zoom new value.
*/
public void setZoomLevel(@NonNull final Result result, float zoom) throws CameraAccessException {
final ZoomLevelFeature zoomLevel = cameraFeatures.getZoomLevel();
float maxZoom = zoomLevel.getMaximumZoomLevel();
float minZoom = zoomLevel.getMinimumZoomLevel();
if (zoom > maxZoom || zoom < minZoom) {
String errorMessage =
String.format(
Locale.ENGLISH,
"Zoom level out of bounds (zoom level should be between %f and %f).",
minZoom,
maxZoom);
result.error("ZOOM_ERROR", errorMessage, null);
return;
}
zoomLevel.setValue(zoom);
zoomLevel.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setZoomLevelFailed", "Could not set zoom level.", null));
}
/**
* Lock capture orientation from dart.
*
* @param orientation new orientation.
*/
public void lockCaptureOrientation(PlatformChannel.DeviceOrientation orientation) {
cameraFeatures.getSensorOrientation().lockCaptureOrientation(orientation);
}
/** Unlock capture orientation from dart. */
public void unlockCaptureOrientation() {
cameraFeatures.getSensorOrientation().unlockCaptureOrientation();
}
/** Pause the preview from dart. */
public void pausePreview() throws CameraAccessException {
if (!this.pausedPreview) {
this.pausedPreview = true;
if (this.captureSession != null) {
this.captureSession.stopRepeating();
}
}
}
/** Resume the preview from dart. */
public void resumePreview() {
this.pausedPreview = false;
this.refreshPreviewCaptureSession(
null, (code, message) -> dartMessenger.sendCameraErrorEvent(message));
}
public void startPreview() throws CameraAccessException, InterruptedException {
// If recording is already in progress, the camera is being flipped, so send it through the VideoRenderer to keep the correct orientation.
if (recordingVideo) {
startPreviewWithVideoRendererStream();
} else {
startRegularPreview();
}
}
private void startRegularPreview() throws CameraAccessException {
if (pictureImageReader == null || pictureImageReader.getSurface() == null) return;
Log.i(TAG, "startPreview");
createCaptureSession(CameraDevice.TEMPLATE_PREVIEW, pictureImageReader.getSurface());
}
private void startPreviewWithVideoRendererStream()
throws CameraAccessException, InterruptedException {
if (videoRenderer == null) return;
// get rotation for rendered video
final PlatformChannel.DeviceOrientation lockedOrientation =
cameraFeatures.getSensorOrientation().getLockedCaptureOrientation();
DeviceOrientationManager orientationManager =
cameraFeatures.getSensorOrientation().getDeviceOrientationManager();
int rotation = 0;
if (orientationManager != null) {
rotation =
lockedOrientation == null
? orientationManager.getVideoOrientation()
: orientationManager.getVideoOrientation(lockedOrientation);
}
if (cameraProperties.getLensFacing() != initialCameraFacing) {
// If the new camera is facing the opposite way than the initial recording,
// the rotation should be flipped 180 degrees.
rotation = (rotation + 180) % 360;
}
videoRenderer.setRotation(rotation);
createCaptureSession(CameraDevice.TEMPLATE_RECORD, videoRenderer.getInputSurface());
}
public void startPreviewWithImageStream(EventChannel imageStreamChannel)
throws CameraAccessException {
setStreamHandler(imageStreamChannel);
startCapture(false, true);
Log.i(TAG, "startPreviewWithImageStream");
}
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
@Override
public void onImageAvailable(ImageReader reader) {
Log.i(TAG, "onImageAvailable");
// Use acquireNextImage since image reader is only for one image.
Image image = reader.acquireNextImage();
if (image == null) {
return;
}
backgroundHandler.post(
new ImageSaver(
image,
captureFile,
new ImageSaver.Callback() {
@Override
public void onComplete(String absolutePath) {
dartMessenger.finish(flutterResult, absolutePath);
}
@Override
public void onError(String errorCode, String errorMessage) {
dartMessenger.error(flutterResult, errorCode, errorMessage, null);
}
}));
cameraCaptureCallback.setCameraState(CameraState.STATE_PREVIEW);
}
@VisibleForTesting
void prepareRecording(@NonNull Result result) {
final File outputDir = applicationContext.getCacheDir();
try {
captureFile = File.createTempFile("REC", ".mp4", outputDir);
} catch (IOException | SecurityException e) {
result.error("cannotCreateFile", e.getMessage(), null);
return;
}
try {
prepareMediaRecorder(captureFile.getAbsolutePath());
} catch (IOException e) {
recordingVideo = false;
captureFile = null;
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
// Re-create autofocus feature so it's using video focus mode now.
cameraFeatures.setAutoFocus(
cameraFeatureFactory.createAutoFocusFeature(cameraProperties, true));
}
private void setStreamHandler(EventChannel imageStreamChannel) {
imageStreamChannel.setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink imageStreamSink) {
setImageStreamImageAvailableListener(imageStreamSink);
}
@Override
public void onCancel(Object o) {
if (imageStreamReader == null) {
return;
}
imageStreamReader.removeListener(backgroundHandler);
}
});
}
void setImageStreamImageAvailableListener(final EventChannel.EventSink imageStreamSink) {
if (imageStreamReader == null) {
return;
}
imageStreamReader.subscribeListener(this.captureProps, imageStreamSink, backgroundHandler);
}
void closeCaptureSession() {
if (captureSession != null) {
Log.i(TAG, "closeCaptureSession");
captureSession.close();
captureSession = null;
}
}
public void close() {
Log.i(TAG, "close");
stopAndReleaseCamera();
if (pictureImageReader != null) {
pictureImageReader.close();
pictureImageReader = null;
}
if (imageStreamReader != null) {
imageStreamReader.close();
imageStreamReader = null;
}
if (mediaRecorder != null) {
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
}
stopBackgroundThread();
}
private void stopAndReleaseCamera() {
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
// Closing the CameraDevice without closing the CameraCaptureSession is recommended
// for quickly closing the camera:
// https://developer.android.com/reference/android/hardware/camera2/CameraCaptureSession#close()
captureSession = null;
} else {
closeCaptureSession();
}
}
private void prepareVideoRenderer() {
if (videoRenderer != null) return;
final ResolutionFeature resolutionFeature = cameraFeatures.getResolution();
// handle videoRenderer errors
Thread.UncaughtExceptionHandler videoRendererUncaughtExceptionHandler =
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
dartMessenger.sendCameraErrorEvent(
"Failed to process frames after camera was flipped.");
}
};
videoRenderer =
new VideoRenderer(
mediaRecorder.getSurface(),
resolutionFeature.getCaptureSize().getWidth(),
resolutionFeature.getCaptureSize().getHeight(),
videoRendererUncaughtExceptionHandler);
}
public void setDescriptionWhileRecording(
@NonNull final Result result, CameraProperties properties) {
if (!recordingVideo) {
result.error("setDescriptionWhileRecordingFailed", "Device was not recording", null);
return;
}
// See VideoRenderer.java; support for this EGL extension is required to switch camera while recording.
if (!SdkCapabilityChecker.supportsEglRecordableAndroid()) {
result.error(
"setDescriptionWhileRecordingFailed",
"Device does not support switching the camera while recording",
null);
return;
}
stopAndReleaseCamera();
prepareVideoRenderer();
cameraProperties = properties;
cameraFeatures =
CameraFeatures.init(
cameraFeatureFactory, cameraProperties, activity, dartMessenger, resolutionPreset);
cameraFeatures.setAutoFocus(
cameraFeatureFactory.createAutoFocusFeature(cameraProperties, true));
try {
open(imageFormatGroup);
} catch (CameraAccessException e) {
result.error("setDescriptionWhileRecordingFailed", e.getMessage(), null);
}
result.success(null);
}
public void dispose() {
Log.i(TAG, "dispose");
close();
flutterTexture.release();
getDeviceOrientationManager().stop();
}
/** Factory class that assists in creating a {@link HandlerThread} instance. */
static class HandlerThreadFactory {
/**
* Creates a new instance of the {@link HandlerThread} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param name to give to the HandlerThread.
* @return new instance of the {@link HandlerThread} class.
*/
@VisibleForTesting
public static HandlerThread create(String name) {
return new HandlerThread(name);
}
}
/** Factory class that assists in creating a {@link Handler} instance. */
static class HandlerFactory {
/**
* Creates a new instance of the {@link Handler} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param looper to give to the Handler.
* @return new instance of the {@link Handler} class.
*/
@VisibleForTesting
public static Handler create(Looper looper) {
return new Handler(looper);
}
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/Camera.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/Camera.java",
"repo_id": "packages",
"token_count": 16534
} | 984 |
name: camera_android
description: Android implementation of the camera plugin.
repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
version: 0.10.8+17
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: camera
platforms:
android:
package: io.flutter.plugins.camera
pluginClass: CameraPlugin
dartPluginClass: AndroidCamera
dependencies:
camera_platform_interface: ^2.5.0
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.2
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
topics:
- camera
| packages/packages/camera/camera_android/pubspec.yaml/0 | {
"file_path": "packages/packages/camera/camera_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 311
} | 985 |
// 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 androidx.annotation.VisibleForTesting;
import androidx.camera.core.resolutionselector.AspectRatioStrategy;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AspectRatioStrategyHostApi;
/**
* Host API implementation for {@link AspectRatioStrategy}.
*
* <p>This class handles instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class AspectRatioStrategyHostApiImpl implements AspectRatioStrategyHostApi {
private final InstanceManager instanceManager;
private final AspectRatioStrategyProxy proxy;
/** Proxy for constructor of {@link AspectRatioStrategy}. */
@VisibleForTesting
public static class AspectRatioStrategyProxy {
/** Creates an instance of {@link AspectRatioStrategy}. */
@NonNull
public AspectRatioStrategy create(
@NonNull Long preferredAspectRatio, @NonNull Long fallbackRule) {
return new AspectRatioStrategy(preferredAspectRatio.intValue(), fallbackRule.intValue());
}
}
/**
* Constructs an {@link AspectRatioStrategyHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public AspectRatioStrategyHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new AspectRatioStrategyProxy());
}
/**
* Constructs an {@link AspectRatioStrategyHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor of {@link AspectRatioStrategy}
*/
@VisibleForTesting
AspectRatioStrategyHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull AspectRatioStrategyProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
/**
* Creates an {@link AspectRatioStrategy} instance with the preferred aspect ratio and fallback
* rule specified.
*/
@Override
public void create(
@NonNull Long identifier, @NonNull Long preferredAspectRatio, @NonNull Long fallbackRule) {
instanceManager.addDartCreatedInstance(
proxy.create(preferredAspectRatio, fallbackRule), identifier);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java",
"repo_id": "packages",
"token_count": 746
} | 986 |
// 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.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation;
/**
* Support class to help to determine the media orientation based on the orientation of the device.
*/
public class DeviceOrientationManager {
interface DeviceOrientationChangeCallback {
void onChange(DeviceOrientation newOrientation);
}
private static final IntentFilter orientationIntentFilter =
new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED);
private final Activity activity;
private final boolean isFrontFacing;
private final int sensorOrientation;
private final DeviceOrientationChangeCallback deviceOrientationChangeCallback;
private PlatformChannel.DeviceOrientation lastOrientation;
private BroadcastReceiver broadcastReceiver;
DeviceOrientationManager(
@NonNull Activity activity,
boolean isFrontFacing,
int sensorOrientation,
DeviceOrientationChangeCallback callback) {
this.activity = activity;
this.isFrontFacing = isFrontFacing;
this.sensorOrientation = sensorOrientation;
this.deviceOrientationChangeCallback = callback;
}
/**
* Starts listening to the device's sensors or UI for orientation updates.
*
* <p>When orientation information is updated, the callback method of the {@link
* DeviceOrientationChangeCallback} is called with the new orientation. This latest value can also
* be retrieved through the {@link #getVideoOrientation()} accessor.
*
* <p>If the device's ACCELEROMETER_ROTATION setting is enabled the {@link
* DeviceOrientationManager} will report orientation updates based on the sensor information. If
* the ACCELEROMETER_ROTATION is disabled the {@link DeviceOrientationManager} will fallback to
* the deliver orientation updates based on the UI orientation.
*/
public void start() {
if (broadcastReceiver != null) {
return;
}
broadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleUIOrientationChange();
}
};
activity.registerReceiver(broadcastReceiver, orientationIntentFilter);
broadcastReceiver.onReceive(activity, null);
}
/** Stops listening for orientation updates. */
public void stop() {
if (broadcastReceiver == null) {
return;
}
activity.unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
/**
* Handles orientation changes based on change events triggered by the OrientationIntentFilter.
*
* <p>This method is visible for testing purposes only and should never be used outside this
* class.
*/
@VisibleForTesting
void handleUIOrientationChange() {
PlatformChannel.DeviceOrientation orientation = getUIOrientation();
handleOrientationChange(orientation, lastOrientation, deviceOrientationChangeCallback);
lastOrientation = orientation;
}
/**
* Handles orientation changes coming from either the device's sensors or the
* OrientationIntentFilter.
*
* <p>This method is visible for testing purposes only and should never be used outside this
* class.
*/
@VisibleForTesting
static void handleOrientationChange(
DeviceOrientation newOrientation,
DeviceOrientation previousOrientation,
DeviceOrientationChangeCallback callback) {
if (!newOrientation.equals(previousOrientation)) {
callback.onChange(newOrientation);
}
}
/**
* Gets the current user interface orientation.
*
* <p>This method is visible for testing purposes only and should never be used outside this
* class.
*
* @return The current user interface orientation.
*/
// Configuration.ORIENTATION_SQUARE is deprecated.
@SuppressWarnings("deprecation")
@VisibleForTesting
PlatformChannel.DeviceOrientation getUIOrientation() {
final int rotation = getDefaultRotation();
final int orientation = activity.getResources().getConfiguration().orientation;
switch (orientation) {
case Configuration.ORIENTATION_PORTRAIT:
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
return PlatformChannel.DeviceOrientation.PORTRAIT_UP;
} else {
return PlatformChannel.DeviceOrientation.PORTRAIT_DOWN;
}
case Configuration.ORIENTATION_LANDSCAPE:
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
return PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT;
} else {
return PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT;
}
case Configuration.ORIENTATION_SQUARE:
case Configuration.ORIENTATION_UNDEFINED:
default:
return PlatformChannel.DeviceOrientation.PORTRAIT_UP;
}
}
/**
* Gets default capture rotation for CameraX {@code UseCase}s.
*
* <p>See
* https://developer.android.com/reference/androidx/camera/core/ImageCapture#setTargetRotation(int),
* for instance.
*
* @return The rotation of the screen from its "natural" orientation; one of {@code
* Surface.ROTATION_0}, {@code Surface.ROTATION_90}, {@code Surface.ROTATION_180}, {@code
* Surface.ROTATION_270}
*/
int getDefaultRotation() {
return getDisplay().getRotation();
}
/**
* Gets an instance of the Android {@link android.view.Display}.
*
* <p>This method is visible for testing purposes only and should never be used outside this
* class.
*
* @return An instance of the Android {@link android.view.Display}.
*/
@SuppressWarnings("deprecation")
@VisibleForTesting
Display getDisplay() {
return ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java",
"repo_id": "packages",
"token_count": 2039
} | 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.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraState;
import androidx.camera.core.ZoomState;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataHostApi;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedTypeData;
import java.util.Objects;
/**
* Host API implementation for {@link LiveData}.
*
* <p>This class may handle instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class LiveDataHostApiImpl implements LiveDataHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
@Nullable private LifecycleOwner lifecycleOwner;
/**
* Constructs a {@link LiveDataHostApiImpl}.
*
* @param binaryMessenger used to communicate with Dart over asynchronous messages
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public LiveDataHostApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
/** Sets {@link LifecycleOwner} used to observe the camera state if so requested. */
public void setLifecycleOwner(@Nullable LifecycleOwner lifecycleOwner) {
this.lifecycleOwner = lifecycleOwner;
}
/**
* Adds an {@link Observer} with the specified identifier to the observers list of this instance
* within the lifespan of the {@link lifecycleOwner}.
*/
@Override
@SuppressWarnings("unchecked")
public void observe(@NonNull Long identifier, @NonNull Long observerIdentifier) {
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner must be set to observe a LiveData instance.");
}
getLiveDataInstance(identifier)
.observe(
lifecycleOwner,
Objects.requireNonNull(instanceManager.getInstance(observerIdentifier)));
}
/** Removes all observers of this instance that are tied to the {@link lifecycleOwner}. */
@Override
public void removeObservers(@NonNull Long identifier) {
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner must be set to remove LiveData observers.");
}
getLiveDataInstance(identifier).removeObservers(lifecycleOwner);
}
@Override
@Nullable
public Long getValue(@NonNull Long identifier, @NonNull LiveDataSupportedTypeData type) {
Object value = getLiveDataInstance(identifier).getValue();
if (value == null) {
return null;
}
LiveDataSupportedType valueType = type.getValue();
switch (valueType) {
case CAMERA_STATE:
return createCameraState((CameraState) value);
case ZOOM_STATE:
return createZoomState((ZoomState) value);
default:
throw new IllegalArgumentException(
"The type of LiveData whose value was requested is not supported.");
}
}
/** Creates a {@link CameraState} on the Dart side and returns its identifier. */
private Long createCameraState(CameraState cameraState) {
new CameraStateFlutterApiWrapper(binaryMessenger, instanceManager)
.create(
cameraState,
CameraStateFlutterApiWrapper.getCameraStateType(cameraState.getType()),
cameraState.getError(),
reply -> {});
return instanceManager.getIdentifierForStrongReference(cameraState);
}
/** Creates a {@link ZoomState} on the Dart side and returns its identifiers. */
private Long createZoomState(ZoomState zoomState) {
new ZoomStateFlutterApiImpl(binaryMessenger, instanceManager).create(zoomState, reply -> {});
return instanceManager.getIdentifierForStrongReference(zoomState);
}
/** Retrieves the {@link LiveData} instance that has the specified identifier. */
private LiveData<?> getLiveDataInstance(@NonNull Long identifier) {
return Objects.requireNonNull(instanceManager.getInstance(identifier));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java",
"repo_id": "packages",
"token_count": 1384
} | 988 |
// 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 androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.resolutionselector.AspectRatioStrategy;
import androidx.camera.core.resolutionselector.ResolutionSelector;
import androidx.camera.core.resolutionselector.ResolutionStrategy;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionSelectorHostApi;
import java.util.Objects;
/**
* Host API implementation for {@link ResolutionSelector}.
*
* <p>This class handles instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class ResolutionSelectorHostApiImpl implements ResolutionSelectorHostApi {
private final InstanceManager instanceManager;
private final ResolutionSelectorProxy proxy;
/** Proxy for constructor of {@link ResolutionSelector}. */
@VisibleForTesting
public static class ResolutionSelectorProxy {
/** Creates an instance of {@link ResolutionSelector}. */
@NonNull
public ResolutionSelector create(
@Nullable ResolutionStrategy resolutionStrategy,
@Nullable AspectRatioStrategy aspectRatioStrategy) {
final ResolutionSelector.Builder builder = new ResolutionSelector.Builder();
if (resolutionStrategy != null) {
builder.setResolutionStrategy(resolutionStrategy);
}
if (aspectRatioStrategy != null) {
builder.setAspectRatioStrategy(aspectRatioStrategy);
}
return builder.build();
}
}
/**
* Constructs a {@link ResolutionSelectorHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public ResolutionSelectorHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new ResolutionSelectorProxy());
}
/**
* Constructs a {@link ResolutionSelectorHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor of {@link ResolutionSelector}
*/
@VisibleForTesting
ResolutionSelectorHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull ResolutionSelectorProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
/**
* Creates a {@link ResolutionSelector} instance with the {@link ResolutionStrategy} and {@link
* AspectRatio} that have the identifiers specified if provided.
*/
@Override
public void create(
@NonNull Long identifier,
@Nullable Long resolutionStrategyIdentifier,
@Nullable Long aspectRatioStrategyIdentifier) {
instanceManager.addDartCreatedInstance(
proxy.create(
resolutionStrategyIdentifier == null
? null
: Objects.requireNonNull(instanceManager.getInstance(resolutionStrategyIdentifier)),
aspectRatioStrategyIdentifier == null
? null
: Objects.requireNonNull(
instanceManager.getInstance(aspectRatioStrategyIdentifier))),
identifier);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java",
"repo_id": "packages",
"token_count": 1057
} | 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.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import androidx.camera.core.CameraState;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateFlutterApi;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateTypeData;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class CameraStateTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public CameraState mockCameraState;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public CameraStateFlutterApi mockFlutterApi;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void flutterApiCreate_makesCallToDartToCreateInstance() {
final CameraStateFlutterApiWrapper flutterApi =
new CameraStateFlutterApiWrapper(mockBinaryMessenger, instanceManager);
flutterApi.setApi(mockFlutterApi);
final CameraStateType type = CameraStateType.OPEN;
final CameraState.StateError mockError = mock(CameraState.StateError.class);
flutterApi.create(mockCameraState, type, mockError, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockCameraState));
final ArgumentCaptor<CameraStateTypeData> cameraStateTypeDataCaptor =
ArgumentCaptor.forClass(CameraStateTypeData.class);
verify(mockFlutterApi)
.create(
eq(instanceIdentifier),
cameraStateTypeDataCaptor.capture(),
eq(Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockError))),
any());
assertEquals(cameraStateTypeDataCaptor.getValue().getValue(), type);
}
@Test
public void getCameraStateType_returnsExpectedType() {
for (CameraState.Type type : CameraState.Type.values()) {
switch (type) {
case CLOSED:
assertEquals(
CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.CLOSED);
break;
case CLOSING:
assertEquals(
CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.CLOSING);
break;
case OPEN:
assertEquals(CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.OPEN);
break;
case OPENING:
assertEquals(
CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.OPENING);
break;
case PENDING_OPEN:
assertEquals(
CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.PENDING_OPEN);
break;
default:
fail("The CameraState.Type " + type.toString() + " is unhandled by this test.");
}
}
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java",
"repo_id": "packages",
"token_count": 1352
} | 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.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.camera.core.CameraState;
import androidx.camera.core.ZoomState;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverFlutterApi;
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 ObserverTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public ObserverHostApiImpl.ObserverImpl<CameraState> mockObserver;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public ObserverFlutterApi mockFlutterApi;
@Mock public ObserverHostApiImpl.ObserverProxy mockProxy;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void create_createsObserverInstance() {
final ObserverHostApiImpl hostApi =
new ObserverHostApiImpl(mockBinaryMessenger, instanceManager, mockProxy);
final long instanceIdentifier = 0;
when(mockProxy.<CameraState>create(mockBinaryMessenger, instanceManager))
.thenReturn(mockObserver);
hostApi.create(instanceIdentifier);
assertEquals(instanceManager.getInstance(instanceIdentifier), mockObserver);
}
@Test
public void onChanged_makesExpectedCallToDartCallbackForCameraState() {
final ObserverFlutterApiWrapper flutterApi =
new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager);
final ObserverHostApiImpl.ObserverImpl<CameraState> instance =
new ObserverHostApiImpl.ObserverImpl<CameraState>(mockBinaryMessenger, instanceManager);
final CameraStateFlutterApiWrapper mockCameraStateFlutterApiWrapper =
mock(CameraStateFlutterApiWrapper.class);
final long instanceIdentifier = 60;
final CameraState.StateError testCameraStateError =
CameraState.StateError.create(CameraState.ERROR_CAMERA_IN_USE);
final CameraState testCameraState =
CameraState.create(CameraState.Type.CLOSED, testCameraStateError);
final Long mockCameraStateIdentifier = instanceManager.addHostCreatedInstance(testCameraState);
flutterApi.setApi(mockFlutterApi);
instance.setApi(flutterApi);
flutterApi.cameraStateFlutterApiWrapper = mockCameraStateFlutterApiWrapper;
instanceManager.addDartCreatedInstance(instance, instanceIdentifier);
instance.onChanged(testCameraState);
verify(mockFlutterApi)
.onChanged(
eq(instanceIdentifier), eq(Objects.requireNonNull(mockCameraStateIdentifier)), any());
verify(mockCameraStateFlutterApiWrapper)
.create(eq(testCameraState), eq(CameraStateType.CLOSED), eq(testCameraStateError), any());
}
@Test
public void onChanged_makesExpectedCallToDartCallbackForZoomState() {
final ObserverFlutterApiWrapper flutterApi =
new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager);
final ObserverHostApiImpl.ObserverImpl<ZoomState> instance =
new ObserverHostApiImpl.ObserverImpl<ZoomState>(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 2;
final ZoomStateFlutterApiImpl mockZoomStateFlutterApiImpl = mock(ZoomStateFlutterApiImpl.class);
final ZoomState mockZoomState = mock(ZoomState.class);
final Long mockZoomStateIdentifier = instanceManager.addHostCreatedInstance(mockZoomState);
flutterApi.setApi(mockFlutterApi);
instance.setApi(flutterApi);
flutterApi.zoomStateFlutterApiImpl = mockZoomStateFlutterApiImpl;
instanceManager.addDartCreatedInstance(instance, instanceIdentifier);
instance.onChanged(mockZoomState);
verify(mockFlutterApi).onChanged(eq(instanceIdentifier), eq(mockZoomStateIdentifier), any());
verify(mockZoomStateFlutterApiImpl).create(eq(mockZoomState), any());
}
@Test
public void onChanged_throwsExceptionForUnsupportedLiveDataType() {
final ObserverFlutterApiWrapper flutterApi =
new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager);
final ObserverHostApiImpl.ObserverImpl<Object> instance =
new ObserverHostApiImpl.ObserverImpl<Object>(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 2;
flutterApi.setApi(mockFlutterApi);
instance.setApi(flutterApi);
instanceManager.addDartCreatedInstance(instance, instanceIdentifier);
assertThrows(UnsupportedOperationException.class, () -> instance.onChanged(mock(Object.class)));
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java",
"repo_id": "packages",
"token_count": 1753
} | 991 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
namespace 'io.flutter.plugins.cameraxexample'
compileSdk flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "io.flutter.plugins.cameraxexample"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 21
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
api 'androidx.test:core:1.4.0'
}
| packages/packages/camera/camera_android_camerax/example/android/app/build.gradle/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/example/android/app/build.gradle",
"repo_id": "packages",
"token_count": 827
} | 992 |
// 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 'analyzer.dart';
import 'camera.dart';
import 'camera_control.dart';
import 'camera_info.dart';
import 'camera_selector.dart';
import 'camera_state.dart';
import 'camera_state_error.dart';
import 'camerax_library.g.dart';
import 'device_orientation_manager.dart';
import 'exposure_state.dart';
import 'focus_metering_result.dart';
import 'image_proxy.dart';
import 'java_object.dart';
import 'live_data.dart';
import 'observer.dart';
import 'pending_recording.dart';
import 'plane_proxy.dart';
import 'process_camera_provider.dart';
import 'recorder.dart';
import 'recording.dart';
import 'system_services.dart';
import 'video_capture.dart';
import 'zoom_state.dart';
/// Handles initialization of Flutter APIs for the Android CameraX library.
class AndroidCameraXCameraFlutterApis {
/// Creates a [AndroidCameraXCameraFlutterApis].
AndroidCameraXCameraFlutterApis(
{JavaObjectFlutterApiImpl? javaObjectFlutterApiImpl,
CameraFlutterApiImpl? cameraFlutterApiImpl,
CameraInfoFlutterApiImpl? cameraInfoFlutterApiImpl,
CameraSelectorFlutterApiImpl? cameraSelectorFlutterApiImpl,
ProcessCameraProviderFlutterApiImpl? processCameraProviderFlutterApiImpl,
SystemServicesFlutterApiImpl? systemServicesFlutterApiImpl,
DeviceOrientationManagerFlutterApiImpl?
deviceOrientationManagerFlutterApiImpl,
CameraStateErrorFlutterApiImpl? cameraStateErrorFlutterApiImpl,
CameraStateFlutterApiImpl? cameraStateFlutterApiImpl,
PendingRecordingFlutterApiImpl? pendingRecordingFlutterApiImpl,
RecordingFlutterApiImpl? recordingFlutterApiImpl,
RecorderFlutterApiImpl? recorderFlutterApiImpl,
VideoCaptureFlutterApiImpl? videoCaptureFlutterApiImpl,
ExposureStateFlutterApiImpl? exposureStateFlutterApiImpl,
ZoomStateFlutterApiImpl? zoomStateFlutterApiImpl,
LiveDataFlutterApiImpl? liveDataFlutterApiImpl,
ObserverFlutterApiImpl? observerFlutterApiImpl,
ImageProxyFlutterApiImpl? imageProxyFlutterApiImpl,
PlaneProxyFlutterApiImpl? planeProxyFlutterApiImpl,
AnalyzerFlutterApiImpl? analyzerFlutterApiImpl,
CameraControlFlutterApiImpl? cameraControlFlutterApiImpl,
FocusMeteringResultFlutterApiImpl? focusMeteringResultFlutterApiImpl}) {
this.javaObjectFlutterApiImpl =
javaObjectFlutterApiImpl ?? JavaObjectFlutterApiImpl();
this.cameraInfoFlutterApiImpl =
cameraInfoFlutterApiImpl ?? CameraInfoFlutterApiImpl();
this.cameraSelectorFlutterApiImpl =
cameraSelectorFlutterApiImpl ?? CameraSelectorFlutterApiImpl();
this.processCameraProviderFlutterApiImpl =
processCameraProviderFlutterApiImpl ??
ProcessCameraProviderFlutterApiImpl();
this.cameraFlutterApiImpl = cameraFlutterApiImpl ?? CameraFlutterApiImpl();
this.systemServicesFlutterApiImpl =
systemServicesFlutterApiImpl ?? SystemServicesFlutterApiImpl();
this.deviceOrientationManagerFlutterApiImpl =
deviceOrientationManagerFlutterApiImpl ??
DeviceOrientationManagerFlutterApiImpl();
this.cameraStateErrorFlutterApiImpl =
cameraStateErrorFlutterApiImpl ?? CameraStateErrorFlutterApiImpl();
this.cameraStateFlutterApiImpl =
cameraStateFlutterApiImpl ?? CameraStateFlutterApiImpl();
this.pendingRecordingFlutterApiImpl =
pendingRecordingFlutterApiImpl ?? PendingRecordingFlutterApiImpl();
this.recordingFlutterApiImpl =
recordingFlutterApiImpl ?? RecordingFlutterApiImpl();
this.recorderFlutterApiImpl =
recorderFlutterApiImpl ?? RecorderFlutterApiImpl();
this.videoCaptureFlutterApiImpl =
videoCaptureFlutterApiImpl ?? VideoCaptureFlutterApiImpl();
this.exposureStateFlutterApiImpl =
exposureStateFlutterApiImpl ?? ExposureStateFlutterApiImpl();
this.zoomStateFlutterApiImpl =
zoomStateFlutterApiImpl ?? ZoomStateFlutterApiImpl();
this.liveDataFlutterApiImpl =
liveDataFlutterApiImpl ?? LiveDataFlutterApiImpl();
this.observerFlutterApiImpl =
observerFlutterApiImpl ?? ObserverFlutterApiImpl();
this.analyzerFlutterApiImpl =
analyzerFlutterApiImpl ?? AnalyzerFlutterApiImpl();
this.imageProxyFlutterApiImpl =
imageProxyFlutterApiImpl ?? ImageProxyFlutterApiImpl();
this.planeProxyFlutterApiImpl =
planeProxyFlutterApiImpl ?? PlaneProxyFlutterApiImpl();
this.cameraControlFlutterApiImpl =
cameraControlFlutterApiImpl ?? CameraControlFlutterApiImpl();
this.focusMeteringResultFlutterApiImpl =
focusMeteringResultFlutterApiImpl ??
FocusMeteringResultFlutterApiImpl();
}
static bool _haveBeenSetUp = false;
/// Mutable instance containing all Flutter Apis for Android CameraX Camera.
///
/// This should only be changed for testing purposes.
static AndroidCameraXCameraFlutterApis instance =
AndroidCameraXCameraFlutterApis();
/// Handles callbacks methods for the native Java Object class.
late final JavaObjectFlutterApi javaObjectFlutterApiImpl;
/// Flutter Api implementation for [CameraInfo].
late final CameraInfoFlutterApiImpl cameraInfoFlutterApiImpl;
/// Flutter Api implementation for [CameraSelector].
late final CameraSelectorFlutterApiImpl cameraSelectorFlutterApiImpl;
/// Flutter Api implementation for [ProcessCameraProvider].
late final ProcessCameraProviderFlutterApiImpl
processCameraProviderFlutterApiImpl;
/// Flutter Api implementation for [Camera].
late final CameraFlutterApiImpl cameraFlutterApiImpl;
/// Flutter Api implementation for [SystemServices].
late final SystemServicesFlutterApiImpl systemServicesFlutterApiImpl;
/// Flutter Api implementation for [DeviceOrientationManager].
late final DeviceOrientationManagerFlutterApiImpl
deviceOrientationManagerFlutterApiImpl;
/// Flutter Api implementation for [CameraStateError].
late final CameraStateErrorFlutterApiImpl? cameraStateErrorFlutterApiImpl;
/// Flutter Api implementation for [CameraState].
late final CameraStateFlutterApiImpl? cameraStateFlutterApiImpl;
/// Flutter Api implementation for [LiveData].
late final LiveDataFlutterApiImpl? liveDataFlutterApiImpl;
/// Flutter Api implementation for [Observer].
late final ObserverFlutterApiImpl? observerFlutterApiImpl;
/// Flutter Api for [PendingRecording].
late final PendingRecordingFlutterApiImpl pendingRecordingFlutterApiImpl;
/// Flutter Api for [Recording].
late final RecordingFlutterApiImpl recordingFlutterApiImpl;
/// Flutter Api for [Recorder].
late final RecorderFlutterApiImpl recorderFlutterApiImpl;
/// Flutter Api for [VideoCapture].
late final VideoCaptureFlutterApiImpl videoCaptureFlutterApiImpl;
/// Flutter Api for [ExposureState].
late final ExposureStateFlutterApiImpl exposureStateFlutterApiImpl;
/// Flutter Api for [ZoomState].
late final ZoomStateFlutterApiImpl zoomStateFlutterApiImpl;
/// Flutter Api implementation for [Analyzer].
late final AnalyzerFlutterApiImpl analyzerFlutterApiImpl;
/// Flutter Api implementation for [ImageProxy].
late final ImageProxyFlutterApiImpl imageProxyFlutterApiImpl;
/// Flutter Api implementation for [PlaneProxy].
late final PlaneProxyFlutterApiImpl planeProxyFlutterApiImpl;
/// Flutter Api implementation for [CameraControl].
late final CameraControlFlutterApiImpl cameraControlFlutterApiImpl;
/// Flutter Api implementation for [FocusMeteringResult].
late final FocusMeteringResultFlutterApiImpl
focusMeteringResultFlutterApiImpl;
/// Ensures all the Flutter APIs have been setup to receive calls from native code.
void ensureSetUp() {
if (!_haveBeenSetUp) {
JavaObjectFlutterApi.setup(javaObjectFlutterApiImpl);
CameraInfoFlutterApi.setup(cameraInfoFlutterApiImpl);
CameraSelectorFlutterApi.setup(cameraSelectorFlutterApiImpl);
ProcessCameraProviderFlutterApi.setup(
processCameraProviderFlutterApiImpl);
CameraFlutterApi.setup(cameraFlutterApiImpl);
SystemServicesFlutterApi.setup(systemServicesFlutterApiImpl);
DeviceOrientationManagerFlutterApi.setup(
deviceOrientationManagerFlutterApiImpl);
CameraStateErrorFlutterApi.setup(cameraStateErrorFlutterApiImpl);
CameraStateFlutterApi.setup(cameraStateFlutterApiImpl);
PendingRecordingFlutterApi.setup(pendingRecordingFlutterApiImpl);
RecordingFlutterApi.setup(recordingFlutterApiImpl);
RecorderFlutterApi.setup(recorderFlutterApiImpl);
VideoCaptureFlutterApi.setup(videoCaptureFlutterApiImpl);
ExposureStateFlutterApi.setup(exposureStateFlutterApiImpl);
ZoomStateFlutterApi.setup(zoomStateFlutterApiImpl);
AnalyzerFlutterApi.setup(analyzerFlutterApiImpl);
ImageProxyFlutterApi.setup(imageProxyFlutterApiImpl);
PlaneProxyFlutterApi.setup(planeProxyFlutterApiImpl);
LiveDataFlutterApi.setup(liveDataFlutterApiImpl);
ObserverFlutterApi.setup(observerFlutterApiImpl);
CameraControlFlutterApi.setup(cameraControlFlutterApiImpl);
FocusMeteringResultFlutterApi.setup(focusMeteringResultFlutterApiImpl);
_haveBeenSetUp = true;
}
}
}
| packages/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart",
"repo_id": "packages",
"token_count": 3170
} | 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 'package:flutter/services.dart' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// The result of [CameraControl.startFocusAndMetering].
///
/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringResult.
@immutable
class FocusMeteringResult extends JavaObject {
/// Creates a [FocusMeteringResult] that is not automatically attached to a
/// native object.
FocusMeteringResult.detached({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
) {
_api = _FocusMeteringResultHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final _FocusMeteringResultHostApiImpl _api;
/// Returns whether or not auto focus is successful.
///
/// If the current camera does not support auto focus, it will return true. If
/// auto focus is not requested, it will return false.
Future<bool> isFocusSuccessful() => _api.isFocusSuccessfulFromInstance(this);
}
/// Host API implementation of [FocusMeteringResult].
class _FocusMeteringResultHostApiImpl extends FocusMeteringResultHostApi {
/// Constructs a [FocusMeteringActionHostApiImpl].
///
/// 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].
_FocusMeteringResultHostApiImpl(
{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;
/// Returns whether or not the [instance] indicates that auto focus was
/// successful.
Future<bool> isFocusSuccessfulFromInstance(FocusMeteringResult instance) {
final int identifier = instanceManager.getIdentifier(instance)!;
return isFocusSuccessful(identifier);
}
}
/// Flutter API implementation of [FocusMeteringResult].
class FocusMeteringResultFlutterApiImpl extends FocusMeteringResultFlutterApi {
/// Constructs a [FocusMeteringResultFlutterApiImpl].
///
/// 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].
FocusMeteringResultFlutterApiImpl({
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(
FocusMeteringResult.detached(
binaryMessenger: _binaryMessenger, instanceManager: _instanceManager),
identifier,
onCopy: (FocusMeteringResult original) {
return FocusMeteringResult.detached(
binaryMessenger: _binaryMessenger,
instanceManager: _instanceManager);
},
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart",
"repo_id": "packages",
"token_count": 1242
} | 994 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:meta/meta.dart' show immutable;
import 'aspect_ratio_strategy.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'resolution_strategy.dart';
/// A set of requirements and priorities used to select a resolution for a
/// UseCase.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionSelector.
@immutable
class ResolutionSelector extends JavaObject {
/// Construct a [ResolutionSelector].
ResolutionSelector({
this.resolutionStrategy,
this.aspectRatioStrategy,
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionSelectorHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached() {
_api.createFromInstances(this, resolutionStrategy, aspectRatioStrategy);
}
/// Instantiates a [ResolutionSelector] without creating and attaching to an
/// instance of the associated native class.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an [InstanceManager].
ResolutionSelector.detached({
this.resolutionStrategy,
this.aspectRatioStrategy,
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionSelectorHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached();
final _ResolutionSelectorHostApiImpl _api;
/// Determines how the UseCase will choose the resolution of the captured
/// image.
final ResolutionStrategy? resolutionStrategy;
/// Determines how the UseCase will choose the aspect ratio of the captured
/// image.
final AspectRatioStrategy? aspectRatioStrategy;
}
/// Host API implementation of [ResolutionSelector].
class _ResolutionSelectorHostApiImpl extends ResolutionSelectorHostApi {
/// Constructs an [_ResolutionSelectorHostApiImpl].
///
/// 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].
_ResolutionSelectorHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
/// Creates a [ResolutionSelector] on the native side with the
/// [ResolutionStrategy] and [AspectRatioStrategy] if specified.
Future<void> createFromInstances(
ResolutionSelector instance,
ResolutionStrategy? resolutionStrategy,
AspectRatioStrategy? aspectRatioStrategy,
) {
return create(
instanceManager.addDartCreatedInstance(
instance,
onCopy: (ResolutionSelector original) => ResolutionSelector.detached(
resolutionStrategy: original.resolutionStrategy,
aspectRatioStrategy: original.aspectRatioStrategy,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
),
resolutionStrategy == null
? null
: instanceManager.getIdentifier(resolutionStrategy)!,
aspectRatioStrategy == null
? null
: instanceManager.getIdentifier(aspectRatioStrategy)!,
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/resolution_selector.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/resolution_selector.dart",
"repo_id": "packages",
"token_count": 1246
} | 995 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/camera2_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/camera_control.dart' as _i2;
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i7;
import 'package:camera_android_camerax/src/capture_request_options.dart' as _i6;
import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i5;
import 'package:camera_android_camerax/src/focus_metering_result.dart' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i8;
// 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 [CameraControl].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockCameraControl extends _i1.Mock implements _i2.CameraControl {
MockCameraControl() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> enableTorch(bool? torch) => (super.noSuchMethod(
Invocation.method(
#enableTorch,
[torch],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<void> setZoomRatio(double? ratio) => (super.noSuchMethod(
Invocation.method(
#setZoomRatio,
[ratio],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<_i4.FocusMeteringResult?> startFocusAndMetering(
_i5.FocusMeteringAction? action) =>
(super.noSuchMethod(
Invocation.method(
#startFocusAndMetering,
[action],
),
returnValue: _i3.Future<_i4.FocusMeteringResult?>.value(),
) as _i3.Future<_i4.FocusMeteringResult?>);
@override
_i3.Future<void> cancelFocusAndMetering() => (super.noSuchMethod(
Invocation.method(
#cancelFocusAndMetering,
[],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<int?> setExposureCompensationIndex(int? index) =>
(super.noSuchMethod(
Invocation.method(
#setExposureCompensationIndex,
[index],
),
returnValue: _i3.Future<int?>.value(),
) as _i3.Future<int?>);
}
/// A class which mocks [CaptureRequestOptions].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockCaptureRequestOptions extends _i1.Mock
implements _i6.CaptureRequestOptions {
MockCaptureRequestOptions() {
_i1.throwOnMissingStub(this);
}
@override
List<(_i7.CaptureRequestKeySupportedType, Object?)> get requestedOptions =>
(super.noSuchMethod(
Invocation.getter(#requestedOptions),
returnValue: <(_i7.CaptureRequestKeySupportedType, Object?)>[],
) as List<(_i7.CaptureRequestKeySupportedType, Object?)>);
}
/// A class which mocks [TestCamera2CameraControlHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestCamera2CameraControlHostApi extends _i1.Mock
implements _i8.TestCamera2CameraControlHostApi {
MockTestCamera2CameraControlHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? cameraControlIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
cameraControlIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<void> addCaptureRequestOptions(
int? identifier,
int? captureRequestOptionsIdentifier,
) =>
(super.noSuchMethod(
Invocation.method(
#addCaptureRequestOptions,
[
identifier,
captureRequestOptionsIdentifier,
],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i8.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart",
"repo_id": "packages",
"token_count": 2149
} | 996 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/device_orientation_manager_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
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 [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 [TestDeviceOrientationManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestDeviceOrientationManagerHostApi extends _i1.Mock
implements _i2.TestDeviceOrientationManagerHostApi {
MockTestDeviceOrientationManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void startListeningForDeviceOrientationChange(
bool? isFrontFacing,
int? sensorOrientation,
) =>
super.noSuchMethod(
Invocation.method(
#startListeningForDeviceOrientationChange,
[
isFrontFacing,
sensorOrientation,
],
),
returnValueForMissingStub: null,
);
@override
void stopListeningForDeviceOrientationChange() => super.noSuchMethod(
Invocation.method(
#stopListeningForDeviceOrientationChange,
[],
),
returnValueForMissingStub: null,
);
@override
int getDefaultDisplayRotation() => (super.noSuchMethod(
Invocation.method(
#getDefaultDisplayRotation,
[],
),
returnValue: 0,
) as int);
}
| packages/packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart",
"repo_id": "packages",
"token_count": 968
} | 997 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camera_state.dart';
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/live_data.dart';
import 'package:camera_android_camerax/src/observer.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'live_data_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestLiveDataHostApi, TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('LiveData', () {
tearDown(() {
TestLiveDataHostApi.setup(null);
});
test('observe makes call to add observer to LiveData instance', () async {
final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi();
TestLiveDataHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final LiveData<Object> instance = LiveData<Object>.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(
instance,
instanceIdentifier,
onCopy: (LiveData<Object> original) => LiveData<Object>.detached(
instanceManager: instanceManager,
),
);
final Observer<Object> observer = Observer<Object>.detached(
instanceManager: instanceManager,
onChanged: (Object value) {},
);
const int observerIdentifier = 20;
instanceManager.addHostCreatedInstance(
observer,
observerIdentifier,
onCopy: (_) => Observer<Object>.detached(
instanceManager: instanceManager,
onChanged: (Object value) {},
),
);
await instance.observe(
observer,
);
verify(mockApi.observe(
instanceIdentifier,
observerIdentifier,
));
});
test(
'removeObservers makes call to remove observers from LiveData instance',
() async {
final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi();
TestLiveDataHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final LiveData<Object> instance = LiveData<Object>.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(
instance,
instanceIdentifier,
onCopy: (LiveData<Object> original) => LiveData<Object>.detached(
instanceManager: instanceManager,
),
);
await instance.removeObservers();
verify(mockApi.removeObservers(
instanceIdentifier,
));
});
test('getValue returns expected value', () async {
final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi();
TestLiveDataHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final LiveData<CameraState> instance = LiveData<CameraState>.detached(
instanceManager: instanceManager,
);
final CameraState testCameraState =
CameraState.detached(type: CameraStateType.closed);
const int instanceIdentifier = 0;
const int testCameraStateIdentifier = 22;
instanceManager.addHostCreatedInstance(
instance,
instanceIdentifier,
onCopy: (LiveData<CameraState> original) =>
LiveData<CameraState>.detached(
instanceManager: instanceManager,
),
);
instanceManager.addHostCreatedInstance(
testCameraState,
testCameraStateIdentifier,
onCopy: (CameraState original) => CameraState.detached(
type: original.type, instanceManager: instanceManager),
);
when(mockApi.getValue(instanceIdentifier, any))
.thenReturn(testCameraStateIdentifier);
expect(await instance.getValue(), equals(testCameraState));
});
test(
'FlutterAPI create makes call to create LiveData<CameraState> instance with expected identifier',
() async {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final LiveDataFlutterApiImpl api = LiveDataFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(
instanceIdentifier,
LiveDataSupportedTypeData(value: LiveDataSupportedType.cameraState),
);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<LiveData<CameraState>>(),
);
});
});
}
| packages/packages/camera/camera_android_camerax/test/live_data_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/live_data_test.dart",
"repo_id": "packages",
"token_count": 1965
} | 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 'package:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/pending_recording.dart';
import 'package:camera_android_camerax/src/quality_selector.dart';
import 'package:camera_android_camerax/src/recorder.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'recorder_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
QualitySelector,
TestInstanceManagerHostApi,
TestFallbackStrategyHostApi,
TestRecorderHostApi,
TestQualitySelectorHostApi,
PendingRecording
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('Recorder', () {
tearDown(() => TestCameraSelectorHostApi.setup(null));
test('detached create does not call create on the Java side', () async {
final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi();
TestRecorderHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
Recorder.detached(
instanceManager: instanceManager, aspectRatio: 0, bitRate: 0);
verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()),
argThat(isA<int>()), argThat(isA<int>())));
});
test('create does call create on the Java side', () async {
final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi();
TestRecorderHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int aspectRatio = 1;
const int bitRate = 2;
final QualitySelector qualitySelector = MockQualitySelector();
const int qualitySelectorIdentifier = 33;
instanceManager.addHostCreatedInstance(
qualitySelector,
qualitySelectorIdentifier,
onCopy: (_) => MockQualitySelector(),
);
Recorder(
instanceManager: instanceManager,
aspectRatio: aspectRatio,
bitRate: bitRate,
qualitySelector: qualitySelector);
verify(mockApi.create(argThat(isA<int>()), aspectRatio, bitRate,
qualitySelectorIdentifier));
});
test('getDefaultQualitySelector returns expected QualitySelector',
() async {
final MockTestQualitySelectorHostApi mockQualitySelectorApi =
MockTestQualitySelectorHostApi();
final MockTestFallbackStrategyHostApi mockFallbackStrategyApi =
MockTestFallbackStrategyHostApi();
TestQualitySelectorHostApi.setup(mockQualitySelectorApi);
TestFallbackStrategyHostApi.setup(mockFallbackStrategyApi);
final QualitySelector defaultQualitySelector =
Recorder.getDefaultQualitySelector();
final List<VideoQuality> expectedVideoQualities = <VideoQuality>[
VideoQuality.FHD,
VideoQuality.HD,
VideoQuality.SD
];
expect(defaultQualitySelector.qualityList.length, equals(3));
for (int i = 0; i < 3; i++) {
final VideoQuality currentVideoQuality =
defaultQualitySelector.qualityList[i].quality;
expect(currentVideoQuality, equals(expectedVideoQualities[i]));
}
expect(defaultQualitySelector.fallbackStrategy!.quality,
equals(VideoQuality.FHD));
expect(defaultQualitySelector.fallbackStrategy!.fallbackRule,
equals(VideoResolutionFallbackRule.higherQualityOrLowerThan));
// Cleanup test Host APIs used only for this test.
TestQualitySelectorHostApi.setup(null);
TestFallbackStrategyHostApi.setup(null);
});
test('prepareRecording calls prepareRecording on Java side', () async {
final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi();
TestRecorderHostApi.setup(mockApi);
when(mockApi.prepareRecording(0, '/test/path')).thenAnswer((_) => 2);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const String filePath = '/test/path';
final Recorder recorder =
Recorder.detached(instanceManager: instanceManager);
const int recorderId = 0;
const int mockPendingRecordingId = 2;
instanceManager.addHostCreatedInstance(recorder, recorderId,
onCopy: (_) => Recorder.detached(instanceManager: instanceManager));
final MockPendingRecording mockPendingRecording = MockPendingRecording();
instanceManager.addHostCreatedInstance(
mockPendingRecording, mockPendingRecordingId,
onCopy: (_) => MockPendingRecording());
when(mockApi.prepareRecording(recorderId, filePath))
.thenReturn(mockPendingRecordingId);
final PendingRecording pendingRecording =
await recorder.prepareRecording(filePath);
expect(pendingRecording, mockPendingRecording);
});
test(
'flutterApi create makes call to create Recorder instance with expected identifier',
() {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final RecorderFlutterApiImpl flutterApi = RecorderFlutterApiImpl(
instanceManager: instanceManager,
);
const int recorderId = 0;
const int aspectRatio = 1;
const int bitrate = 2;
flutterApi.create(recorderId, aspectRatio, bitrate);
expect(instanceManager.getInstanceWithWeakReference(recorderId),
isA<Recorder>());
expect(
(instanceManager.getInstanceWithWeakReference(recorderId)!
as Recorder)
.aspectRatio,
equals(aspectRatio));
expect(
(instanceManager.getInstanceWithWeakReference(0)! as Recorder)
.bitRate,
equals(bitrate));
});
});
}
| packages/packages/camera/camera_android_camerax/test/recorder_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/recorder_test.dart",
"repo_id": "packages",
"token_count": 2350
} | 999 |
## 0.9.14+1
* Fixes bug where max resolution preset does not produce highest available resolution on iOS.
## 0.9.14
* Adds support to HEIF format.
## 0.9.13+11
* Fixes a memory leak of sample buffer when pause and resume the video recording.
* Removes development team from example app.
* Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6.
## 0.9.13+10
* Adds privacy manifest.
## 0.9.13+9
* Fixes new lint warnings.
## 0.9.13+8
* Updates example app to use non-deprecated video_player method.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 0.9.13+7
* Fixes inverted orientation strings.
## 0.9.13+6
* Fixes incorrect use of `NSError` that could cause crashes on launch.
## 0.9.13+5
* Ignores audio samples until the first video sample arrives.
## 0.9.13+4
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.9.13+3
* Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters.
* Fixes unawaited_futures violations.
## 0.9.13+2
* Removes obsolete null checks on non-nullable values.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 0.9.13+1
* Clarifies explanation of endorsement in README.
## 0.9.13
* Allows camera to be switched while video recording.
* Aligns Dart and Flutter SDK constraints.
## 0.9.12
* Updates minimum Flutter version to 3.3 and iOS 11.
## 0.9.11+1
* Updates links for the merge of flutter/plugins into flutter/packages.
## 0.9.11
* Adds back use of Optional type.
* Updates minimum Flutter version to 3.0.
## 0.9.10+2
* Updates code for stricter lint checks.
## 0.9.10+1
* Updates code for stricter lint checks.
## 0.9.10
* Remove usage of deprecated quiver Optional type.
## 0.9.9
* Implements option to also stream when recording a video.
## 0.9.8+6
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
## 0.9.8+5
* Fixes a regression introduced in 0.9.8+4 where the stream handler is not set.
## 0.9.8+4
* Fixes a crash due to sending orientation change events when the engine is torn down.
## 0.9.8+3
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
* Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750).
## 0.9.8+2
* Fixes exception in registerWith caused by the switch to an in-package method channel.
## 0.9.8+1
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.9.8
* Switches to internal method channel implementation.
## 0.9.7+1
* Splits from `camera` as a federated implementation.
| packages/packages/camera/camera_avfoundation/CHANGELOG.md/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/CHANGELOG.md",
"repo_id": "packages",
"token_count": 891
} | 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 camera_avfoundation;
@import camera_avfoundation.Test;
@import AVFoundation;
@import XCTest;
#import <OCMock/OCMock.h>
#import "CameraTestUtils.h"
/// Includes test cases related to resolution presets setting operations for FLTCam class.
@interface FLTCamSessionPresetsTest : XCTestCase
@end
@implementation FLTCamSessionPresetsTest
- (void)testResolutionPresetWithBestFormat_mustUpdateCaptureSessionPreset {
NSString *expectedPreset = AVCaptureSessionPresetInputPriority;
id videoSessionMock = OCMClassMock([AVCaptureSession class]);
OCMStub([videoSessionMock addInputWithNoConnections:[OCMArg any]]);
id captureFormatMock = OCMClassMock([AVCaptureDeviceFormat class]);
id captureDeviceMock = OCMClassMock([AVCaptureDevice class]);
OCMStub([captureDeviceMock formats]).andReturn(@[ captureFormatMock ]);
OCMExpect([captureDeviceMock activeFormat]).andReturn(captureFormatMock);
OCMExpect([captureDeviceMock lockForConfiguration:NULL]).andReturn(YES);
OCMExpect([videoSessionMock setSessionPreset:expectedPreset]);
FLTCreateCamWithVideoDimensionsForFormat(videoSessionMock, @"max", captureDeviceMock,
^CMVideoDimensions(AVCaptureDeviceFormat *format) {
CMVideoDimensions videoDimensions;
videoDimensions.width = 1;
videoDimensions.height = 1;
return videoDimensions;
});
OCMVerifyAll(captureDeviceMock);
OCMVerifyAll(videoSessionMock);
}
- (void)testResolutionPresetWithCanSetSessionPresetMax_mustUpdateCaptureSessionPreset {
NSString *expectedPreset = AVCaptureSessionPreset3840x2160;
id videoSessionMock = OCMClassMock([AVCaptureSession class]);
OCMStub([videoSessionMock addInputWithNoConnections:[OCMArg any]]);
// Make sure that setting resolution preset for session always succeeds.
OCMStub([videoSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES);
OCMExpect([videoSessionMock setSessionPreset:expectedPreset]);
FLTCreateCamWithVideoCaptureSession(videoSessionMock, @"max");
OCMVerifyAll(videoSessionMock);
}
- (void)testResolutionPresetWithCanSetSessionPresetUltraHigh_mustUpdateCaptureSessionPreset {
NSString *expectedPreset = AVCaptureSessionPreset3840x2160;
id videoSessionMock = OCMClassMock([AVCaptureSession class]);
OCMStub([videoSessionMock addInputWithNoConnections:[OCMArg any]]);
// Make sure that setting resolution preset for session always succeeds.
OCMStub([videoSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES);
// Expect that setting "ultraHigh" resolutionPreset correctly updates videoCaptureSession.
OCMExpect([videoSessionMock setSessionPreset:expectedPreset]);
FLTCreateCamWithVideoCaptureSession(videoSessionMock, @"ultraHigh");
OCMVerifyAll(videoSessionMock);
}
@end
| packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.m",
"repo_id": "packages",
"token_count": 1128
} | 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 "FLTCam.h"
#import "FLTSavePhotoDelegate.h"
/// Determines the video dimensions (width and height) for a given capture device format.
/// Used in tests to mock CMVideoFormatDescriptionGetDimensions.
typedef CMVideoDimensions (^VideoDimensionsForFormat)(AVCaptureDeviceFormat *);
/// Factory block returning an AVCaptureDevice.
/// Used in tests to inject a device into FLTCam.
typedef AVCaptureDevice * (^CaptureDeviceFactory)(void);
@interface FLTImageStreamHandler : NSObject <FlutterStreamHandler>
/// The queue on which `eventSink` property should be accessed.
@property(nonatomic, strong) dispatch_queue_t captureSessionQueue;
/// The event sink to stream camera events to Dart.
///
/// The property should only be accessed on `captureSessionQueue`.
/// The block itself should be invoked on the main queue.
@property FlutterEventSink eventSink;
@end
// APIs exposed for unit testing.
@interface FLTCam ()
/// The output for video capturing.
@property(readonly, nonatomic) AVCaptureVideoDataOutput *captureVideoOutput;
/// The output for photo capturing. Exposed setter for unit tests.
@property(strong, nonatomic) AVCapturePhotoOutput *capturePhotoOutput;
/// True when images from the camera are being streamed.
@property(assign, nonatomic) BOOL isStreamingImages;
/// A dictionary to retain all in-progress FLTSavePhotoDelegates. The key of the dictionary is the
/// AVCapturePhotoSettings's uniqueID for each photo capture operation, and the value is the
/// FLTSavePhotoDelegate that handles the result of each photo capture operation. Note that photo
/// capture operations may overlap, so FLTCam has to keep track of multiple delegates in progress,
/// instead of just a single delegate reference.
@property(readonly, nonatomic)
NSMutableDictionary<NSNumber *, FLTSavePhotoDelegate *> *inProgressSavePhotoDelegates;
/// Delegate callback when receiving a new video or audio sample.
/// Exposed for unit tests.
- (void)captureOutput:(AVCaptureOutput *)output
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection;
/// Initializes a camera instance.
/// Allows for injecting dependencies that are usually internal.
- (instancetype)initWithCameraName:(NSString *)cameraName
resolutionPreset:(NSString *)resolutionPreset
enableAudio:(BOOL)enableAudio
orientation:(UIDeviceOrientation)orientation
videoCaptureSession:(AVCaptureSession *)videoCaptureSession
audioCaptureSession:(AVCaptureSession *)audioCaptureSession
captureSessionQueue:(dispatch_queue_t)captureSessionQueue
error:(NSError **)error;
/// Initializes a camera instance.
/// Allows for testing with specified resolution, audio preference, orientation,
/// and direct access to capture sessions and blocks.
- (instancetype)initWithResolutionPreset:(NSString *)resolutionPreset
enableAudio:(BOOL)enableAudio
orientation:(UIDeviceOrientation)orientation
videoCaptureSession:(AVCaptureSession *)videoCaptureSession
audioCaptureSession:(AVCaptureSession *)audioCaptureSession
captureSessionQueue:(dispatch_queue_t)captureSessionQueue
captureDeviceFactory:(CaptureDeviceFactory)captureDeviceFactory
videoDimensionsForFormat:(VideoDimensionsForFormat)videoDimensionsForFormat
error:(NSError **)error;
/// Start streaming images.
- (void)startImageStreamWithMessenger:(NSObject<FlutterBinaryMessenger> *)messenger
imageStreamHandler:(FLTImageStreamHandler *)imageStreamHandler;
@end
| packages/packages/camera/camera_avfoundation/ios/Classes/FLTCam_Test.h/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/FLTCam_Test.h",
"repo_id": "packages",
"token_count": 1265
} | 1,002 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class MethodChannelMock {
MethodChannelMock({
required String channelName,
this.delay,
required this.methods,
}) : methodChannel = MethodChannel(channelName) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(methodChannel, _handler);
}
final Duration? delay;
final MethodChannel methodChannel;
final Map<String, dynamic> methods;
final List<MethodCall> log = <MethodCall>[];
Future<dynamic> _handler(MethodCall methodCall) async {
log.add(methodCall);
if (!methods.containsKey(methodCall.method)) {
throw MissingPluginException('No implementation found for method '
'${methodCall.method} on channel ${methodChannel.name}');
}
return Future<dynamic>.delayed(delay ?? Duration.zero, () {
final dynamic result = methods[methodCall.method];
if (result is Exception) {
throw result;
}
return Future<dynamic>.value(result);
});
}
}
| packages/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart",
"repo_id": "packages",
"token_count": 405
} | 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 'package:camera_web/src/types/types.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'helpers/helpers.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('ZoomLevelCapability', () {
testWidgets('sets all properties', (WidgetTester tester) async {
const double minimum = 100.0;
const double maximum = 400.0;
final MockMediaStreamTrack videoTrack = MockMediaStreamTrack();
final ZoomLevelCapability capability = ZoomLevelCapability(
minimum: minimum,
maximum: maximum,
videoTrack: videoTrack,
);
expect(capability.minimum, equals(minimum));
expect(capability.maximum, equals(maximum));
expect(capability.videoTrack, equals(videoTrack));
});
testWidgets('supports value equality', (WidgetTester tester) async {
final MockMediaStreamTrack videoTrack = MockMediaStreamTrack();
expect(
ZoomLevelCapability(
minimum: 0.0,
maximum: 100.0,
videoTrack: videoTrack,
),
equals(
ZoomLevelCapability(
minimum: 0.0,
maximum: 100.0,
videoTrack: videoTrack,
),
),
);
});
});
}
| packages/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart/0 | {
"file_path": "packages/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart",
"repo_id": "packages",
"token_count": 569
} | 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 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:web/web.dart';
import '../web_helpers/web_helpers.dart';
import 'base.dart';
// Four Gigabytes, in bytes.
const int _fourGigabytes = 4 * 1024 * 1024 * 1024;
/// A CrossFile that works on web.
///
/// It wraps the bytes of a selected file.
class XFile extends XFileBase {
/// Construct a CrossFile object from its ObjectUrl.
///
/// Optionally, this can be initialized with `bytes` and `length`
/// so no http requests are performed to retrieve files later.
///
/// `name` needs to be passed from the outside, since it's only available
/// while handling [html.File]s (when the ObjectUrl is created).
// ignore: use_super_parameters
XFile(
String path, {
String? mimeType,
String? name,
int? length,
Uint8List? bytes,
DateTime? lastModified,
@visibleForTesting CrossFileTestOverrides? overrides,
}) : _mimeType = mimeType,
_path = path,
_length = length,
_overrides = overrides,
_lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0),
_name = name ?? '',
super(path) {
// Cache `bytes` as Blob, if passed.
if (bytes != null) {
_browserBlob = _createBlobFromBytes(bytes, mimeType);
}
}
/// Construct an CrossFile from its data
XFile.fromData(
Uint8List bytes, {
String? mimeType,
String? name,
int? length,
DateTime? lastModified,
String? path,
@visibleForTesting CrossFileTestOverrides? overrides,
}) : _mimeType = mimeType,
_length = length,
_overrides = overrides,
_lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0),
_name = name ?? '',
super(path) {
if (path == null) {
_browserBlob = _createBlobFromBytes(bytes, mimeType);
_path = URL.createObjectURL(_browserBlob!);
} else {
_path = path;
}
}
// Initializes a Blob from a bunch of `bytes` and an optional `mimeType`.
Blob _createBlobFromBytes(Uint8List bytes, String? mimeType) {
return (mimeType == null)
? Blob(<JSUint8Array>[bytes.toJS].toJS)
: Blob(
<JSUint8Array>[bytes.toJS].toJS, BlobPropertyBag(type: mimeType));
}
// Overridable (meta) data that can be specified by the constructors.
// MimeType of the file (eg: "image/gif").
final String? _mimeType;
// Name (with extension) of the file (eg: "anim.gif")
final String _name;
// Path of the file (must be a valid Blob URL, when set manually!)
late String _path;
// The size of the file (in bytes).
final int? _length;
// The time the file was last modified.
final DateTime _lastModified;
// The link to the binary object in the browser memory (Blob).
// This can be passed in (as `bytes` in the constructor) or derived from
// [_path] with a fetch request.
// (Similar to a (read-only) dart:io File.)
Blob? _browserBlob;
// An html Element that will be used to trigger a "save as" dialog later.
// TODO(dit): https://github.com/flutter/flutter/issues/91400 Remove this _target.
late Element _target;
// Overrides for testing
// TODO(dit): https://github.com/flutter/flutter/issues/91400 Remove these _overrides,
// they're only used to Save As...
final CrossFileTestOverrides? _overrides;
bool get _hasTestOverrides => _overrides != null;
@override
String? get mimeType => _mimeType;
@override
String get name => _name;
@override
String get path => _path;
@override
Future<DateTime> lastModified() async => _lastModified;
Future<Blob> get _blob async {
if (_browserBlob != null) {
return _browserBlob!;
}
// Attempt to re-hydrate the blob from the `path` via a (local) HttpRequest.
// Note that safari hangs if the Blob is >=4GB, so bail out in that case.
if (isSafari() && _length != null && _length >= _fourGigabytes) {
throw Exception('Safari cannot handle XFiles larger than 4GB.');
}
final Completer<Blob> blobCompleter = Completer<Blob>();
late XMLHttpRequest request;
request = XMLHttpRequest()
..open('get', path, true)
..responseType = 'blob'
..onLoad.listen((ProgressEvent e) {
assert(request.response != null,
'The Blob backing this XFile cannot be null!');
blobCompleter.complete(request.response! as Blob);
})
..onError.listen((ProgressEvent e) {
if (e.type == 'error') {
blobCompleter.completeError(Exception(
'Could not load Blob from its URL. Has it been revoked?'));
}
})
..send();
return blobCompleter.future;
}
@override
Future<Uint8List> readAsBytes() async {
return _blob.then(_blobToByteBuffer);
}
@override
Future<int> length() async => _length ?? (await _blob).size;
@override
Future<String> readAsString({Encoding encoding = utf8}) async {
return readAsBytes().then(encoding.decode);
}
// TODO(dit): https://github.com/flutter/flutter/issues/91867 Implement openRead properly.
@override
Stream<Uint8List> openRead([int? start, int? end]) async* {
final Blob blob = await _blob;
final Blob slice = blob.slice(start ?? 0, end ?? blob.size, blob.type);
final Uint8List convertedSlice = await _blobToByteBuffer(slice);
yield convertedSlice;
}
// Converts an html Blob object to a Uint8List, through a FileReader.
Future<Uint8List> _blobToByteBuffer(Blob blob) async {
final FileReader reader = FileReader();
reader.readAsArrayBuffer(blob);
await reader.onLoadEnd.first;
final Uint8List? result =
(reader.result as JSArrayBuffer?)?.toDart.asUint8List();
if (result == null) {
throw Exception('Cannot read bytes from Blob. Is it still available?');
}
return result;
}
/// Saves the data of this CrossFile at the location indicated by path.
/// For the web implementation, the path variable is ignored.
// TODO(dit): https://github.com/flutter/flutter/issues/91400
// Move implementation to web_helpers.dart
@override
Future<void> saveTo(String path) async {
// Create a DOM container where the anchor can be injected.
_target = ensureInitialized('__x_file_dom_element');
// Create an <a> tag with the appropriate download attributes and click it
// May be overridden with CrossFileTestOverrides
final HTMLAnchorElement element = _hasTestOverrides
? _overrides!.createAnchorElement(this.path, name) as HTMLAnchorElement
: createAnchorElement(this.path, name);
// Clear the children in _target and add an element to click
while (_target.children.length > 0) {
_target.removeChild(_target.children.item(0)!);
}
addElementToContainerAndClick(_target, element);
}
}
/// Overrides some functions to allow testing
// TODO(dit): https://github.com/flutter/flutter/issues/91400
// Move this to web_helpers_test.dart
@visibleForTesting
class CrossFileTestOverrides {
/// Default constructor for overrides
CrossFileTestOverrides({required this.createAnchorElement});
/// For overriding the creation of the file input element.
Element Function(String href, String suggestedName) createAnchorElement;
}
| packages/packages/cross_file/lib/src/types/html.dart/0 | {
"file_path": "packages/packages/cross_file/lib/src/types/html.dart",
"repo_id": "packages",
"token_count": 2675
} | 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:css_colors/css_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('CSSColors.orange should be correct',
(WidgetTester tester) async {
// Create a Container widget using CSSColors.orange.
// #docregion Usage
final Container orange = Container(color: CSSColors.orange);
// #enddocregion Usage
// Ensure the color of the container is the expected one.
expect(orange.color, equals(const Color(0xFFFFA500)));
});
}
| packages/packages/css_colors/test/css_colors_test.dart/0 | {
"file_path": "packages/packages/css_colors/test/css_colors_test.dart",
"repo_id": "packages",
"token_count": 224
} | 1,006 |
#include "Generated.xcconfig"
| packages/packages/dynamic_layouts/example/ios/Flutter/Release.xcconfig/0 | {
"file_path": "packages/packages/dynamic_layouts/example/ios/Flutter/Release.xcconfig",
"repo_id": "packages",
"token_count": 12
} | 1,007 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/dynamic_layouts/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/dynamic_layouts/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,008 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Updates compileSdk version to 34.
## 0.3.0+7
* Replaces call to deprecated `getObservatoryUri`.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 0.3.0+6
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.3.0+5
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
* Bumps okhttp version to 4.11.0.
## 0.3.0+4
* Fixes compatibility with AGP versions older than 4.2.
## 0.3.0+3
* Adds `targetCompatibilty` matching `sourceCompatibility` for older toolchains.
## 0.3.0+2
* Adds a namespace for compatibility with AGP 8.0.
## 0.3.0+1
* Sets an explicit Java compatibility version.
## 0.3.0
* **BREAKING CHANGE**: Migrates uses of the deprecated `@Beta` annotation to the new `@ExperimentalApi` annotation.
* Changes the severity of `javac` warnings so that they are treated as errors and fixes the violations.
* Aligns Dart and Flutter SDK constraints.
## 0.2.1
* Updates the version of com.google.truth:truth to 1.1.3.
## 0.2.0+10
* Updates espresso dependencies.
* Fixes example app to compile with multidex.
* Updates compileSdkVersion to 33.
## 0.2.0+9
* Updates links for the merge of flutter/plugins into flutter/packages.
## 0.2.0+8
* Updates espresso and junit dependencies.
## 0.2.0+7
* Updates espresso gradle and gson dependencies.
* Updates minimum Flutter version to 3.0.
## 0.2.0+6
* Updates espresso-accessibility to 3.5.1.
* Updates espresso-idling-resource to 3.5.1.
## 0.2.0+5
* Updates android gradle plugin to 7.3.1.
## 0.2.0+4
* Updates minimum Flutter version to 2.10.
* Bumps gson to 2.9.1
## 0.2.0+3
* Bumps okhttp to 4.10.0.
## 0.2.0+2
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.2.0+1
* Adds OS version support information to README.
* Updates `androidx.test.ext:junit` and `androidx.test.ext:truth` for
compatibility with updated Flutter template.
## 0.2.0
* Updates compileSdkVersion to 31.
* **Breaking Change** Update guava version to latest stable: `com.google.guava:guava:31.1-android`.
## 0.1.0+4
* Updated Android lint settings.
* Updated package description.
## 0.1.0+3
* Remove references to the Android v1 embedding.
## 0.1.0+2
* Migrate maven repo from jcenter to mavenCentral
## 0.1.0+1
* Minor code cleanup
* Package metadata updates
## 0.1.0
* Update SDK requirement for null-safety compatibility.
## 0.0.1+9
* Update Flutter SDK constraint.
## 0.0.1+8
* Android: Handle deprecation & unchecked warning as error.
## 0.0.1+7
* Update android compileSdkVersion to 29.
## 0.0.1+6
* Keep handling deprecated Android v1 classes for backward compatibility.
## 0.0.1+5
* Replace deprecated `getFlutterEngine` call on Android.
* Fix CocoaPods podspec lint warnings.
## 0.0.1+4
* Remove Swift dependency.
## 0.0.1+3
* Make the pedantic dev_dependency explicit.
## 0.0.1+2
* Update te example app to avoid using deprecated api.
## 0.0.1+1
* Updates to README to avoid unnecessary imports and warnings.
## 0.0.1
* Initial open-source release of Espresso bindings for Flutter.
| packages/packages/espresso/CHANGELOG.md/0 | {
"file_path": "packages/packages/espresso/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1130
} | 1,009 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.action;
import android.view.View;
import androidx.test.espresso.UiController;
import androidx.test.espresso.flutter.api.FlutterTestingProtocol;
import androidx.test.espresso.flutter.api.WidgetAction;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import java.util.concurrent.Future;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** An action that ensures Flutter is in an idle state. */
public final class WaitUntilIdleAction implements WidgetAction {
@Override
public Future<Void> perform(
@Nullable WidgetMatcher targetWidget,
@Nonnull View flutterView,
@Nonnull FlutterTestingProtocol flutterTestingProtocol,
@Nonnull UiController androidUiController) {
return flutterTestingProtocol.waitUntilIdle();
}
@Override
public String toString() {
return "action that waits until Flutter's idle.";
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WaitUntilIdleAction.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WaitUntilIdleAction.java",
"repo_id": "packages",
"token_count": 337
} | 1,010 |
// 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;
/** Thrown if an ID cannot be generated. */
public final class IdException extends RuntimeException {
private static final long serialVersionUID = 0L;
public IdException() {
super();
}
public IdException(String message) {
super(message);
}
public IdException(String message, Throwable throwable) {
super(message, throwable);
}
public IdException(Throwable throwable) {
super(throwable);
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java",
"repo_id": "packages",
"token_count": 189
} | 1,011 |
// 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;
/**
* Represents a condition that waits until there are no pending platform messages in the Flutter's
* platform channels.
*/
class NoPendingPlatformMessagesCondition extends WaitCondition {
public NoPendingPlatformMessagesCondition() {
super("NoPendingPlatformMessagesCondition");
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/NoPendingPlatformMessagesCondition.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/NoPendingPlatformMessagesCondition.java",
"repo_id": "packages",
"token_count": 136
} | 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 'dart:async';
// #docregion Import
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
// #enddocregion Import
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/people/v1.dart';
import 'package:googleapis_auth/googleapis_auth.dart' as auth show AuthClient;
final GoogleSignIn _googleSignIn = GoogleSignIn(
// Optional clientId
// clientId: '[YOUR_OAUTH_2_CLIENT_ID]',
scopes: <String>[PeopleServiceApi.contactsReadonlyScope],
);
void main() {
runApp(
const MaterialApp(
title: 'Google Sign In + googleapis',
home: SignInDemo(),
),
);
}
/// The main widget of this demo.
class SignInDemo extends StatefulWidget {
/// Creates the main widget of this demo.
const SignInDemo({super.key});
@override
State createState() => SignInDemoState();
}
/// The state of the main widget.
class SignInDemoState extends State<SignInDemo> {
GoogleSignInAccount? _currentUser;
String _contactText = '';
@override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
setState(() {
_currentUser = account;
});
if (_currentUser != null) {
_handleGetContact();
}
});
_googleSignIn.signInSilently();
}
Future<void> _handleGetContact() async {
setState(() {
_contactText = 'Loading contact info...';
});
// #docregion CreateAPIClient
// Retrieve an [auth.AuthClient] from the current [GoogleSignIn] instance.
final auth.AuthClient? client = await _googleSignIn.authenticatedClient();
assert(client != null, 'Authenticated client missing!');
// Prepare a People Service authenticated client.
final PeopleServiceApi peopleApi = PeopleServiceApi(client!);
// Retrieve a list of the `names` of my `connections`
final ListConnectionsResponse response =
await peopleApi.people.connections.list(
'people/me',
personFields: 'names',
);
// #enddocregion CreateAPIClient
final String? firstNamedContactName =
_pickFirstNamedContact(response.connections);
setState(() {
if (firstNamedContactName != null) {
_contactText = 'I see you know $firstNamedContactName!';
} else {
_contactText = 'No contacts to display.';
}
});
}
String? _pickFirstNamedContact(List<Person>? connections) {
return connections
?.firstWhere(
(Person person) => person.names != null,
)
.names
?.firstWhere(
(Name name) => name.displayName != null,
)
.displayName;
}
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error); // ignore: avoid_print
}
}
Future<void> _handleSignOut() => _googleSignIn.disconnect();
Widget _buildBody() {
final GoogleSignInAccount? user = _currentUser;
if (user != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
leading: GoogleUserCircleAvatar(
identity: user,
),
title: Text(user.displayName ?? ''),
subtitle: Text(user.email),
),
const Text('Signed in successfully.'),
Text(_contactText),
ElevatedButton(
onPressed: _handleSignOut,
child: const Text('SIGN OUT'),
),
ElevatedButton(
onPressed: _handleGetContact,
child: const Text('REFRESH'),
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text('You are not currently signed in.'),
ElevatedButton(
onPressed: _handleSignIn,
child: const Text('SIGN IN'),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In + googleapis'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}
| packages/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart",
"repo_id": "packages",
"token_count": 1829
} | 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.
import 'package:file_selector/file_selector.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
late FakeFileSelector fakePlatformImplementation;
const String initialDirectory = '/home/flutteruser';
const String confirmButtonText = 'Use this profile picture';
const String suggestedName = 'suggested_name';
const List<XTypeGroup> acceptedTypeGroups = <XTypeGroup>[
XTypeGroup(label: 'documents', mimeTypes: <String>[
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessing',
]),
XTypeGroup(label: 'images', extensions: <String>[
'jpg',
'png',
]),
];
setUp(() {
fakePlatformImplementation = FakeFileSelector();
FileSelectorPlatform.instance = fakePlatformImplementation;
});
group('openFile', () {
final XFile expectedFile = XFile('path');
test('works', () async {
fakePlatformImplementation
..setExpectations(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(<XFile>[expectedFile]);
final XFile? file = await openFile(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups,
);
expect(file, expectedFile);
});
test('works with no arguments', () async {
fakePlatformImplementation.setFileResponse(<XFile>[expectedFile]);
final XFile? file = await openFile();
expect(file, expectedFile);
});
test('sets the initial directory', () async {
fakePlatformImplementation
..setExpectations(initialDirectory: initialDirectory)
..setFileResponse(<XFile>[expectedFile]);
final XFile? file = await openFile(initialDirectory: initialDirectory);
expect(file, expectedFile);
});
test('sets the button confirmation label', () async {
fakePlatformImplementation
..setExpectations(confirmButtonText: confirmButtonText)
..setFileResponse(<XFile>[expectedFile]);
final XFile? file = await openFile(confirmButtonText: confirmButtonText);
expect(file, expectedFile);
});
test('sets the accepted type groups', () async {
fakePlatformImplementation
..setExpectations(acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(<XFile>[expectedFile]);
final XFile? file =
await openFile(acceptedTypeGroups: acceptedTypeGroups);
expect(file, expectedFile);
});
});
group('openFiles', () {
final List<XFile> expectedFiles = <XFile>[XFile('path')];
test('works', () async {
fakePlatformImplementation
..setExpectations(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(expectedFiles);
final List<XFile> files = await openFiles(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups,
);
expect(files, expectedFiles);
});
test('works with no arguments', () async {
fakePlatformImplementation.setFileResponse(expectedFiles);
final List<XFile> files = await openFiles();
expect(files, expectedFiles);
});
test('sets the initial directory', () async {
fakePlatformImplementation
..setExpectations(initialDirectory: initialDirectory)
..setFileResponse(expectedFiles);
final List<XFile> files =
await openFiles(initialDirectory: initialDirectory);
expect(files, expectedFiles);
});
test('sets the button confirmation label', () async {
fakePlatformImplementation
..setExpectations(confirmButtonText: confirmButtonText)
..setFileResponse(expectedFiles);
final List<XFile> files =
await openFiles(confirmButtonText: confirmButtonText);
expect(files, expectedFiles);
});
test('sets the accepted type groups', () async {
fakePlatformImplementation
..setExpectations(acceptedTypeGroups: acceptedTypeGroups)
..setFileResponse(expectedFiles);
final List<XFile> files =
await openFiles(acceptedTypeGroups: acceptedTypeGroups);
expect(files, expectedFiles);
});
});
group('getSaveLocation', () {
const String expectedSavePath = '/example/path';
test('works', () async {
const int expectedActiveFilter = 1;
fakePlatformImplementation
..setExpectations(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups,
suggestedName: suggestedName)
..setPathsResponse(<String>[expectedSavePath],
activeFilter: expectedActiveFilter);
final FileSaveLocation? location = await getSaveLocation(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
acceptedTypeGroups: acceptedTypeGroups,
suggestedName: suggestedName,
);
expect(location?.path, expectedSavePath);
expect(location?.activeFilter, acceptedTypeGroups[expectedActiveFilter]);
});
test('works with no arguments', () async {
fakePlatformImplementation.setPathsResponse(<String>[expectedSavePath]);
final FileSaveLocation? location = await getSaveLocation();
expect(location?.path, expectedSavePath);
});
test('sets the initial directory', () async {
fakePlatformImplementation
..setExpectations(initialDirectory: initialDirectory)
..setPathsResponse(<String>[expectedSavePath]);
final FileSaveLocation? location =
await getSaveLocation(initialDirectory: initialDirectory);
expect(location?.path, expectedSavePath);
});
test('sets the button confirmation label', () async {
fakePlatformImplementation
..setExpectations(confirmButtonText: confirmButtonText)
..setPathsResponse(<String>[expectedSavePath]);
final FileSaveLocation? location =
await getSaveLocation(confirmButtonText: confirmButtonText);
expect(location?.path, expectedSavePath);
});
test('sets the accepted type groups', () async {
fakePlatformImplementation
..setExpectations(acceptedTypeGroups: acceptedTypeGroups)
..setPathsResponse(<String>[expectedSavePath]);
final FileSaveLocation? location =
await getSaveLocation(acceptedTypeGroups: acceptedTypeGroups);
expect(location?.path, expectedSavePath);
});
test('sets the suggested name', () async {
fakePlatformImplementation
..setExpectations(suggestedName: suggestedName)
..setPathsResponse(<String>[expectedSavePath]);
final FileSaveLocation? location =
await getSaveLocation(suggestedName: suggestedName);
expect(location?.path, expectedSavePath);
});
});
group('getDirectoryPath', () {
const String expectedDirectoryPath = '/example/path';
test('works', () async {
fakePlatformImplementation
..setExpectations(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText)
..setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath = await getDirectoryPath(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
);
expect(directoryPath, expectedDirectoryPath);
});
test('works with no arguments', () async {
fakePlatformImplementation
.setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath = await getDirectoryPath();
expect(directoryPath, expectedDirectoryPath);
});
test('sets the initial directory', () async {
fakePlatformImplementation
..setExpectations(initialDirectory: initialDirectory)
..setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath =
await getDirectoryPath(initialDirectory: initialDirectory);
expect(directoryPath, expectedDirectoryPath);
});
test('sets the button confirmation label', () async {
fakePlatformImplementation
..setExpectations(confirmButtonText: confirmButtonText)
..setPathsResponse(<String>[expectedDirectoryPath]);
final String? directoryPath =
await getDirectoryPath(confirmButtonText: confirmButtonText);
expect(directoryPath, expectedDirectoryPath);
});
});
group('getDirectoryPaths', () {
const List<String> expectedDirectoryPaths = <String>[
'/example/path',
'/example/2/path'
];
test('works', () async {
fakePlatformImplementation
..setExpectations(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText)
..setPathsResponse(expectedDirectoryPaths);
final List<String?> directoryPaths = await getDirectoryPaths(
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText,
);
expect(directoryPaths, expectedDirectoryPaths);
});
test('works with no arguments', () async {
fakePlatformImplementation.setPathsResponse(expectedDirectoryPaths);
final List<String?> directoryPaths = await getDirectoryPaths();
expect(directoryPaths, expectedDirectoryPaths);
});
test('sets the initial directory', () async {
fakePlatformImplementation
..setExpectations(initialDirectory: initialDirectory)
..setPathsResponse(expectedDirectoryPaths);
final List<String?> directoryPaths =
await getDirectoryPaths(initialDirectory: initialDirectory);
expect(directoryPaths, expectedDirectoryPaths);
});
test('sets the button confirmation label', () async {
fakePlatformImplementation
..setExpectations(confirmButtonText: confirmButtonText)
..setPathsResponse(expectedDirectoryPaths);
final List<String?> directoryPaths =
await getDirectoryPaths(confirmButtonText: confirmButtonText);
expect(directoryPaths, expectedDirectoryPaths);
});
});
}
class FakeFileSelector extends Fake
with MockPlatformInterfaceMixin
implements FileSelectorPlatform {
// Expectations.
List<XTypeGroup>? acceptedTypeGroups = const <XTypeGroup>[];
String? initialDirectory;
String? confirmButtonText;
String? suggestedName;
// Return values.
List<XFile>? files;
List<String>? paths;
int? activeFilter;
void setExpectations({
List<XTypeGroup> acceptedTypeGroups = const <XTypeGroup>[],
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) {
this.acceptedTypeGroups = acceptedTypeGroups;
this.initialDirectory = initialDirectory;
this.suggestedName = suggestedName;
this.confirmButtonText = confirmButtonText;
}
// ignore: use_setters_to_change_properties
void setFileResponse(List<XFile> files) {
this.files = files;
}
void setPathsResponse(List<String> paths, {int? activeFilter}) {
this.paths = paths;
this.activeFilter = activeFilter;
}
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
expect(acceptedTypeGroups, this.acceptedTypeGroups);
expect(initialDirectory, this.initialDirectory);
expect(suggestedName, suggestedName);
return files?[0];
}
@override
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
expect(acceptedTypeGroups, this.acceptedTypeGroups);
expect(initialDirectory, this.initialDirectory);
expect(suggestedName, suggestedName);
return files!;
}
@override
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) async {
final FileSaveLocation? result = await getSaveLocation(
acceptedTypeGroups: acceptedTypeGroups,
options: SaveDialogOptions(
initialDirectory: initialDirectory,
suggestedName: suggestedName,
confirmButtonText: confirmButtonText,
),
);
return result?.path;
}
@override
Future<FileSaveLocation?> getSaveLocation({
List<XTypeGroup>? acceptedTypeGroups,
SaveDialogOptions options = const SaveDialogOptions(),
}) async {
expect(acceptedTypeGroups, this.acceptedTypeGroups);
expect(options.initialDirectory, initialDirectory);
expect(options.suggestedName, suggestedName);
expect(options.confirmButtonText, confirmButtonText);
final String? path = paths?[0];
final int? activeFilterIndex = activeFilter;
return path == null
? null
: FileSaveLocation(path,
activeFilter: activeFilterIndex == null
? null
: acceptedTypeGroups?[activeFilterIndex]);
}
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
expect(initialDirectory, this.initialDirectory);
expect(confirmButtonText, this.confirmButtonText);
return paths?[0];
}
@override
Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) async {
expect(initialDirectory, this.initialDirectory);
expect(confirmButtonText, this.confirmButtonText);
return paths!;
}
}
| packages/packages/file_selector/file_selector/test/file_selector_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector/test/file_selector_test.dart",
"repo_id": "packages",
"token_count": 4799
} | 1,014 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name="dev.flutter.packages.file_selector_android_example.DriverExtensionActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.Entrypoint"
android:value="integrationTestMain" />
</activity>
<provider
android:authorities="file_selector_android_test"
android:name=".TestContentProvider"
android:exported="true"/>
</application>
</manifest>
| packages/packages/file_selector/file_selector_android/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 485
} | 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.
// 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, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:file_selector_ios/src/messages.g.dart';
class _TestFileSelectorApiCodec extends StandardMessageCodec {
const _TestFileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileSelectorConfig) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileSelectorConfig.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestFileSelectorApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = _TestFileSelectorApiCodec();
Future<List<String?>> openFile(FileSelectorConfig config);
static void setup(TestFileSelectorApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null.');
final List<Object?> args = (message as List<Object?>?)!;
final FileSelectorConfig? arg_config =
(args[0] as FileSelectorConfig?);
assert(arg_config != null,
'Argument for dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile was null, expected non-null FileSelectorConfig.');
try {
final List<String?> output = await api.openFile(arg_config!);
return <Object?>[output];
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/file_selector/file_selector_ios/test/test_api.g.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_ios/test/test_api.g.dart",
"repo_id": "packages",
"token_count": 1252
} | 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.
#include <gtest/gtest.h>
#include <gtk/gtk.h>
int main(int argc, char** argv) {
gtk_init(0, nullptr);
testing::InitGoogleTest(&argc, argv);
int exit_code = RUN_ALL_TESTS();
return exit_code;
}
| packages/packages/file_selector/file_selector_linux/linux/test/test_main.cc/0 | {
"file_path": "packages/packages/file_selector/file_selector_linux/linux/test/test_main.cc",
"repo_id": "packages",
"token_count": 131
} | 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 FlutterMacOS
import UniformTypeIdentifiers
import XCTest
@testable import file_selector_macos
class TestPanelController: NSObject, PanelController {
// The last panels that the relevant display methods were called on.
public var savePanel: NSSavePanel?
public var openPanel: NSOpenPanel?
// Mock return values for the display methods.
public var saveURL: URL?
public var openURLs: [URL]?
func display(
_ panel: NSSavePanel, for window: NSWindow?, completionHandler handler: @escaping (URL?) -> Void
) {
savePanel = panel
handler(saveURL)
}
func display(
_ panel: NSOpenPanel, for window: NSWindow?,
completionHandler handler: @escaping ([URL]?) -> Void
) {
openPanel = panel
handler(openURLs)
}
}
class TestViewProvider: NSObject, ViewProvider {
var view: NSView? {
window?.contentView
}
var window: NSWindow? = NSWindow()
}
class ExampleTests: XCTestCase {
func testOpenSimple() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
XCTAssertTrue(panel.canChooseFiles)
// For consistency across platforms, directory selection is disabled.
XCTAssertFalse(panel.canChooseDirectories)
}
}
func testOpenWithArguments() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
directoryPath: "/some/dir",
nameFieldStringValue: "a name",
prompt: "Open it!"))
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
XCTAssertEqual(panel.directoryURL?.path, "/some/dir")
XCTAssertEqual(panel.nameFieldStringValue, "a name")
XCTAssertEqual(panel.prompt, "Open it!")
}
}
func testOpenMultiple() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPaths = ["/foo/bar", "/foo/baz"]
panelController.openURLs = returnPaths.map({ path in URL(fileURLWithPath: path) })
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths.count, returnPaths.count)
XCTAssertEqual(paths[0], returnPaths[0])
XCTAssertEqual(paths[1], returnPaths[1])
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
}
func testOpenWithFilter() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
allowedFileTypes: AllowedTypes(
extensions: ["txt", "json"],
mimeTypes: ["text/html"],
utis: ["public.text", "public.image"])))
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
if #available(macOS 11.0, *) {
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.plainText))
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.json))
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.html))
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.image))
} else {
// MIME type is not supported for the legacy codepath, but the rest should be set.
XCTAssertEqual(panel.allowedFileTypes, ["txt", "json", "public.text", "public.image"])
}
}
}
func testFilterUnknownFileExtension() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let unknownExtension = "somenewextension"
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
allowedFileTypes: AllowedTypes(
extensions: [unknownExtension],
mimeTypes: [],
utis: [])))
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
if #available(macOS 11.0, *) {
XCTAssertEqual(panel.allowedContentTypes.count, 1)
XCTAssertEqual(panel.allowedContentTypes[0].preferredFilenameExtension, unknownExtension)
// If this isn't true, the dynamic type created for the extension won't work as a file
// extension filter.
XCTAssertTrue(panel.allowedContentTypes[0].conforms(to: UTType.data))
} else {
XCTAssertEqual(panel.allowedFileTypes, [unknownExtension])
}
}
}
func testOpenWithFilterLegacy() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
plugin.forceLegacyTypes = true
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
allowedFileTypes: AllowedTypes(
extensions: ["txt", "json"],
mimeTypes: ["text/html"],
utis: ["public.text", "public.image"])))
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
// On the legacy path, the allowedFileTypes should be set directly.
XCTAssertEqual(panel.allowedFileTypes, ["txt", "json", "public.text", "public.image"])
// They should also be translated to corresponding allowed content types.
if #available(macOS 11.0, *) {
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.plainText))
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.json))
XCTAssertTrue(panel.allowedContentTypes.contains(UTType.image))
// MIME type is not supported for the legacy codepath.
XCTAssertFalse(panel.allowedContentTypes.contains(UTType.html))
}
}
}
func testOpenCancel() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths.count, 0)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
}
func testSaveSimple() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.saveURL = URL(fileURLWithPath: returnPath)
let called = XCTestExpectation()
let options = SavePanelOptions()
plugin.displaySavePanel(options: options) { result in
switch result {
case .success(let path):
XCTAssertEqual(path, returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.savePanel)
}
func testSaveWithArguments() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.saveURL = URL(fileURLWithPath: returnPath)
let called = XCTestExpectation()
let options = SavePanelOptions(
directoryPath: "/some/dir",
prompt: "Save it!")
plugin.displaySavePanel(options: options) { result in
switch result {
case .success(let path):
XCTAssertEqual(path, returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.savePanel)
if let panel = panelController.savePanel {
XCTAssertEqual(panel.directoryURL?.path, "/some/dir")
XCTAssertEqual(panel.prompt, "Save it!")
}
}
func testSaveCancel() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let called = XCTestExpectation()
let options = SavePanelOptions()
plugin.displaySavePanel(options: options) { result in
switch result {
case .success(let path):
XCTAssertNil(path)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.savePanel)
}
func testGetDirectorySimple() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPath = "/foo/bar"
panelController.openURLs = [URL(fileURLWithPath: returnPath)]
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths[0], returnPath)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
XCTAssertTrue(panel.canChooseDirectories)
// For consistency across platforms, file selection is disabled.
XCTAssertFalse(panel.canChooseFiles)
// The Dart API only allows a single directory to be returned, so users shouldn't be allowed
// to select multiple.
XCTAssertFalse(panel.allowsMultipleSelection)
}
}
func testGetDirectoryCancel() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths.count, 0)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
}
func testGetDirectoriesMultiple() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let returnPaths = ["/foo/bar", "/foo/test"]
panelController.openURLs = returnPaths.map({ path in URL(fileURLWithPath: path) })
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths, returnPaths)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
if let panel = panelController.openPanel {
XCTAssertTrue(panel.canChooseDirectories)
// For consistency across platforms, file selection is disabled.
XCTAssertFalse(panel.canChooseFiles)
XCTAssertTrue(panel.allowsMultipleSelection)
}
}
func testGetDirectoryMultipleCancel() throws {
let panelController = TestPanelController()
let plugin = FileSelectorPlugin(
viewProvider: TestViewProvider(),
panelController: panelController)
let called = XCTestExpectation()
let options = OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions())
plugin.displayOpenPanel(options: options) { result in
switch result {
case .success(let paths):
XCTAssertEqual(paths.count, 0)
case .failure(let error):
XCTFail("\(error)")
}
called.fulfill()
}
wait(for: [called])
XCTAssertNotNil(panelController.openPanel)
}
}
| packages/packages/file_selector/file_selector_macos/example/macos/RunnerTests/RunnerTests.swift/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/example/macos/RunnerTests/RunnerTests.swift",
"repo_id": "packages",
"token_count": 6042
} | 1,018 |
# file\_selector\_web
The web implementation of [`file_selector`][1].
## Usage
This package is [endorsed][2], which means you can simply use `file_selector`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
[1]: https://pub.dev/packages/file_selector
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
## Limitations on the Web platform
### `cancel` event
The `cancel` event used by the web plugin to detect when users close the file
selector without picking a file is relatively new, and will only work in
recent browsers.
See:
* https://caniuse.com/mdn-api_htmlinputelement_cancel_event
| packages/packages/file_selector/file_selector_web/README.md/0 | {
"file_path": "packages/packages/file_selector/file_selector_web/README.md",
"repo_id": "packages",
"token_count": 264
} | 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.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [FileSelectorPlatform] for Windows.
class FileSelectorWindows extends FileSelectorPlatform {
final FileSelectorApi _hostApi = FileSelectorApi();
/// Registers the Windows implementation.
static void registerWith() {
FileSelectorPlatform.instance = FileSelectorWindows();
}
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
initialDirectory,
confirmButtonText);
return result.paths.isEmpty ? null : XFile(result.paths.first!);
}
@override
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: true,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
initialDirectory,
confirmButtonText);
return result.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 FileDialogResult result = await _hostApi.showSaveDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
options.initialDirectory,
options.suggestedName,
options.confirmButtonText);
final int? groupIndex = result.typeGroupIndex;
return result.paths.isEmpty
? null
: FileSaveLocation(result.paths.first!,
activeFilter:
groupIndex == null ? null : acceptedTypeGroups?[groupIndex]);
}
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: true,
allowedTypes: <TypeGroup>[],
),
initialDirectory,
confirmButtonText);
return result.paths.isEmpty ? null : result.paths.first!;
}
@override
Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) async {
final FileDialogResult result = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: true,
selectFolders: true,
allowedTypes: <TypeGroup>[],
),
initialDirectory,
confirmButtonText);
return result.paths.isEmpty ? <String>[] : List<String>.from(result.paths);
}
}
List<TypeGroup> _typeGroupsFromXTypeGroups(List<XTypeGroup>? xtypes) {
return (xtypes ?? <XTypeGroup>[]).map((XTypeGroup xtype) {
if (!xtype.allowsAny && (xtype.extensions?.isEmpty ?? true)) {
throw ArgumentError('Provided type group $xtype does not allow '
'all files, but does not set any of the Windows-supported filter '
'categories. "extensions" must be non-empty for Windows if '
'anything is non-empty.');
}
return TypeGroup(
label: xtype.label ?? '', extensions: xtype.extensions ?? <String>[]);
}).toList();
}
| packages/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart",
"repo_id": "packages",
"token_count": 1665
} | 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.
// Autogenerated from Pigeon (v10.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#undef _HAS_EXCEPTIONS
#include "messages.g.h"
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace file_selector_windows {
using flutter::BasicMessageChannel;
using flutter::CustomEncodableValue;
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
// TypeGroup
TypeGroup::TypeGroup(const std::string& label, const EncodableList& extensions)
: label_(label), extensions_(extensions) {}
const std::string& TypeGroup::label() const { return label_; }
void TypeGroup::set_label(std::string_view value_arg) { label_ = value_arg; }
const EncodableList& TypeGroup::extensions() const { return extensions_; }
void TypeGroup::set_extensions(const EncodableList& value_arg) {
extensions_ = value_arg;
}
EncodableList TypeGroup::ToEncodableList() const {
EncodableList list;
list.reserve(2);
list.push_back(EncodableValue(label_));
list.push_back(EncodableValue(extensions_));
return list;
}
TypeGroup TypeGroup::FromEncodableList(const EncodableList& list) {
TypeGroup decoded(std::get<std::string>(list[0]),
std::get<EncodableList>(list[1]));
return decoded;
}
// SelectionOptions
SelectionOptions::SelectionOptions(bool allow_multiple, bool select_folders,
const EncodableList& allowed_types)
: allow_multiple_(allow_multiple),
select_folders_(select_folders),
allowed_types_(allowed_types) {}
bool SelectionOptions::allow_multiple() const { return allow_multiple_; }
void SelectionOptions::set_allow_multiple(bool value_arg) {
allow_multiple_ = value_arg;
}
bool SelectionOptions::select_folders() const { return select_folders_; }
void SelectionOptions::set_select_folders(bool value_arg) {
select_folders_ = value_arg;
}
const EncodableList& SelectionOptions::allowed_types() const {
return allowed_types_;
}
void SelectionOptions::set_allowed_types(const EncodableList& value_arg) {
allowed_types_ = value_arg;
}
EncodableList SelectionOptions::ToEncodableList() const {
EncodableList list;
list.reserve(3);
list.push_back(EncodableValue(allow_multiple_));
list.push_back(EncodableValue(select_folders_));
list.push_back(EncodableValue(allowed_types_));
return list;
}
SelectionOptions SelectionOptions::FromEncodableList(
const EncodableList& list) {
SelectionOptions decoded(std::get<bool>(list[0]), std::get<bool>(list[1]),
std::get<EncodableList>(list[2]));
return decoded;
}
// FileDialogResult
FileDialogResult::FileDialogResult(const EncodableList& paths)
: paths_(paths) {}
FileDialogResult::FileDialogResult(const EncodableList& paths,
const int64_t* type_group_index)
: paths_(paths),
type_group_index_(type_group_index
? std::optional<int64_t>(*type_group_index)
: std::nullopt) {}
const EncodableList& FileDialogResult::paths() const { return paths_; }
void FileDialogResult::set_paths(const EncodableList& value_arg) {
paths_ = value_arg;
}
const int64_t* FileDialogResult::type_group_index() const {
return type_group_index_ ? &(*type_group_index_) : nullptr;
}
void FileDialogResult::set_type_group_index(const int64_t* value_arg) {
type_group_index_ =
value_arg ? std::optional<int64_t>(*value_arg) : std::nullopt;
}
void FileDialogResult::set_type_group_index(int64_t value_arg) {
type_group_index_ = value_arg;
}
EncodableList FileDialogResult::ToEncodableList() const {
EncodableList list;
list.reserve(2);
list.push_back(EncodableValue(paths_));
list.push_back(type_group_index_ ? EncodableValue(*type_group_index_)
: EncodableValue());
return list;
}
FileDialogResult FileDialogResult::FromEncodableList(
const EncodableList& list) {
FileDialogResult decoded(std::get<EncodableList>(list[0]));
auto& encodable_type_group_index = list[1];
if (!encodable_type_group_index.IsNull()) {
decoded.set_type_group_index(encodable_type_group_index.LongValue());
}
return decoded;
}
FileSelectorApiCodecSerializer::FileSelectorApiCodecSerializer() {}
EncodableValue FileSelectorApiCodecSerializer::ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const {
switch (type) {
case 128:
return CustomEncodableValue(FileDialogResult::FromEncodableList(
std::get<EncodableList>(ReadValue(stream))));
case 129:
return CustomEncodableValue(SelectionOptions::FromEncodableList(
std::get<EncodableList>(ReadValue(stream))));
case 130:
return CustomEncodableValue(TypeGroup::FromEncodableList(
std::get<EncodableList>(ReadValue(stream))));
default:
return flutter::StandardCodecSerializer::ReadValueOfType(type, stream);
}
}
void FileSelectorApiCodecSerializer::WriteValue(
const EncodableValue& value, flutter::ByteStreamWriter* stream) const {
if (const CustomEncodableValue* custom_value =
std::get_if<CustomEncodableValue>(&value)) {
if (custom_value->type() == typeid(FileDialogResult)) {
stream->WriteByte(128);
WriteValue(
EncodableValue(
std::any_cast<FileDialogResult>(*custom_value).ToEncodableList()),
stream);
return;
}
if (custom_value->type() == typeid(SelectionOptions)) {
stream->WriteByte(129);
WriteValue(
EncodableValue(
std::any_cast<SelectionOptions>(*custom_value).ToEncodableList()),
stream);
return;
}
if (custom_value->type() == typeid(TypeGroup)) {
stream->WriteByte(130);
WriteValue(EncodableValue(
std::any_cast<TypeGroup>(*custom_value).ToEncodableList()),
stream);
return;
}
}
flutter::StandardCodecSerializer::WriteValue(value, stream);
}
/// The codec used by FileSelectorApi.
const flutter::StandardMessageCodec& FileSelectorApi::GetCodec() {
return flutter::StandardMessageCodec::GetInstance(
&FileSelectorApiCodecSerializer::GetInstance());
}
// Sets up an instance of `FileSelectorApi` to handle messages through the
// `binary_messenger`.
void FileSelectorApi::SetUp(flutter::BinaryMessenger* binary_messenger,
FileSelectorApi* api) {
{
auto channel = std::make_unique<BasicMessageChannel<>>(
binary_messenger, "dev.flutter.pigeon.FileSelectorApi.showOpenDialog",
&GetCodec());
if (api != nullptr) {
channel->SetMessageHandler(
[api](const EncodableValue& message,
const flutter::MessageReply<EncodableValue>& reply) {
try {
const auto& args = std::get<EncodableList>(message);
const auto& encodable_options_arg = args.at(0);
if (encodable_options_arg.IsNull()) {
reply(WrapError("options_arg unexpectedly null."));
return;
}
const auto& options_arg = std::any_cast<const SelectionOptions&>(
std::get<CustomEncodableValue>(encodable_options_arg));
const auto& encodable_initial_directory_arg = args.at(1);
const auto* initial_directory_arg =
std::get_if<std::string>(&encodable_initial_directory_arg);
const auto& encodable_confirm_button_text_arg = args.at(2);
const auto* confirm_button_text_arg =
std::get_if<std::string>(&encodable_confirm_button_text_arg);
ErrorOr<FileDialogResult> output = api->ShowOpenDialog(
options_arg, initial_directory_arg, confirm_button_text_arg);
if (output.has_error()) {
reply(WrapError(output.error()));
return;
}
EncodableList wrapped;
wrapped.push_back(
CustomEncodableValue(std::move(output).TakeValue()));
reply(EncodableValue(std::move(wrapped)));
} catch (const std::exception& exception) {
reply(WrapError(exception.what()));
}
});
} else {
channel->SetMessageHandler(nullptr);
}
}
{
auto channel = std::make_unique<BasicMessageChannel<>>(
binary_messenger, "dev.flutter.pigeon.FileSelectorApi.showSaveDialog",
&GetCodec());
if (api != nullptr) {
channel->SetMessageHandler(
[api](const EncodableValue& message,
const flutter::MessageReply<EncodableValue>& reply) {
try {
const auto& args = std::get<EncodableList>(message);
const auto& encodable_options_arg = args.at(0);
if (encodable_options_arg.IsNull()) {
reply(WrapError("options_arg unexpectedly null."));
return;
}
const auto& options_arg = std::any_cast<const SelectionOptions&>(
std::get<CustomEncodableValue>(encodable_options_arg));
const auto& encodable_initial_directory_arg = args.at(1);
const auto* initial_directory_arg =
std::get_if<std::string>(&encodable_initial_directory_arg);
const auto& encodable_suggested_name_arg = args.at(2);
const auto* suggested_name_arg =
std::get_if<std::string>(&encodable_suggested_name_arg);
const auto& encodable_confirm_button_text_arg = args.at(3);
const auto* confirm_button_text_arg =
std::get_if<std::string>(&encodable_confirm_button_text_arg);
ErrorOr<FileDialogResult> output = api->ShowSaveDialog(
options_arg, initial_directory_arg, suggested_name_arg,
confirm_button_text_arg);
if (output.has_error()) {
reply(WrapError(output.error()));
return;
}
EncodableList wrapped;
wrapped.push_back(
CustomEncodableValue(std::move(output).TakeValue()));
reply(EncodableValue(std::move(wrapped)));
} catch (const std::exception& exception) {
reply(WrapError(exception.what()));
}
});
} else {
channel->SetMessageHandler(nullptr);
}
}
}
EncodableValue FileSelectorApi::WrapError(std::string_view error_message) {
return EncodableValue(
EncodableList{EncodableValue(std::string(error_message)),
EncodableValue("Error"), EncodableValue()});
}
EncodableValue FileSelectorApi::WrapError(const FlutterError& error) {
return EncodableValue(EncodableList{EncodableValue(error.code()),
EncodableValue(error.message()),
error.details()});
}
} // namespace file_selector_windows
| packages/packages/file_selector/file_selector_windows/windows/messages.g.cpp/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/windows/messages.g.cpp",
"repo_id": "packages",
"token_count": 4816
} | 1,021 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/flutter_adaptive_scaffold/example/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,022 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/flutter_image/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "packages/packages/flutter_image/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,023 |
#!/bin/bash
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Dart sources are only allowed in the example directory.
filecount=`find . -name '*.dart' ! -path './example/*' | wc -l`
if [ $filecount -ne 0 ]
then
echo 'Dart sources are not allowed in this package:'
find . -name '*.dart'
exit 1
fi
| packages/packages/flutter_lints/run_tests.sh/0 | {
"file_path": "packages/packages/flutter_lints/run_tests.sh",
"repo_id": "packages",
"token_count": 131
} | 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.
import 'package:flutter/material.dart';
import '../screens/demo_screen.dart';
import '../shared/markdown_demo_widget.dart';
// ignore_for_file: public_member_api_docs
class DemoCard extends StatelessWidget {
const DemoCard({super.key, required this.widget});
final MarkdownDemoWidget widget;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => Navigator.pushNamed(
context,
DemoScreen.routeName,
arguments: widget,
),
child: Container(
alignment: Alignment.center,
child: ConstrainedBox(
constraints:
const BoxConstraints(minHeight: 50, minWidth: 425, maxWidth: 425),
child: Card(
color: Colors.blue,
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.title,
style: Theme.of(context).primaryTextTheme.headlineSmall,
),
const SizedBox(
height: 6,
),
Text(
widget.description,
style: Theme.of(context).primaryTextTheme.bodyLarge,
),
],
),
)),
),
),
);
}
}
| packages/packages/flutter_markdown/example/lib/screens/demo_card.dart/0 | {
"file_path": "packages/packages/flutter_markdown/example/lib/screens/demo_card.dart",
"repo_id": "packages",
"token_count": 892
} | 1,025 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/flutter_markdown/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/flutter_markdown/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,026 |
// 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:flutter/cupertino.dart' show CupertinoTheme;
import 'package:flutter/material.dart' show Theme;
import 'package:flutter/widgets.dart';
import 'style_sheet.dart';
import 'widget.dart';
/// Type for a function that creates image widgets.
typedef ImageBuilder = Widget Function(
Uri uri, String? imageDirectory, double? width, double? height);
/// A default image builder handling http/https, resource, and file URLs.
// ignore: prefer_function_declarations_over_variables
final ImageBuilder kDefaultImageBuilder = (
Uri uri,
String? imageDirectory,
double? width,
double? height,
) {
if (uri.scheme == 'http' || uri.scheme == 'https') {
return Image.network(uri.toString(), width: width, height: height);
} else if (uri.scheme == 'data') {
return _handleDataSchemeUri(uri, width, height);
} else if (uri.scheme == 'resource') {
return Image.asset(uri.path, width: width, height: height);
} else {
final Uri fileUri = imageDirectory != null
? Uri.parse(imageDirectory + uri.toString())
: uri;
if (fileUri.scheme == 'http' || fileUri.scheme == 'https') {
return Image.network(fileUri.toString(), width: width, height: height);
} else {
return Image.file(File.fromUri(fileUri), width: width, height: height);
}
}
};
/// A default style sheet generator.
final MarkdownStyleSheet Function(BuildContext, MarkdownStyleSheetBaseTheme?)
// ignore: prefer_function_declarations_over_variables
kFallbackStyle = (
BuildContext context,
MarkdownStyleSheetBaseTheme? baseTheme,
) {
MarkdownStyleSheet result;
switch (baseTheme) {
case MarkdownStyleSheetBaseTheme.platform:
result = (Platform.isIOS || Platform.isMacOS)
? MarkdownStyleSheet.fromCupertinoTheme(CupertinoTheme.of(context))
: MarkdownStyleSheet.fromTheme(Theme.of(context));
case MarkdownStyleSheetBaseTheme.cupertino:
result =
MarkdownStyleSheet.fromCupertinoTheme(CupertinoTheme.of(context));
case MarkdownStyleSheetBaseTheme.material:
// ignore: no_default_cases
default:
result = MarkdownStyleSheet.fromTheme(Theme.of(context));
}
return result.copyWith(
textScaler: MediaQuery.textScalerOf(context),
);
};
Widget _handleDataSchemeUri(
Uri uri, final double? width, final double? height) {
final String mimeType = uri.data!.mimeType;
if (mimeType.startsWith('image/')) {
return Image.memory(
uri.data!.contentAsBytes(),
width: width,
height: height,
);
} else if (mimeType.startsWith('text/')) {
return Text(uri.data!.contentAsString());
}
return const SizedBox();
}
| packages/packages/flutter_markdown/lib/src/_functions_io.dart/0 | {
"file_path": "packages/packages/flutter_markdown/lib/src/_functions_io.dart",
"repo_id": "packages",
"token_count": 998
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils.dart';
void main() => defineTests();
void defineTests() {
group('HTML', () {
testWidgets(
'ignore tags',
(WidgetTester tester) async {
final List<String> data = <String>[
'Line 1\n<p>HTML content</p>\nLine 2',
'Line 1\n<!-- HTML\n comment\n ignored --><\nLine 2'
];
for (final String line in data) {
await tester.pumpWidget(boilerplate(MarkdownBody(data: line)));
final Iterable<Widget> widgets = tester.allWidgets;
expectTextStrings(widgets, <String>['Line 1', 'Line 2']);
}
},
);
testWidgets(
"doesn't convert & to & when parsing",
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
const Markdown(data: '&'),
),
);
expectTextStrings(tester.allWidgets, <String>['&']);
},
);
testWidgets(
"doesn't convert < to < when parsing",
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
const Markdown(data: '<'),
),
);
expectTextStrings(tester.allWidgets, <String>['<']);
},
);
});
}
| packages/packages/flutter_markdown/test/html_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/html_test.dart",
"repo_id": "packages",
"token_count": 682
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils.dart';
void main() => defineTests();
void defineTests() {
group('Uri Data Scheme', () {
testWidgets(
'should work with image in uri data scheme',
(WidgetTester tester) async {
const String data =
'';
await tester.pumpWidget(
boilerplate(
const Markdown(data: data),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
final Image image =
widgets.firstWhere((Widget widget) => widget is Image) as Image;
expect(image.image.runtimeType, MemoryImage);
},
);
testWidgets(
'should work with base64 text in uri data scheme',
(WidgetTester tester) async {
const String imageData = '';
await tester.pumpWidget(
boilerplate(
const Markdown(data: imageData),
),
);
final Text widget = tester.widget(find.byType(Text));
expect(widget.runtimeType, Text);
expect(widget.data, 'Flutter');
},
);
testWidgets(
'should work with text in uri data scheme',
(WidgetTester tester) async {
const String imageData = '';
await tester.pumpWidget(
boilerplate(
const Markdown(data: imageData),
),
);
final Text widget = tester.widget(find.byType(Text));
expect(widget.runtimeType, Text);
expect(widget.data, 'Hello, Flutter');
},
);
testWidgets(
'should work with empty uri data scheme',
(WidgetTester tester) async {
const String imageData = '';
await tester.pumpWidget(
boilerplate(
const Markdown(data: imageData),
),
);
final Text widget = tester.widget(find.byType(Text));
expect(widget.runtimeType, Text);
expect(widget.data, '');
},
);
testWidgets(
'should work with unsupported mime types of uri data scheme',
(WidgetTester tester) async {
const String data = '';
await tester.pumpWidget(
boilerplate(
const Markdown(data: data),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
final SizedBox widget = widgets
.firstWhere((Widget widget) => widget is SizedBox) as SizedBox;
expect(widget.runtimeType, SizedBox);
},
);
});
}
| packages/packages/flutter_markdown/test/uri_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/uri_test.dart",
"repo_id": "packages",
"token_count": 1296
} | 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.
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'dart:math';
import 'package:intl/intl.dart';
import 'package:meta/meta.dart';
import 'common.dart';
import 'io.dart';
import 'terminal.dart' show OutputPreferences, Terminal, TerminalColor;
const int kDefaultStatusPadding = 59;
final NumberFormat kSecondsFormat = NumberFormat('0.0');
final NumberFormat kMillisecondsFormat = NumberFormat.decimalPattern();
/// Smallest column that will be used for text wrapping. If the requested column
/// width is smaller than this, then this is what will be used.
const int kMinColumnWidth = 10;
/// A factory for generating [Stopwatch] instances for [Status] instances.
class StopwatchFactory {
/// const constructor so that subclasses may be const.
const StopwatchFactory();
/// Create a new [Stopwatch] instance.
///
/// The optional [name] parameter is useful in tests when there are multiple
/// instances being created.
Stopwatch createStopwatch([String name = '']) => Stopwatch();
}
typedef VoidCallback = void Function();
abstract class Logger {
/// Whether or not this logger should print [printTrace] messages.
bool get isVerbose => false;
/// If true, silences the logger output.
bool quiet = false;
/// If true, this logger supports color output.
bool get supportsColor;
/// If true, this logger is connected to a terminal.
bool get hasTerminal;
/// If true, then [printError] has been called at least once for this logger
/// since the last time it was set to false.
bool hadErrorOutput = false;
/// If true, then [printWarning] has been called at least once for this logger
/// since the last time it was reset to false.
bool hadWarningOutput = false;
/// Causes [checkForFatalLogs] to call [throwToolExit] when it is called if
/// [hadWarningOutput] is true.
bool fatalWarnings = false;
/// Returns the terminal attached to this logger.
Terminal get terminal;
/// Display an error `message` to the user. Commands should use this if they
/// fail in some way. Errors are typically followed shortly by a call to
/// [throwToolExit] to terminate the run.
///
/// The `message` argument is printed to the stderr in [TerminalColor.red] by
/// default.
///
/// The `stackTrace` argument is the stack trace that will be printed if
/// supplied.
///
/// The `emphasis` argument will cause the output message be printed in bold text.
///
/// The `color` argument will print the message in the supplied color instead
/// of the default of red. Colors will not be printed if the output terminal
/// doesn't support them.
///
/// The `indent` argument specifies the number of spaces to indent the overall
/// message. If wrapping is enabled in [outputPreferences], then the wrapped
/// lines will be indented as well.
///
/// If `hangingIndent` is specified, then any wrapped lines will be indented
/// by this much more than the first line, if wrapping is enabled in
/// [outputPreferences].
///
/// If `wrap` is specified, then it overrides the
/// `outputPreferences.wrapText` setting.
void printError(
String message, {
StackTrace? stackTrace,
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
});
/// Display a warning `message` to the user. Commands should use this if they
/// important information to convey to the user that is not fatal.
///
/// The `message` argument is printed to the stderr in [TerminalColor.cyan] by
/// default.
///
/// The `emphasis` argument will cause the output message be printed in bold text.
///
/// The `color` argument will print the message in the supplied color instead
/// of the default of cyan. Colors will not be printed if the output terminal
/// doesn't support them.
///
/// The `indent` argument specifies the number of spaces to indent the overall
/// message. If wrapping is enabled in [outputPreferences], then the wrapped
/// lines will be indented as well.
///
/// If `hangingIndent` is specified, then any wrapped lines will be indented
/// by this much more than the first line, if wrapping is enabled in
/// [outputPreferences].
///
/// If `wrap` is specified, then it overrides the
/// `outputPreferences.wrapText` setting.
void printWarning(
String message, {
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
});
/// Display normal output of the command. This should be used for things like
/// progress messages, success messages, or just normal command output.
///
/// The `message` argument is printed to the stdout.
///
/// The `stackTrace` argument is the stack trace that will be printed if
/// supplied.
///
/// If the `emphasis` argument is true, it will cause the output message be
/// printed in bold text. Defaults to false.
///
/// The `color` argument will print the message in the supplied color instead
/// of the default of red. Colors will not be printed if the output terminal
/// doesn't support them.
///
/// If `newline` is true, then a newline will be added after printing the
/// status. Defaults to true.
///
/// The `indent` argument specifies the number of spaces to indent the overall
/// message. If wrapping is enabled in [outputPreferences], then the wrapped
/// lines will be indented as well.
///
/// If `hangingIndent` is specified, then any wrapped lines will be indented
/// by this much more than the first line, if wrapping is enabled in
/// [outputPreferences].
///
/// If `wrap` is specified, then it overrides the
/// `outputPreferences.wrapText` setting.
void printStatus(
String message, {
bool? emphasis,
TerminalColor? color,
bool? newline,
int? indent,
int? hangingIndent,
bool? wrap,
});
/// Display the [message] inside a box.
///
/// For example, this is the generated output:
///
/// ┌─ [title] ─┐
/// │ [message] │
/// └───────────┘
///
/// If a terminal is attached, the lines in [message] are automatically wrapped based on
/// the available columns.
///
/// Use this utility only to highlight a message in the logs.
///
/// This is particularly useful when the message can be easily missed because of clutter
/// generated by other commands invoked by the tool.
///
/// One common use case is to provide actionable steps in a Flutter app when a Gradle
/// error is printed.
///
/// In the future, this output can be integrated with an IDE like VS Code to display a
/// notification, and allow the user to trigger an action. e.g. run a migration.
void printBox(
String message, {
String? title,
});
/// Use this for verbose tracing output. Users can turn this output on in order
/// to help diagnose issues with the toolchain or with their setup.
void printTrace(String message);
/// Start an indeterminate progress display.
///
/// The `message` argument is the message to display to the user.
///
/// The `progressId` argument provides an ID that can be used to identify
/// this type of progress (e.g. `hot.reload`, `hot.restart`).
///
/// The `progressIndicatorPadding` can optionally be used to specify the width
/// of the space into which the `message` is placed before the progress
/// indicator, if any. It is ignored if the message is longer.
Status startProgress(
String message, {
String? progressId,
int progressIndicatorPadding = kDefaultStatusPadding,
});
/// A [SilentStatus] or an [AnonymousSpinnerStatus] (depending on whether the
/// terminal is fancy enough), already started.
Status startSpinner({
VoidCallback? onFinish,
Duration? timeout,
SlowWarningCallback? slowWarningCallback,
});
/// Clears all output.
void clear();
/// If [fatalWarnings] is set, causes the logger to check if
/// [hadWarningOutput] is true, and then to call [throwToolExit] if so.
///
/// The [fatalWarnings] flag can be set from the command line with the
/// "--fatal-warnings" option on commands that support it.
void checkForFatalLogs() {
if (fatalWarnings && (hadWarningOutput || hadErrorOutput)) {
throwToolExit(
'Logger received ${hadErrorOutput ? 'error' : 'warning'} output '
'during the run, and "--fatal-warnings" is enabled.');
}
}
}
class StdoutLogger extends Logger {
StdoutLogger({
required this.terminal,
required Stdio stdio,
required OutputPreferences outputPreferences,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
}) : _stdio = stdio,
_outputPreferences = outputPreferences,
_stopwatchFactory = stopwatchFactory;
@override
final Terminal terminal;
final OutputPreferences _outputPreferences;
final Stdio _stdio;
final StopwatchFactory _stopwatchFactory;
Status? _status;
@override
bool get isVerbose => false;
@override
bool get supportsColor => terminal.supportsColor;
@override
bool get hasTerminal => _stdio.stdinHasTerminal;
@override
void printError(
String message, {
StackTrace? stackTrace,
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
hadErrorOutput = true;
_status?.pause();
message = wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis ?? false) {
message = terminal.bolden(message);
}
message = terminal.color(message, color ?? TerminalColor.red);
writeToStdErr('$message\n');
if (stackTrace != null) {
writeToStdErr('$stackTrace\n');
}
_status?.resume();
}
@override
void printWarning(
String message, {
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
hadWarningOutput = true;
_status?.pause();
message = wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis ?? false) {
message = terminal.bolden(message);
}
message = terminal.color(message, color ?? TerminalColor.cyan);
writeToStdErr('$message\n');
_status?.resume();
}
@override
void printStatus(
String message, {
bool? emphasis,
TerminalColor? color,
bool? newline,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
_status?.pause();
message = wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis ?? false) {
message = terminal.bolden(message);
}
if (color != null) {
message = terminal.color(message, color);
}
if (newline ?? true) {
message = '$message\n';
}
writeToStdOut(message);
_status?.resume();
}
@override
void printBox(
String message, {
String? title,
}) {
_status?.pause();
_generateBox(
title: title,
message: message,
wrapColumn: _outputPreferences.wrapColumn,
terminal: terminal,
write: writeToStdOut,
);
_status?.resume();
}
@protected
void writeToStdOut(String message) => _stdio.stdoutWrite(message);
@protected
void writeToStdErr(String message) => _stdio.stderrWrite(message);
@override
void printTrace(String message) {}
@override
Status startProgress(
String message, {
String? progressId,
int progressIndicatorPadding = kDefaultStatusPadding,
}) {
if (_status != null) {
// Ignore nested progresses; return a no-op status object.
return SilentStatus(
stopwatch: _stopwatchFactory.createStopwatch(),
)..start();
}
if (supportsColor) {
_status = SpinnerStatus(
message: message,
padding: progressIndicatorPadding,
onFinish: _clearStatus,
stdio: _stdio,
stopwatch: _stopwatchFactory.createStopwatch(),
terminal: terminal,
)..start();
} else {
_status = SummaryStatus(
message: message,
padding: progressIndicatorPadding,
onFinish: _clearStatus,
stdio: _stdio,
stopwatch: _stopwatchFactory.createStopwatch(),
)..start();
}
return _status!;
}
@override
Status startSpinner({
VoidCallback? onFinish,
Duration? timeout,
SlowWarningCallback? slowWarningCallback,
}) {
if (_status != null || !supportsColor) {
return SilentStatus(
onFinish: onFinish,
stopwatch: _stopwatchFactory.createStopwatch(),
)..start();
}
_status = AnonymousSpinnerStatus(
onFinish: () {
if (onFinish != null) {
onFinish();
}
_clearStatus();
},
stdio: _stdio,
stopwatch: _stopwatchFactory.createStopwatch(),
terminal: terminal,
timeout: timeout,
slowWarningCallback: slowWarningCallback,
)..start();
return _status!;
}
void _clearStatus() {
_status = null;
}
@override
void clear() {
_status?.pause();
writeToStdOut('${terminal.clearScreen()}\n');
_status?.resume();
}
}
/// A [StdoutLogger] which replaces Unicode characters that cannot be printed to
/// the Windows console with alternative symbols.
///
/// By default, Windows uses either "Consolas" or "Lucida Console" as fonts to
/// render text in the console. Both fonts only have a limited character set.
/// Unicode characters, that are not available in either of the two default
/// fonts, should be replaced by this class with printable symbols. Otherwise,
/// they will show up as the unrepresentable character symbol '�'.
class WindowsStdoutLogger extends StdoutLogger {
WindowsStdoutLogger({
required super.terminal,
required super.stdio,
required super.outputPreferences,
super.stopwatchFactory,
});
@override
void writeToStdOut(String message) {
final String windowsMessage = terminal.supportsEmoji
? message
: message
.replaceAll('🔥', '')
.replaceAll('🖼️', '')
.replaceAll('✗', 'X')
.replaceAll('✓', '√')
.replaceAll('🔨', '')
.replaceAll('💪', '')
.replaceAll('⚠️', '!')
.replaceAll('✏️', '');
_stdio.stdoutWrite(windowsMessage);
}
}
typedef _Writter = void Function(String message);
/// Wraps the message in a box, and writes the bytes by calling [write].
///
/// Example output:
///
/// ┌─ [title] ─┐
/// │ [message] │
/// └───────────┘
///
/// When [title] is provided, the box will have a title above it.
///
/// The box width never exceeds [wrapColumn].
///
/// If [wrapColumn] is not provided, the default value is 100.
void _generateBox({
required String message,
required int wrapColumn,
required _Writter write,
required Terminal terminal,
String? title,
}) {
const int kPaddingLeftRight = 1;
const int kEdges = 2;
final int maxTextWidthPerLine = wrapColumn - kEdges - kPaddingLeftRight * 2;
final List<String> lines =
wrapText(message, shouldWrap: true, columnWidth: maxTextWidthPerLine)
.split('\n');
final List<int> lineWidth =
lines.map((String line) => _getColumnSize(line)).toList();
final int maxColumnSize =
lineWidth.reduce((int currLen, int maxLen) => max(currLen, maxLen));
final int textWidth = min(maxColumnSize, maxTextWidthPerLine);
final int textWithPaddingWidth = textWidth + kPaddingLeftRight * 2;
write('\n');
// Write `┌─ [title] ─┐`.
write('┌');
write('─');
if (title == null) {
write('─' * (textWithPaddingWidth - 1));
} else {
write(' ${terminal.bolden(title)} ');
write('─' * (textWithPaddingWidth - title.length - 3));
}
write('┐');
write('\n');
// Write `│ [message] │`.
for (int lineIdx = 0; lineIdx < lines.length; lineIdx++) {
write('│');
write(' ' * kPaddingLeftRight);
write(lines[lineIdx]);
final int remainingSpacesToEnd = textWidth - lineWidth[lineIdx];
write(' ' * (remainingSpacesToEnd + kPaddingLeftRight));
write('│');
write('\n');
}
// Write `└───────────┘`.
write('└');
write('─' * textWithPaddingWidth);
write('┘');
write('\n');
}
final RegExp _ansiEscapePattern =
RegExp('\x1B\\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]');
int _getColumnSize(String line) {
// Remove ANSI escape characters from the string.
return line.replaceAll(_ansiEscapePattern, '').length;
}
class BufferLogger extends Logger {
BufferLogger({
required this.terminal,
required OutputPreferences outputPreferences,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
bool verbose = false,
}) : _outputPreferences = outputPreferences,
_stopwatchFactory = stopwatchFactory,
_verbose = verbose;
/// Create a [BufferLogger] with test preferences.
BufferLogger.test({
Terminal? terminal,
OutputPreferences? outputPreferences,
bool verbose = false,
}) : terminal = terminal ?? Terminal.test(),
_outputPreferences = outputPreferences ?? OutputPreferences.test(),
_stopwatchFactory = const StopwatchFactory(),
_verbose = verbose;
final OutputPreferences _outputPreferences;
@override
final Terminal terminal;
final StopwatchFactory _stopwatchFactory;
final bool _verbose;
@override
bool get isVerbose => _verbose;
@override
bool get supportsColor => terminal.supportsColor;
final StringBuffer _error = StringBuffer();
final StringBuffer _warning = StringBuffer();
final StringBuffer _status = StringBuffer();
final StringBuffer _trace = StringBuffer();
final StringBuffer _events = StringBuffer();
String get errorText => _error.toString();
String get warningText => _warning.toString();
String get statusText => _status.toString();
String get traceText => _trace.toString();
String get eventText => _events.toString();
@override
bool get hasTerminal => false;
@override
void printError(
String message, {
StackTrace? stackTrace,
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
hadErrorOutput = true;
_error.writeln(terminal.color(
wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
),
color ?? TerminalColor.red,
));
}
@override
void printWarning(
String message, {
bool? emphasis,
TerminalColor? color,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
hadWarningOutput = true;
_warning.writeln(terminal.color(
wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
),
color ?? TerminalColor.cyan,
));
}
@override
void printStatus(
String message, {
bool? emphasis,
TerminalColor? color,
bool? newline,
int? indent,
int? hangingIndent,
bool? wrap,
}) {
if (newline ?? true) {
_status.writeln(wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
));
} else {
_status.write(wrapText(
message,
indent: indent,
hangingIndent: hangingIndent,
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
));
}
}
@override
void printBox(
String message, {
String? title,
}) {
_generateBox(
title: title,
message: message,
wrapColumn: _outputPreferences.wrapColumn,
terminal: terminal,
write: _status.write,
);
}
@override
void printTrace(String message) => _trace.writeln(message);
@override
Status startProgress(
String message, {
String? progressId,
int progressIndicatorPadding = kDefaultStatusPadding,
}) {
printStatus(message);
return SilentStatus(
stopwatch: _stopwatchFactory.createStopwatch(),
)..start();
}
@override
Status startSpinner({
VoidCallback? onFinish,
Duration? timeout,
SlowWarningCallback? slowWarningCallback,
}) {
return SilentStatus(
stopwatch: _stopwatchFactory.createStopwatch(),
onFinish: onFinish,
)..start();
}
@override
void clear() {
_error.clear();
_status.clear();
_trace.clear();
_events.clear();
}
}
typedef SlowWarningCallback = String Function();
/// A [Status] class begins when start is called, and may produce progress
/// information asynchronously.
///
/// The [SilentStatus] class never has any output.
///
/// The [SpinnerStatus] subclass shows a message with a spinner, and replaces it
/// with timing information when stopped. When canceled, the information isn't
/// shown. In either case, a newline is printed.
///
/// The [AnonymousSpinnerStatus] subclass just shows a spinner.
///
/// The [SummaryStatus] subclass shows only a static message (without an
/// indicator), then updates it when the operation ends.
///
/// Generally, consider `logger.startProgress` instead of directly creating
/// a [Status] or one of its subclasses.
abstract class Status {
Status({
this.onFinish,
required Stopwatch stopwatch,
this.timeout,
}) : _stopwatch = stopwatch;
final VoidCallback? onFinish;
final Duration? timeout;
@protected
final Stopwatch _stopwatch;
@protected
String get elapsedTime {
if (_stopwatch.elapsed.inSeconds > 2) {
return _getElapsedAsSeconds(_stopwatch.elapsed);
}
return _getElapsedAsMilliseconds(_stopwatch.elapsed);
}
String _getElapsedAsSeconds(Duration duration) {
final double seconds =
duration.inMilliseconds / Duration.millisecondsPerSecond;
return '${kSecondsFormat.format(seconds)}s';
}
String _getElapsedAsMilliseconds(Duration duration) {
return '${kMillisecondsFormat.format(duration.inMilliseconds)}ms';
}
@visibleForTesting
bool get seemsSlow => timeout != null && _stopwatch.elapsed > timeout!;
/// Call to start spinning.
void start() {
assert(!_stopwatch.isRunning);
_stopwatch.start();
}
/// Call to stop spinning after success.
void stop() {
finish();
}
/// Call to cancel the spinner after failure or cancellation.
void cancel() {
finish();
}
/// Call to clear the current line but not end the progress.
void pause() {}
/// Call to resume after a pause.
void resume() {}
@protected
void finish() {
assert(_stopwatch.isRunning);
_stopwatch.stop();
onFinish?.call();
}
}
/// A [Status] that shows nothing.
class SilentStatus extends Status {
SilentStatus({
required super.stopwatch,
super.onFinish,
});
@override
void finish() {
onFinish?.call();
}
}
/// Constructor writes [message] to [stdout]. On [cancel] or [stop], will call
/// [onFinish]. On [stop], will additionally print out summary information.
class SummaryStatus extends Status {
SummaryStatus({
this.message = '',
required super.stopwatch,
this.padding = kDefaultStatusPadding,
super.onFinish,
required Stdio stdio,
}) : _stdio = stdio;
final String message;
final int padding;
final Stdio _stdio;
bool _messageShowingOnCurrentLine = false;
@override
void start() {
_printMessage();
super.start();
}
void _writeToStdOut(String message) => _stdio.stdoutWrite(message);
void _printMessage() {
assert(!_messageShowingOnCurrentLine);
_writeToStdOut('${message.padRight(padding)} ');
_messageShowingOnCurrentLine = true;
}
@override
void stop() {
if (!_messageShowingOnCurrentLine) {
_printMessage();
}
super.stop();
assert(_messageShowingOnCurrentLine);
_writeToStdOut(elapsedTime.padLeft(_kTimePadding));
_writeToStdOut('\n');
}
@override
void cancel() {
super.cancel();
if (_messageShowingOnCurrentLine) {
_writeToStdOut('\n');
}
}
@override
void pause() {
super.pause();
if (_messageShowingOnCurrentLine) {
_writeToStdOut('\n');
_messageShowingOnCurrentLine = false;
}
}
}
const int _kTimePadding = 8; // should fit "99,999ms"
/// A kind of animated [Status] that has no message.
///
/// Call [pause] before outputting any text while this is running.
class AnonymousSpinnerStatus extends Status {
AnonymousSpinnerStatus({
super.onFinish,
required super.stopwatch,
required Stdio stdio,
required Terminal terminal,
this.slowWarningCallback,
super.timeout,
}) : _stdio = stdio,
_terminal = terminal,
_animation = _selectAnimation(terminal);
final Stdio _stdio;
final Terminal _terminal;
String _slowWarning = '';
final SlowWarningCallback? slowWarningCallback;
static const String _backspaceChar = '\b';
static const String _clearChar = ' ';
static const List<String> _emojiAnimations = <String>[
'⣾⣽⣻⢿⡿⣟⣯⣷', // counter-clockwise
'⣾⣷⣯⣟⡿⢿⣻⣽', // clockwise
'⣾⣷⣯⣟⡿⢿⣻⣽⣷⣾⣽⣻⢿⡿⣟⣯⣷', // bouncing clockwise and counter-clockwise
'⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽', // snaking
'⣾⣽⣻⢿⣿⣷⣯⣟⡿⣿', // alternating rain
'⣀⣠⣤⣦⣶⣾⣿⡿⠿⠻⠛⠋⠉⠙⠛⠟⠿⢿⣿⣷⣶⣴⣤⣄', // crawl up and down, large
'⠙⠚⠖⠦⢤⣠⣄⡤⠴⠲⠓⠋', // crawl up and down, small
'⣀⡠⠤⠔⠒⠊⠉⠑⠒⠢⠤⢄', // crawl up and down, tiny
'⡀⣄⣦⢷⠻⠙⠈⠀⠁⠋⠟⡾⣴⣠⢀⠀', // slide up and down
'⠙⠸⢰⣠⣄⡆⠇⠋', // clockwise line
'⠁⠈⠐⠠⢀⡀⠄⠂', // clockwise dot
'⢇⢣⢱⡸⡜⡎', // vertical wobble up
'⡇⡎⡜⡸⢸⢱⢣⢇', // vertical wobble down
'⡀⣀⣐⣒⣖⣶⣾⣿⢿⠿⠯⠭⠩⠉⠁⠀', // swirl
'⠁⠐⠄⢀⢈⢂⢠⣀⣁⣐⣄⣌⣆⣤⣥⣴⣼⣶⣷⣿⣾⣶⣦⣤⣠⣀⡀⠀⠀', // snowing and melting
'⠁⠋⠞⡴⣠⢀⠀⠈⠙⠻⢷⣦⣄⡀⠀⠉⠛⠲⢤⢀⠀', // falling water
'⠄⡢⢑⠈⠀⢀⣠⣤⡶⠞⠋⠁⠀⠈⠙⠳⣆⡀⠀⠆⡷⣹⢈⠀⠐⠪⢅⡀⠀', // fireworks
'⠐⢐⢒⣒⣲⣶⣷⣿⡿⡷⡧⠧⠇⠃⠁⠀⡀⡠⡡⡱⣱⣳⣷⣿⢿⢯⢧⠧⠣⠃⠂⠀⠈⠨⠸⠺⡺⡾⡿⣿⡿⡷⡗⡇⡅⡄⠄⠀⡀⡐⣐⣒⣓⣳⣻⣿⣾⣼⡼⡸⡘⡈⠈⠀', // fade
'⢸⡯⠭⠅⢸⣇⣀⡀⢸⣇⣸⡇⠈⢹⡏⠁⠈⢹⡏⠁⢸⣯⣭⡅⢸⡯⢕⡂⠀⠀', // text crawl
];
static const List<String> _asciiAnimations = <String>[
r'-\|/',
];
static List<String> _selectAnimation(Terminal terminal) {
final List<String> animations =
terminal.supportsEmoji ? _emojiAnimations : _asciiAnimations;
return animations[terminal.preferredStyle % animations.length]
.runes
.map<String>((int scalar) => String.fromCharCode(scalar))
.toList();
}
final List<String> _animation;
Timer? timer;
int ticks = 0;
int _lastAnimationFrameLength = 0;
bool timedOut = false;
String get _currentAnimationFrame => _animation[ticks % _animation.length];
int get _currentLineLength => _lastAnimationFrameLength + _slowWarning.length;
void _writeToStdOut(String message) => _stdio.stdoutWrite(message);
void _clear(int length) {
_writeToStdOut('${_backspaceChar * length}'
'${_clearChar * length}'
'${_backspaceChar * length}');
}
@override
void start() {
super.start();
assert(timer == null);
_startSpinner();
}
void _startSpinner() {
timer = Timer.periodic(const Duration(milliseconds: 100), _callback);
_callback(timer!);
}
void _callback(Timer timer) {
assert(this.timer == timer);
assert(timer.isActive);
_writeToStdOut(_backspaceChar * _lastAnimationFrameLength);
ticks += 1;
if (seemsSlow) {
if (!timedOut) {
timedOut = true;
_clear(_currentLineLength);
}
if (_slowWarning == '' && slowWarningCallback != null) {
_slowWarning = slowWarningCallback!();
_writeToStdOut(_slowWarning);
}
}
final String newFrame = _currentAnimationFrame;
_lastAnimationFrameLength = newFrame.runes.length;
_writeToStdOut(newFrame);
}
@override
void pause() {
assert(timer != null);
assert(timer!.isActive);
if (_terminal.supportsColor) {
_writeToStdOut('\r\x1B[K'); // go to start of line and clear line
} else {
_clear(_currentLineLength);
}
_lastAnimationFrameLength = 0;
timer?.cancel();
}
@override
void resume() {
assert(timer != null);
assert(!timer!.isActive);
_startSpinner();
}
@override
void finish() {
assert(timer != null);
assert(timer!.isActive);
timer?.cancel();
timer = null;
_clear(_lastAnimationFrameLength);
_lastAnimationFrameLength = 0;
super.finish();
}
}
/// An animated version of [Status].
///
/// The constructor writes [message] to [stdout] with padding, then starts an
/// indeterminate progress indicator animation.
///
/// On [cancel] or [stop], will call [onFinish]. On [stop], will
/// additionally print out summary information.
///
/// Call [pause] before outputting any text while this is running.
class SpinnerStatus extends AnonymousSpinnerStatus {
SpinnerStatus({
required this.message,
this.padding = kDefaultStatusPadding,
super.onFinish,
required super.stopwatch,
required super.stdio,
required super.terminal,
});
final String message;
final int padding;
static final String _margin =
AnonymousSpinnerStatus._clearChar * (5 + _kTimePadding - 1);
int _totalMessageLength = 0;
@override
int get _currentLineLength => _totalMessageLength + super._currentLineLength;
@override
void start() {
_printStatus();
super.start();
}
void _printStatus() {
final String line = '${message.padRight(padding)}$_margin';
_totalMessageLength = line.length;
_writeToStdOut(line);
}
@override
void pause() {
super.pause();
_totalMessageLength = 0;
}
@override
void resume() {
_printStatus();
super.resume();
}
@override
void stop() {
super.stop(); // calls finish, which clears the spinner
assert(_totalMessageLength > _kTimePadding);
_writeToStdOut(AnonymousSpinnerStatus._backspaceChar * (_kTimePadding - 1));
_writeToStdOut(elapsedTime.padLeft(_kTimePadding));
_writeToStdOut('\n');
}
@override
void cancel() {
super.cancel(); // calls finish, which clears the spinner
assert(_totalMessageLength > 0);
_writeToStdOut('\n');
}
}
/// Wraps a block of text into lines no longer than [columnWidth].
///
/// Tries to split at whitespace, but if that's not good enough to keep it under
/// the limit, then it splits in the middle of a word. If [columnWidth] (minus
/// any indent) is smaller than [kMinColumnWidth], the text is wrapped at that
/// [kMinColumnWidth] instead.
///
/// Preserves indentation (leading whitespace) for each line (delimited by '\n')
/// in the input, and will indent wrapped lines that same amount, adding
/// [indent] spaces in addition to any existing indent.
///
/// If [hangingIndent] is supplied, then that many additional spaces will be
/// added to each line, except for the first line. The [hangingIndent] is added
/// to the specified [indent], if any. This is useful for wrapping
/// text with a heading prefix (e.g. "Usage: "):
///
/// ```dart
/// String prefix = "Usage: ";
/// print(prefix + wrapText(invocation, indent: 2, hangingIndent: prefix.length, columnWidth: 40));
/// ```
///
/// yields:
/// ```
/// Usage: app main_command <subcommand>
/// [arguments]
/// ```
///
/// If [outputPreferences.wrapText] is false, then the text will be returned
/// unchanged. If [shouldWrap] is specified, then it overrides the
/// [outputPreferences.wrapText] setting.
///
/// If the amount of indentation (from the text, [indent], and [hangingIndent])
/// is such that less than [kMinColumnWidth] characters can fit in the
/// [columnWidth], then the indent is truncated to allow the text to fit.
String wrapText(
String text, {
required int columnWidth,
required bool shouldWrap,
int? hangingIndent,
int? indent,
}) {
assert(columnWidth >= 0);
if (text.isEmpty) {
return '';
}
indent ??= 0;
hangingIndent ??= 0;
final List<String> splitText = text.split('\n');
final List<String> result = <String>[];
for (final String line in splitText) {
String trimmedText = line.trimLeft();
final String leadingWhitespace =
line.substring(0, line.length - trimmedText.length);
List<String> notIndented;
if (hangingIndent != 0) {
// When we have a hanging indent, we want to wrap the first line at one
// width, and the rest at another (offset by hangingIndent), so we wrap
// them twice and recombine.
final List<String> firstLineWrap = _wrapTextAsLines(
trimmedText,
columnWidth: columnWidth - leadingWhitespace.length - indent,
shouldWrap: shouldWrap,
);
notIndented = <String>[firstLineWrap.removeAt(0)];
trimmedText = trimmedText.substring(notIndented[0].length).trimLeft();
if (trimmedText.isNotEmpty) {
notIndented.addAll(_wrapTextAsLines(
trimmedText,
columnWidth:
columnWidth - leadingWhitespace.length - indent - hangingIndent,
shouldWrap: shouldWrap,
));
}
} else {
notIndented = _wrapTextAsLines(
trimmedText,
columnWidth: columnWidth - leadingWhitespace.length - indent,
shouldWrap: shouldWrap,
);
}
String? hangingIndentString;
final String indentString = ' ' * indent;
result.addAll(notIndented.map<String>(
(String line) {
// Don't return any lines with just whitespace on them.
if (line.isEmpty) {
return '';
}
String truncatedIndent =
'$indentString${hangingIndentString ?? ''}$leadingWhitespace';
if (truncatedIndent.length > columnWidth - kMinColumnWidth) {
truncatedIndent = truncatedIndent.substring(
0, math.max(columnWidth - kMinColumnWidth, 0));
}
final String result = '$truncatedIndent$line';
hangingIndentString ??= ' ' * hangingIndent!;
return result;
},
));
}
return result.join('\n');
}
/// Wraps a block of text into lines no longer than [columnWidth], starting at the
/// [start] column, and returning the result as a list of strings.
///
/// Tries to split at whitespace, but if that's not good enough to keep it
/// under the limit, then splits in the middle of a word. Preserves embedded
/// newlines, but not indentation (it trims whitespace from each line).
///
/// If [columnWidth] is not specified, then the column width will be the width of the
/// terminal window by default. If the stdout is not a terminal window, then the
/// default will be [outputPreferences.wrapColumn].
///
/// The [columnWidth] is clamped to [kMinColumnWidth] at minimum (so passing negative
/// widths is fine, for instance).
///
/// If [outputPreferences.wrapText] is false, then the text will be returned
/// simply split at the newlines, but not wrapped. If [shouldWrap] is specified,
/// then it overrides the [outputPreferences.wrapText] setting.
List<String> _wrapTextAsLines(
String text, {
int start = 0,
required int columnWidth,
required bool shouldWrap,
}) {
if (text.isEmpty) {
return <String>[''];
}
assert(start >= 0);
// Splits a string so that the resulting list has the same number of elements
// as there are visible characters in the string, but elements may include one
// or more adjacent ANSI sequences. Joining the list elements again will
// reconstitute the original string. This is useful for manipulating "visible"
// characters in the presence of ANSI control codes.
List<_AnsiRun> splitWithCodes(String input) {
final RegExp characterOrCode =
RegExp('(\u001b\\[[0-9;]*m|.)', multiLine: true);
List<_AnsiRun> result = <_AnsiRun>[];
final StringBuffer current = StringBuffer();
for (final Match match in characterOrCode.allMatches(input)) {
current.write(match[0]);
if (match[0]!.length < 4) {
// This is a regular character, write it out.
result.add(_AnsiRun(current.toString(), match[0]!));
current.clear();
}
}
// If there's something accumulated, then it must be an ANSI sequence, so
// add it to the end of the last entry so that we don't lose it.
if (current.isNotEmpty) {
if (result.isNotEmpty) {
result.last.original += current.toString();
} else {
// If there is nothing in the string besides control codes, then just
// return them as the only entry.
result = <_AnsiRun>[_AnsiRun(current.toString(), '')];
}
}
return result;
}
String joinRun(List<_AnsiRun> list, int start, [int? end]) {
return list
.sublist(start, end)
.map<String>((_AnsiRun run) => run.original)
.join()
.trim();
}
final List<String> result = <String>[];
final int effectiveLength = math.max(columnWidth - start, kMinColumnWidth);
for (final String line in text.split('\n')) {
// If the line is short enough, even with ANSI codes, then we can just add
// add it and move on.
if (line.length <= effectiveLength || !shouldWrap) {
result.add(line);
continue;
}
final List<_AnsiRun> splitLine = splitWithCodes(line);
if (splitLine.length <= effectiveLength) {
result.add(line);
continue;
}
int currentLineStart = 0;
int? lastWhitespace;
// Find the start of the current line.
for (int index = 0; index < splitLine.length; ++index) {
if (splitLine[index].character.isNotEmpty &&
_isWhitespace(splitLine[index])) {
lastWhitespace = index;
}
if (index - currentLineStart >= effectiveLength) {
// Back up to the last whitespace, unless there wasn't any, in which
// case we just split where we are.
if (lastWhitespace != null) {
index = lastWhitespace;
}
result.add(joinRun(splitLine, currentLineStart, index));
// Skip any intervening whitespace.
while (index < splitLine.length && _isWhitespace(splitLine[index])) {
index++;
}
currentLineStart = index;
lastWhitespace = null;
}
}
result.add(joinRun(splitLine, currentLineStart));
}
return result;
}
// Used to represent a run of ANSI control sequences next to a visible
// character.
class _AnsiRun {
_AnsiRun(this.original, this.character);
String original;
String character;
}
/// Returns true if the code unit at [index] in [text] is a whitespace
/// character.
///
/// Based on: https://en.wikipedia.org/wiki/Whitespace_character#Unicode
bool _isWhitespace(_AnsiRun run) {
final int rune = run.character.isNotEmpty ? run.character.codeUnitAt(0) : 0x0;
return rune >= 0x0009 && rune <= 0x000D ||
rune == 0x0020 ||
rune == 0x0085 ||
rune == 0x1680 ||
rune == 0x180E ||
rune >= 0x2000 && rune <= 0x200A ||
rune == 0x2028 ||
rune == 0x2029 ||
rune == 0x202F ||
rune == 0x205F ||
rune == 0x3000 ||
rune == 0xFEFF;
}
/// An abstraction for instantiation of the correct logger type.
///
/// Our logger class hierarchy and runtime requirements are overly complicated.
class LoggerFactory {
LoggerFactory({
required Terminal terminal,
required Stdio stdio,
required OutputPreferences outputPreferences,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
}) : _terminal = terminal,
_stdio = stdio,
_stopwatchFactory = stopwatchFactory,
_outputPreferences = outputPreferences;
final Terminal _terminal;
final Stdio _stdio;
final StopwatchFactory _stopwatchFactory;
final OutputPreferences _outputPreferences;
/// Create the appropriate logger for the current platform and configuration.
Logger createLogger({
required bool windows,
}) {
Logger logger;
if (windows) {
logger = WindowsStdoutLogger(
terminal: _terminal,
stdio: _stdio,
outputPreferences: _outputPreferences,
stopwatchFactory: _stopwatchFactory,
);
} else {
logger = StdoutLogger(
terminal: _terminal,
stdio: _stdio,
outputPreferences: _outputPreferences,
stopwatchFactory: _stopwatchFactory);
}
return logger;
}
}
| packages/packages/flutter_migrate/lib/src/base/logger.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/base/logger.dart",
"repo_id": "packages",
"token_count": 15012
} | 1,030 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/project.dart';
import 'base/terminal.dart';
import 'utils.dart';
/// Checks if the project uses pubspec dependency locking and prompts if
/// the pub upgrade should be run.
Future<void> updatePubspecDependencies(FlutterProject flutterProject,
MigrateUtils migrateUtils, Logger logger, Terminal terminal,
{bool force = false}) async {
final File pubspecFile = flutterProject.directory.childFile('pubspec.yaml');
if (!pubspecFile.existsSync()) {
return;
}
if (!pubspecFile
.readAsStringSync()
.contains('# THIS LINE IS AUTOGENERATED')) {
return;
}
logger.printStatus('\nDart dependency locking detected in pubspec.yaml.');
terminal.usesTerminalUi = true;
String selection = 'y';
if (!force) {
selection = await terminal.promptForCharInput(
<String>['y', 'n'],
logger: logger,
prompt:
'Do you want the tool to run `flutter pub upgrade --major-versions`? (y)es, (n)o',
defaultChoiceIndex: 1,
);
}
if (selection == 'y') {
// Runs `flutter pub upgrade --major-versions`
await migrateUtils.flutterPubUpgrade(flutterProject.directory.path);
}
}
/// Checks if gradle dependency locking is used and prompts the developer to
/// remove and back up the gradle dependency lockfile.
Future<void> updateGradleDependencyLocking(
FlutterProject flutterProject,
MigrateUtils migrateUtils,
Logger logger,
Terminal terminal,
bool verbose,
FileSystem fileSystem, {
bool force = false,
}) async {
final Directory androidDir =
flutterProject.directory.childDirectory('android');
if (!androidDir.existsSync()) {
return;
}
final List<FileSystemEntity> androidFiles = androidDir.listSync();
final List<File> lockfiles = <File>[];
final List<String> backedUpFilePaths = <String>[];
for (final FileSystemEntity entity in androidFiles) {
if (entity is! File) {
continue;
}
final File file = entity.absolute;
// Don't re-handle backed up lockfiles.
if (file.path.contains('_backup_')) {
continue;
}
try {
// lockfiles generated by gradle start with this prefix.
if (file.readAsStringSync().startsWith(
'# This is a Gradle generated file for dependency locking.\n# '
'Manual edits can break the build and are not advised.\n# This '
'file is expected to be part of source control.')) {
lockfiles.add(file);
}
} on FileSystemException {
if (verbose) {
logger.printStatus('Unable to check ${file.path}');
}
}
}
if (lockfiles.isNotEmpty) {
logger.printStatus('\nGradle dependency locking detected.');
logger
.printStatus('Flutter can backup the lockfiles and regenerate updated '
'lockfiles.');
terminal.usesTerminalUi = true;
String selection = 'y';
if (!force) {
selection = await terminal.promptForCharInput(
<String>['y', 'n'],
logger: logger,
prompt:
'Do you want the tool to update locked dependencies? (y)es, (n)o',
defaultChoiceIndex: 1,
);
}
if (selection == 'y') {
for (final File file in lockfiles) {
int counter = 0;
while (true) {
final String newPath = '${file.absolute.path}_backup_$counter';
if (!fileSystem.file(newPath).existsSync()) {
file.renameSync(newPath);
backedUpFilePaths.add(newPath);
break;
} else {
counter++;
}
}
}
// Runs `./gradlew tasks`in the project's android directory.
await migrateUtils.gradlewTasks(
flutterProject.directory.childDirectory('android').path);
logger.printStatus('Old lockfiles renamed to:');
for (final String path in backedUpFilePaths) {
logger.printStatus(path, color: TerminalColor.grey, indent: 2);
}
}
}
}
| packages/packages/flutter_migrate/lib/src/update_locks.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/update_locks.dart",
"repo_id": "packages",
"token_count": 1555
} | 1,031 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_migrate/src/base/common.dart';
import 'package:flutter_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/io.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/base/signals.dart';
import 'package:flutter_migrate/src/base/terminal.dart';
import 'package:process/process.dart';
import 'src/common.dart';
import 'src/context.dart';
import 'test_data/migrate_project.dart';
// This file contains E2E test that execute the core migrate commands
// and simulates manual conflict resolution and other manipulations of
// the project files.
void main() {
late Directory tempDir;
late BufferLogger logger;
late ProcessManager processManager;
late FileSystem fileSystem;
setUp(() async {
logger = BufferLogger.test();
processManager = const LocalProcessManager();
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_run_test');
});
tearDown(() async {
tryToDelete(tempDir);
});
Future<bool> hasFlutterEnvironment() async {
final String flutterRoot = getFlutterRoot();
final String flutterExecutable = fileSystem.path
.join(flutterRoot, 'bin', 'flutter${isWindows ? '.bat' : ''}');
final ProcessResult result = await Process.run(
flutterExecutable, <String>['analyze', '--suggestions', '--machine']);
if (result.exitCode != 0) {
return false;
}
return true;
}
// Migrates a clean untouched app generated with flutter create
testUsingContext('vanilla migrate process succeeds', () async {
// This tool does not support old versions of flutter that dont include
// `flutter analyze --suggestions --machine` command
if (!await hasFlutterEnvironment()) {
return;
}
// Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
await MigrateProject.installProject('version:1.22.6_stable', tempDir);
ProcessResult result = await runMigrateCommand(<String>[
'start',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.stdout.toString(), contains('Staging directory created at'));
const String linesToMatch = '''
Added files:
- android/app/src/main/res/values-night/styles.xml
- android/app/src/main/res/drawable-v21/launch_background.xml
- analysis_options.yaml
Modified files:
- .metadata
- ios/Runner/Info.plist
- ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
- ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
- ios/Flutter/AppFrameworkInfo.plist
- ios/.gitignore
- pubspec.yaml
- .gitignore
- android/app/build.gradle
- android/app/src/profile/AndroidManifest.xml
- android/app/src/main/res/values/styles.xml
- android/app/src/main/AndroidManifest.xml
- android/app/src/debug/AndroidManifest.xml
- android/gradle/wrapper/gradle-wrapper.properties
- android/.gitignore
- android/build.gradle''';
for (final String line in linesToMatch.split('\n')) {
expect(result.stdout.toString(), contains(line));
}
result = await runMigrateCommand(<String>[
'apply',
'--verbose',
], workingDirectory: tempDir.path);
logger.printStatus('${result.exitCode}', color: TerminalColor.blue);
logger.printStatus(result.stdout as String, color: TerminalColor.green);
logger.printStatus(result.stderr as String, color: TerminalColor.red);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Migration complete'));
expect(tempDir.childFile('.metadata').readAsStringSync(),
contains('migration:\n platforms:\n - platform: root\n'));
expect(
tempDir
.childFile('android/app/src/main/res/values-night/styles.xml')
.existsSync(),
true);
expect(tempDir.childFile('analysis_options.yaml').existsSync(), true);
},
timeout: const Timeout(Duration(seconds: 500)),
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: true);
// Migrates a clean untouched app generated with flutter create
testUsingContext('vanilla migrate builds', () async {
// This tool does not support old versions of flutter that dont include
// `flutter analyze --suggestions --machine` command
if (!await hasFlutterEnvironment()) {
return;
}
// Flutter Stable 2.0.0 hash: 60bd88df915880d23877bfc1602e8ddcf4c4dd2a
await MigrateProject.installProject('version:2.0.0_stable', tempDir,
main: '''
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Container(),
);
}
}
''');
ProcessResult result = await runMigrateCommand(<String>[
'start',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.stdout.toString(), contains('Staging directory created at'));
result = await runMigrateCommand(<String>[
'apply',
'--verbose',
], workingDirectory: tempDir.path);
logger.printStatus('${result.exitCode}', color: TerminalColor.blue);
logger.printStatus(result.stdout as String, color: TerminalColor.green);
logger.printStatus(result.stderr as String, color: TerminalColor.red);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Migration complete'));
result = await processManager.run(<String>[
'flutter',
'build',
'apk',
'--debug',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('app-debug.apk'));
// Skipped due to being flaky, the build completes successfully, but sometimes
// Gradle crashes due to resources on the bot. We should fine tune this to
// make it stable.
},
timeout: const Timeout(Duration(seconds: 900)),
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: true);
testUsingContext('migrate abandon', () async {
// Abandon in an empty dir fails.
ProcessResult result = await runMigrateCommand(<String>[
'abandon',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stderr.toString(),
contains('Error: No pubspec.yaml file found'));
expect(
result.stderr.toString(),
contains(
'This command should be run from the root of your Flutter project'));
final File manifestFile =
tempDir.childFile('migrate_staging_dir/.migrate_manifest');
expect(manifestFile.existsSync(), false);
// Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
await MigrateProject.installProject('version:1.22.6_stable', tempDir);
// Initialized repo fails.
result = await runMigrateCommand(<String>[
'abandon',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('No migration in progress'));
// Create migration.
manifestFile.createSync(recursive: true);
// Directory with manifest_staging_dir succeeds.
result = await runMigrateCommand(<String>[
'abandon',
'--verbose',
'--force',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Abandon complete'));
},
timeout: const Timeout(Duration(seconds: 300)),
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: true);
// Migrates a user-modified app
testUsingContext('modified migrate process succeeds', () async {
// This tool does not support old versions of flutter that dont include
// `flutter analyze --suggestions --machine` command
if (!await hasFlutterEnvironment()) {
return;
}
// Flutter Stable 1.22.6 hash: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
await MigrateProject.installProject('version:1.22.6_stable', tempDir,
vanilla: false);
ProcessResult result = await runMigrateCommand(<String>[
'apply',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('No migration'));
result = await runMigrateCommand(<String>[
'status',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('No migration'));
result = await runMigrateCommand(<String>[
'start',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Staging directory created at'));
const String linesToMatch = '''
Modified files:
- .metadata
- ios/Runner/Info.plist
- ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
- ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
- ios/Flutter/AppFrameworkInfo.plist
- ios/.gitignore
- .gitignore
- android/app/build.gradle
- android/app/src/profile/AndroidManifest.xml
- android/app/src/main/res/values/styles.xml
- android/app/src/main/AndroidManifest.xml
- android/app/src/debug/AndroidManifest.xml
- android/gradle/wrapper/gradle-wrapper.properties
- android/.gitignore
- android/build.gradle
Merge conflicted files:
- pubspec.yaml''';
for (final String line in linesToMatch.split('\n')) {
expect(result.stdout.toString(), contains(line));
}
// Call apply with conflicts remaining. Should fail.
result = await runMigrateCommand(<String>[
'apply',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(
result.stdout.toString(),
contains(
'Conflicting files found. Resolve these conflicts and try again.'));
expect(result.stdout.toString(), contains('- pubspec.yaml'));
result = await runMigrateCommand(<String>[
'status',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Modified files'));
expect(result.stdout.toString(), contains('Merge conflicted files'));
// Manually resolve conflics. The correct contents for resolution may change over time,
// but it shouldnt matter for this test.
final File metadataFile =
tempDir.childFile('migrate_staging_dir/.metadata');
metadataFile.writeAsStringSync('''
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: e96a72392696df66755ca246ff291dfc6ca6c4ad
channel: unknown
project_type: app
''', flush: true);
final File pubspecYamlFile =
tempDir.childFile('migrate_staging_dir/pubspec.yaml');
pubspecYamlFile.writeAsStringSync('''
name: vanilla_app_1_22_6_stable
description: This is a modified description from the default.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.17.0-79.0.dev <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/a_dot_burr.jpeg
- images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
''', flush: true);
result = await runMigrateCommand(<String>[
'status',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Modified files'));
expect(result.stdout.toString(), contains('diff --git'));
expect(result.stdout.toString(), contains('@@'));
expect(result.stdout.toString(), isNot(contains('Merge conflicted files')));
result = await runMigrateCommand(<String>[
'apply',
'--verbose',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('Migration complete'));
expect(tempDir.childFile('.metadata').readAsStringSync(),
contains('e96a72392696df66755ca246ff291dfc6ca6c4ad'));
expect(tempDir.childFile('pubspec.yaml').readAsStringSync(),
isNot(contains('">=2.6.0 <3.0.0"')));
expect(tempDir.childFile('pubspec.yaml').readAsStringSync(),
contains('">=2.17.0-79.0.dev <3.0.0"'));
expect(
tempDir.childFile('pubspec.yaml').readAsStringSync(),
contains(
'description: This is a modified description from the default.'));
expect(tempDir.childFile('lib/main.dart').readAsStringSync(),
contains('OtherWidget()'));
expect(tempDir.childFile('lib/other.dart').existsSync(), true);
expect(tempDir.childFile('lib/other.dart').readAsStringSync(),
contains('class OtherWidget'));
expect(
tempDir
.childFile('android/app/src/main/res/values-night/styles.xml')
.existsSync(),
true);
expect(tempDir.childFile('analysis_options.yaml').existsSync(), true);
},
timeout: const Timeout(Duration(seconds: 500)),
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: true);
}
| packages/packages/flutter_migrate/test/migrate_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/migrate_test.dart",
"repo_id": "packages",
"token_count": 5948
} | 1,032 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Updates compileSdk version to 34.
## 2.0.17
* Updates annotations lib to 1.7.0.
## 2.0.16
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.0.15
* Fixes Java lints.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 2.0.14
* Fixes compatibility with ActivityPluginBinding.
## 2.0.13
* Fixes compatibility with AGP versions older than 4.2.
## 2.0.12
* Adds `targetCompatibilty` matching `sourceCompatibility` for older toolchains.
## 2.0.11
* Adds a namespace for compatibility with AGP 8.0.
## 2.0.10
* Sets an explicit Java compatibility version.
* Aligns Dart and Flutter SDK constraints.
## 2.0.9
* Updates annotation and espresso dependencies.
* Updates compileSdkVersion to 33.
## 2.0.8
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.0.7
* Bumps gradle from 3.5.0 to 7.2.1.
## 2.0.6
* Adds OS version support information to README.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.5
* Updates compileSdkVersion to 31.
## 2.0.4
* Updated Android lint settings.
* Remove placeholder Dart file.
## 2.0.3
* Remove references to the Android V1 embedding.
## 2.0.2
* Migrate maven repo from jcenter to mavenCentral.
## 2.0.1
* Make sure androidx.lifecycle.DefaultLifecycleObservable doesn't get shrunk away.
## 2.0.0
* Bump Dart SDK for null-safety compatibility.
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
## 1.0.12
* Update Flutter SDK constraint.
## 1.0.11
* Keep handling deprecated Android v1 classes for backward compatibility.
## 1.0.10
* Update android compileSdkVersion to 29.
## 1.0.9
* Let the no-op plugin implement the `FlutterPlugin` interface.
## 1.0.8
* Post-v2 Android embedding cleanup.
## 1.0.7
* Update Gradle version. Fixes https://github.com/flutter/flutter/issues/48724.
* Fix CocoaPods podspec lint warnings.
## 1.0.6
* Make the pedantic dev_dependency explicit.
## 1.0.5
* Add notice in example this plugin only provides Android Lifecycle API.
## 1.0.4
* Require Flutter SDK 1.12.13 or greater.
* Change to avoid reflection.
## 1.0.3
* Remove the deprecated `author:` field from pubspec.yaml
* Require Flutter SDK 1.10.0 or greater.
## 1.0.2
* Adapt to the embedding API changes in https://github.com/flutter/engine/pull/13280 (only supports Activity Lifecycle).
## 1.0.1
* Register the E2E plugin in the example app.
## 1.0.0
* Introduces a `FlutterLifecycleAdapter`, which can be used by other plugins to obtain a `Lifecycle`
reference from a `FlutterPluginBinding`.
| packages/packages/flutter_plugin_android_lifecycle/CHANGELOG.md/0 | {
"file_path": "packages/packages/flutter_plugin_android_lifecycle/CHANGELOG.md",
"repo_id": "packages",
"token_count": 959
} | 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.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
// This scenario demonstrates how to navigate using named locations instead of
// URLs.
//
// Instead of hardcoding the URI locations , you can also use the named
// locations. To use this API, give a unique name to each GoRoute. The name can
// then be used in context.namedLocation to be translate back to the actual URL
// location.
/// Family data class.
class Family {
/// Create a family.
const Family({required this.name, required this.people});
/// The last name of the family.
final String name;
/// The people in the family.
final Map<String, Person> people;
}
/// Person data class.
class Person {
/// Creates a person.
const Person({required this.name, required this.age});
/// The first name of the person.
final String name;
/// The age of the person.
final int age;
}
const Map<String, Family> _families = <String, Family>{
'f1': Family(
name: 'Doe',
people: <String, Person>{
'p1': Person(name: 'Jane', age: 23),
'p2': Person(name: 'John', age: 6),
},
),
'f2': Family(
name: 'Wong',
people: <String, Person>{
'p1': Person(name: 'June', age: 51),
'p2': Person(name: 'Xin', age: 44),
},
),
};
void main() => runApp(App());
/// The main app.
class App extends StatelessWidget {
/// Creates an [App].
App({super.key});
/// The title of the app.
static const String title = 'GoRouter Example: Named Routes';
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
debugShowCheckedModeBanner: false,
);
late final GoRouter _router = GoRouter(
debugLogDiagnostics: true,
routes: <GoRoute>[
GoRoute(
name: 'home',
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family/:fid',
builder: (BuildContext context, GoRouterState state) =>
FamilyScreen(fid: state.pathParameters['fid']!),
routes: <GoRoute>[
GoRoute(
name: 'person',
path: 'person/:pid',
builder: (BuildContext context, GoRouterState state) {
return PersonScreen(
fid: state.pathParameters['fid']!,
pid: state.pathParameters['pid']!);
},
),
],
),
],
),
],
);
}
/// The home screen that shows a list of families.
class HomeScreen extends StatelessWidget {
/// Creates a [HomeScreen].
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(App.title),
),
body: ListView(
children: <Widget>[
for (final MapEntry<String, Family> entry in _families.entries)
ListTile(
title: Text(entry.value.name),
onTap: () => context.go(context.namedLocation('family',
pathParameters: <String, String>{'fid': entry.key})),
)
],
),
);
}
}
/// The screen that shows a list of persons in a family.
class FamilyScreen extends StatelessWidget {
/// Creates a [FamilyScreen].
const FamilyScreen({required this.fid, super.key});
/// The id family to display.
final String fid;
@override
Widget build(BuildContext context) {
final Map<String, Person> people = _families[fid]!.people;
return Scaffold(
appBar: AppBar(title: Text(_families[fid]!.name)),
body: ListView(
children: <Widget>[
for (final MapEntry<String, Person> entry in people.entries)
ListTile(
title: Text(entry.value.name),
onTap: () => context.go(context.namedLocation(
'person',
pathParameters: <String, String>{'fid': fid, 'pid': entry.key},
queryParameters: <String, String>{'qid': 'quid'},
)),
),
],
),
);
}
}
/// The person screen.
class PersonScreen extends StatelessWidget {
/// Creates a [PersonScreen].
const PersonScreen({required this.fid, required this.pid, super.key});
/// The id of family this person belong to.
final String fid;
/// The id of the person to be displayed.
final String pid;
@override
Widget build(BuildContext context) {
final Family family = _families[fid]!;
final Person person = family.people[pid]!;
return Scaffold(
appBar: AppBar(title: Text(person.name)),
body: Text('${person.name} ${family.name} is ${person.age} years old'),
);
}
}
| packages/packages/go_router/example/lib/named_routes.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/named_routes.dart",
"repo_id": "packages",
"token_count": 2029
} | 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/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> _rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'shell');
// This scenario demonstrates how to set up nested navigation using ShellRoute,
// which is a pattern where an additional Navigator is placed in the widget tree
// to be used instead of the root navigator. This allows deep-links to display
// pages along with other UI components such as a BottomNavigationBar.
//
// This example demonstrates how to display a route within a ShellRoute and also
// push a screen using a different navigator (such as the root Navigator) by
// providing a `parentNavigatorKey`.
void main() {
runApp(ShellRouteExampleApp());
}
/// An example demonstrating how to use [ShellRoute]
class ShellRouteExampleApp extends StatelessWidget {
/// Creates a [ShellRouteExampleApp]
ShellRouteExampleApp({super.key});
final GoRouter _router = GoRouter(
navigatorKey: _rootNavigatorKey,
initialLocation: '/a',
debugLogDiagnostics: true,
routes: <RouteBase>[
/// Application shell
ShellRoute(
navigatorKey: _shellNavigatorKey,
builder: (BuildContext context, GoRouterState state, Widget child) {
return ScaffoldWithNavBar(child: child);
},
routes: <RouteBase>[
/// The first screen to display in the bottom navigation bar.
GoRoute(
path: '/a',
builder: (BuildContext context, GoRouterState state) {
return const ScreenA();
},
routes: <RouteBase>[
// The details screen to display stacked on the inner Navigator.
// This will cover screen A but not the application shell.
GoRoute(
path: 'details',
builder: (BuildContext context, GoRouterState state) {
return const DetailsScreen(label: 'A');
},
),
],
),
/// Displayed when the second item in the the bottom navigation bar is
/// selected.
GoRoute(
path: '/b',
builder: (BuildContext context, GoRouterState state) {
return const ScreenB();
},
routes: <RouteBase>[
/// Same as "/a/details", but displayed on the root Navigator by
/// specifying [parentNavigatorKey]. This will cover both screen B
/// and the application shell.
GoRoute(
path: 'details',
parentNavigatorKey: _rootNavigatorKey,
builder: (BuildContext context, GoRouterState state) {
return const DetailsScreen(label: 'B');
},
),
],
),
/// The third screen to display in the bottom navigation bar.
GoRoute(
path: '/c',
builder: (BuildContext context, GoRouterState state) {
return const ScreenC();
},
routes: <RouteBase>[
// The details screen to display stacked on the inner Navigator.
// This will cover screen A but not the application shell.
GoRoute(
path: 'details',
builder: (BuildContext context, GoRouterState state) {
return const DetailsScreen(label: 'C');
},
),
],
),
],
),
],
);
@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.child,
super.key,
});
/// The widget to display in the body of the Scaffold.
/// In this sample, it is a Navigator.
final Widget child;
@override
Widget build(BuildContext context) {
return Scaffold(
body: child,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'A Screen',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'B Screen',
),
BottomNavigationBarItem(
icon: Icon(Icons.notification_important_rounded),
label: 'C Screen',
),
],
currentIndex: _calculateSelectedIndex(context),
onTap: (int idx) => _onItemTapped(idx, context),
),
);
}
static int _calculateSelectedIndex(BuildContext context) {
final String location = GoRouterState.of(context).uri.toString();
if (location.startsWith('/a')) {
return 0;
}
if (location.startsWith('/b')) {
return 1;
}
if (location.startsWith('/c')) {
return 2;
}
return 0;
}
void _onItemTapped(int index, BuildContext context) {
switch (index) {
case 0:
GoRouter.of(context).go('/a');
case 1:
GoRouter.of(context).go('/b');
case 2:
GoRouter.of(context).go('/c');
}
}
}
/// The first screen in the bottom navigation bar.
class ScreenA extends StatelessWidget {
/// Constructs a [ScreenA] widget.
const ScreenA({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Screen A'),
TextButton(
onPressed: () {
GoRouter.of(context).go('/a/details');
},
child: const Text('View A details'),
),
],
),
),
);
}
}
/// The second screen in the bottom navigation bar.
class ScreenB extends StatelessWidget {
/// Constructs a [ScreenB] widget.
const ScreenB({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Screen B'),
TextButton(
onPressed: () {
GoRouter.of(context).go('/b/details');
},
child: const Text('View B details'),
),
],
),
),
);
}
}
/// The third screen in the bottom navigation bar.
class ScreenC extends StatelessWidget {
/// Constructs a [ScreenC] widget.
const ScreenC({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Screen C'),
TextButton(
onPressed: () {
GoRouter.of(context).go('/c/details');
},
child: const Text('View C details'),
),
],
),
),
);
}
}
/// The details screen for either the A, B or C screen.
class DetailsScreen extends StatelessWidget {
/// Constructs a [DetailsScreen].
const DetailsScreen({
required this.label,
super.key,
});
/// The label to display in the center of the screen.
final String label;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Details Screen'),
),
body: Center(
child: Text(
'Details for $label',
style: Theme.of(context).textTheme.headlineMedium,
),
),
);
}
}
| packages/packages/go_router/example/lib/shell_route.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/shell_route.dart",
"repo_id": "packages",
"token_count": 3583
} | 1,035 |
// 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/exception_handling.dart' as example;
void main() {
testWidgets('example works', (WidgetTester tester) async {
await tester.pumpWidget(const example.MyApp());
expect(find.text('Simulates user entering unknown url'), findsOneWidget);
await tester.tap(find.text('Simulates user entering unknown url'));
await tester.pumpAndSettle();
expect(find.text("Can't find a page for: /some-unknown-route"),
findsOneWidget);
});
}
| packages/packages/go_router/example/test/exception_handling_test.dart/0 | {
"file_path": "packages/packages/go_router/example/test/exception_handling_test.dart",
"repo_id": "packages",
"token_count": 226
} | 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.
/// A declarative router for Flutter based on Navigation 2 supporting
/// deep linking, data-driven routes and more.
library go_router;
export 'src/builder.dart';
export 'src/configuration.dart';
export 'src/delegate.dart';
export 'src/information_provider.dart';
export 'src/match.dart' hide RouteMatchListCodec;
export 'src/misc/errors.dart';
export 'src/misc/extensions.dart';
export 'src/misc/inherited_router.dart';
export 'src/pages/custom_transition_page.dart';
export 'src/parser.dart';
export 'src/route.dart';
export 'src/route_data.dart' hide NoOpPage;
export 'src/router.dart';
export 'src/state.dart' hide GoRouterStateRegistry, GoRouterStateRegistryScope;
| packages/packages/go_router/lib/go_router.dart/0 | {
"file_path": "packages/packages/go_router/lib/go_router.dart",
"repo_id": "packages",
"token_count": 272
} | 1,037 |
// 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:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:meta/meta.dart';
import 'configuration.dart';
import 'match.dart';
import 'path_utils.dart';
import 'router.dart';
import 'state.dart';
/// The page builder for [GoRoute].
typedef GoRouterPageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
);
/// The widget builder for [GoRoute].
typedef GoRouterWidgetBuilder = Widget Function(
BuildContext context,
GoRouterState state,
);
/// The widget builder for [ShellRoute].
typedef ShellRouteBuilder = Widget Function(
BuildContext context,
GoRouterState state,
Widget child,
);
/// The page builder for [ShellRoute].
typedef ShellRoutePageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
Widget child,
);
/// The widget builder for [StatefulShellRoute].
typedef StatefulShellRouteBuilder = Widget Function(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
);
/// The page builder for [StatefulShellRoute].
typedef StatefulShellRoutePageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
);
/// Signature for functions used to build Navigators
typedef NavigatorBuilder = Widget Function(
List<NavigatorObserver>? observers, String? restorationScopeId);
/// Signature for function used in [RouteBase.onExit].
///
/// If the return value is true or the future resolve to true, the route will
/// exit as usual. Otherwise, the operation will abort.
typedef ExitCallback = FutureOr<bool> Function(BuildContext context);
/// The base class for [GoRoute] and [ShellRoute].
///
/// Routes are defined in a tree such that parent routes must match the
/// current location for their child route to be considered a match. For
/// example the location "/home/user/12" matches with parent route "/home" and
/// child route "user/:userId".
///
/// To create sub-routes for a route, provide them as a [GoRoute] list
/// with the sub routes.
///
/// For example these routes:
/// ```
/// / => HomePage()
/// family/f1 => FamilyPage('f1')
/// person/p2 => PersonPage('f1', 'p2') ← showing this page, Back pops ↑
/// ```
///
/// Can be represented as:
///
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'family/:fid',
/// pageBuilder: (BuildContext context, GoRouterState state) {
/// final Family family = Families.family(state.pathParameters['fid']!);
/// return MaterialPage<void>(
/// key: state.pageKey,
/// child: FamilyPage(family: family),
/// );
/// },
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'person/:pid',
/// pageBuilder: (BuildContext context, GoRouterState state) {
/// final Family family = Families.family(state.pathParameters['fid']!);
/// final Person person = family.person(state.pathParameters['pid']!);
/// return MaterialPage<void>(
/// key: state.pageKey,
/// child: PersonPage(family: family, person: person),
/// );
/// },
/// ),
/// ],
/// ),
/// ],
/// ),
/// ],
/// );
///
/// If there are multiple routes that match the location, the first match is used.
/// To make predefined routes to take precedence over dynamic routes eg. '/:id'
/// consider adding the dynamic route at the end of the routes
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/family/${Families.data[0].id}',
/// ),
/// GoRoute(
/// path: '/family',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// GoRoute(
/// path: '/:username',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// ],
/// );
/// ```
/// In the above example, if /family route is matched, it will be used.
/// else /:username route will be used.
/// ///
/// See [main.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart)
@immutable
abstract class RouteBase with Diagnosticable {
const RouteBase._({
required this.routes,
required this.parentNavigatorKey,
});
/// The list of child routes associated with this route.
final List<RouteBase> routes;
/// An optional key specifying which Navigator to display this route's screen
/// onto.
///
/// Specifying the root Navigator will stack this route onto that
/// Navigator instead of the nearest ShellRoute ancestor.
final GlobalKey<NavigatorState>? parentNavigatorKey;
/// Builds a lists containing the provided routes along with all their
/// descendant [routes].
static Iterable<RouteBase> routesRecursively(Iterable<RouteBase> routes) {
return routes.expand(
(RouteBase e) => <RouteBase>[e, ...routesRecursively(e.routes)]);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
if (parentNavigatorKey != null) {
properties.add(DiagnosticsProperty<GlobalKey<NavigatorState>>(
'parentNavKey', parentNavigatorKey));
}
}
}
/// A route that is displayed visually above the matching parent route using the
/// [Navigator].
///
/// The widget returned by [builder] is wrapped in [Page] and provided to the
/// root Navigator, the nearest ShellRoute ancestor's Navigator, or the
/// Navigator with a matching [parentNavigatorKey].
///
/// The Page depends on the application type: [MaterialPage] for
/// [MaterialApp], [CupertinoPage] for [CupertinoApp], or
/// [NoTransitionPage] for [WidgetsApp].
///
/// {@category Get started}
/// {@category Configuration}
/// {@category Transition animations}
/// {@category Named routes}
/// {@category Redirection}
class GoRoute extends RouteBase {
/// Constructs a [GoRoute].
/// - [path] and [name] cannot be empty strings.
/// - One of either [builder] or [pageBuilder] must be provided.
GoRoute({
required this.path,
this.name,
this.builder,
this.pageBuilder,
super.parentNavigatorKey,
this.redirect,
this.onExit,
super.routes = const <RouteBase>[],
}) : assert(path.isNotEmpty, 'GoRoute path cannot be empty'),
assert(name == null || name.isNotEmpty, 'GoRoute name cannot be empty'),
assert(pageBuilder != null || builder != null || redirect != null,
'builder, pageBuilder, or redirect must be provided'),
assert(onExit == null || pageBuilder != null || builder != null,
'if onExit is provided, one of pageBuilder or builder must be provided'),
super._() {
// cache the path regexp and parameters
_pathRE = patternToRegExp(path, pathParameters);
}
/// Whether this [GoRoute] only redirects to another route.
///
/// If this is true, this route must redirect location other than itself.
bool get redirectOnly => pageBuilder == null && builder == null;
/// Optional name of the route.
///
/// If used, a unique string name must be provided and it can not be empty.
///
/// This is used in [GoRouter.namedLocation] and its related API. This
/// property can be used to navigate to this route without knowing exact the
/// URI of it.
///
/// {@tool snippet}
/// Typical usage is as follows:
///
/// ```dart
/// GoRoute(
/// name: 'home',
/// path: '/',
/// builder: (BuildContext context, GoRouterState state) =>
/// HomeScreen(),
/// routes: <GoRoute>[
/// GoRoute(
/// name: 'family',
/// path: 'family/:fid',
/// builder: (BuildContext context, GoRouterState state) =>
/// FamilyScreen(),
/// ),
/// ],
/// );
///
/// context.go(
/// context.namedLocation('family'),
/// pathParameters: <String, String>{'fid': 123},
/// queryParameters: <String, String>{'qid': 'quid'},
/// );
/// ```
/// {@end-tool}
///
/// See the [named routes example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/named_routes.dart)
/// for a complete runnable app.
final String? name;
/// The path of this go route.
///
/// For example:
/// ```
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// ),
/// ```
///
/// The path also support path parameters. For a path: `/family/:fid`, it
/// matches all URIs start with `/family/...`, e.g. `/family/123`,
/// `/family/456` and etc. The parameter values are stored in [GoRouterState]
/// that are passed into [pageBuilder] and [builder].
///
/// The query parameter are also capture during the route parsing and stored
/// in [GoRouterState].
///
/// See [Query parameters and path parameters](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/path_and_query_parameters.dart)
/// to learn more about parameters.
final String path;
/// A page builder for this route.
///
/// Typically a MaterialPage, as in:
/// ```
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// ),
/// ```
///
/// You can also use CupertinoPage, and for a custom page builder to use
/// custom page transitions, you can use [CustomTransitionPage].
final GoRouterPageBuilder? pageBuilder;
/// A custom builder for this route.
///
/// For example:
/// ```
/// GoRoute(
/// path: '/',
/// builder: (BuildContext context, GoRouterState state) => FamilyPage(
/// families: Families.family(
/// state.pathParameters['id'],
/// ),
/// ),
/// ),
/// ```
///
final GoRouterWidgetBuilder? builder;
/// An optional redirect function for this route.
///
/// In the case that you like to make a redirection decision for a specific
/// route (or sub-route), consider doing so by passing a redirect function to
/// the GoRoute constructor.
///
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/family/${Families.data[0].id}',
/// ),
/// GoRoute(
/// path: '/family/:fid',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// ],
/// );
/// ```
///
/// If there are multiple redirects in the matched routes, the parent route's
/// redirect takes priority over sub-route's.
///
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/page1', // this takes priority over the sub-route.
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'child',
/// redirect: (_) => '/page2',
/// ),
/// ],
/// ),
/// ],
/// );
/// ```
///
/// The `context.go('/child')` will be redirected to `/page1` instead of
/// `/page2`.
///
/// Redirect can also be used for conditionally preventing users from visiting
/// routes, also known as route guards. One canonical example is user
/// authentication. See [Redirection](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/redirection.dart)
/// for a complete runnable example.
///
/// If [BuildContext.dependOnInheritedWidgetOfExactType] is used during the
/// redirection (which is how `of` method is usually implemented), a
/// re-evaluation will be triggered if the [InheritedWidget] changes.
final GoRouterRedirect? redirect;
/// Called when this route is removed from GoRouter's route history.
///
/// Some example this callback may be called:
/// * This route is removed as the result of [GoRouter.pop].
/// * This route is no longer in the route history after a [GoRouter.go].
///
/// This method can be useful it one wants to launch a dialog for user to
/// confirm if they want to exit the screen.
///
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// onExit: (BuildContext context) => showDialog<bool>(
/// context: context,
/// builder: (BuildContext context) {
/// return AlertDialog(
/// title: const Text('Do you want to exit this page?'),
/// actions: <Widget>[
/// TextButton(
/// style: TextButton.styleFrom(
/// textStyle: Theme.of(context).textTheme.labelLarge,
/// ),
/// child: const Text('Go Back'),
/// onPressed: () {
/// Navigator.of(context).pop(false);
/// },
/// ),
/// TextButton(
/// style: TextButton.styleFrom(
/// textStyle: Theme.of(context).textTheme.labelLarge,
/// ),
/// child: const Text('Confirm'),
/// onPressed: () {
/// Navigator.of(context).pop(true);
/// },
/// ),
/// ],
/// );
/// },
/// ),
/// ),
/// ],
/// );
/// ```
final ExitCallback? onExit;
// TODO(chunhtai): move all regex related help methods to path_utils.dart.
/// Match this route against a location.
RegExpMatch? matchPatternAsPrefix(String loc) =>
_pathRE.matchAsPrefix(loc) as RegExpMatch?;
/// Extract the path parameters from a match.
Map<String, String> extractPathParams(RegExpMatch match) =>
extractPathParameters(pathParameters, match);
/// The path parameters in this route.
@internal
final List<String> pathParameters = <String>[];
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('name', name));
properties.add(StringProperty('path', path));
properties.add(
FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'));
}
late final RegExp _pathRE;
}
/// Base class for classes that act as shells for sub-routes, such
/// as [ShellRoute] and [StatefulShellRoute].
abstract class ShellRouteBase extends RouteBase {
/// Constructs a [ShellRouteBase].
const ShellRouteBase._(
{required super.routes, required super.parentNavigatorKey})
: super._();
static void _debugCheckSubRouteParentNavigatorKeys(
List<RouteBase> subRoutes, GlobalKey<NavigatorState> navigatorKey) {
for (final RouteBase route in subRoutes) {
assert(
route.parentNavigatorKey == null ||
route.parentNavigatorKey == navigatorKey,
"sub-route's parent navigator key must either be null or has the same navigator key as parent's key");
if (route is GoRoute && route.redirectOnly) {
// This route does not produce a page, need to check its sub-routes
// instead.
_debugCheckSubRouteParentNavigatorKeys(route.routes, navigatorKey);
}
}
}
/// Attempts to build the Widget representing this shell route.
///
/// Returns null if this shell route does not build a Widget, but instead uses
/// a Page to represent itself (see [buildPage]).
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext);
/// Attempts to build the Page representing this shell route.
///
/// Returns null if this shell route does not build a Page, but instead uses
/// a Widget to represent itself (see [buildWidget]).
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext);
/// Returns the key for the [Navigator] that is to be used for the specified
/// immediate sub-route of this shell route.
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute);
}
/// Context object used when building the shell and Navigator for a shell route.
class ShellRouteContext {
/// Constructs a [ShellRouteContext].
ShellRouteContext({
required this.route,
required this.routerState,
required this.navigatorKey,
required this.routeMatchList,
required this.navigatorBuilder,
});
/// The associated shell route.
final ShellRouteBase route;
/// The current route state associated with [route].
final GoRouterState routerState;
/// The [Navigator] key to be used for the nested navigation associated with
/// [route].
final GlobalKey<NavigatorState> navigatorKey;
/// The route match list representing the current location within the
/// associated shell route.
final RouteMatchList routeMatchList;
/// Function used to build the [Navigator] for the current route.
final NavigatorBuilder navigatorBuilder;
}
/// A route that displays a UI shell around the matching child route.
///
/// When a ShellRoute is added to the list of routes on GoRouter or GoRoute, a
/// new Navigator is used to display any matching sub-routes instead of placing
/// them on the root Navigator.
///
/// To display a child route on a different Navigator, provide it with a
/// [parentNavigatorKey] that matches the key provided to either the [GoRouter]
/// or [ShellRoute] constructor. In this example, the _rootNavigator key is
/// passed to the /b/details route so that it displays on the root Navigator
/// instead of the ShellRoute's Navigator:
///
/// ```
/// final GlobalKey<NavigatorState> _rootNavigatorKey =
/// GlobalKey<NavigatorState>();
///
/// final GoRouter _router = GoRouter(
/// navigatorKey: _rootNavigatorKey,
/// initialLocation: '/a',
/// routes: [
/// ShellRoute(
/// navigatorKey: _shellNavigatorKey,
/// builder: (context, state, child) {
/// return ScaffoldWithNavBar(child: child);
/// },
/// routes: [
/// // This screen is displayed on the ShellRoute's Navigator.
/// GoRoute(
/// path: '/a',
/// builder: (context, state) {
/// return const ScreenA();
/// },
/// routes: <RouteBase>[
/// // This screen is displayed on the ShellRoute's Navigator.
/// GoRoute(
/// path: 'details',
/// builder: (BuildContext context, GoRouterState state) {
/// return const DetailsScreen(label: 'A');
/// },
/// ),
/// ],
/// ),
/// // Displayed ShellRoute's Navigator.
/// GoRoute(
/// path: '/b',
/// builder: (BuildContext context, GoRouterState state) {
/// return const ScreenB();
/// },
/// routes: <RouteBase>[
/// // Displayed on the root Navigator by specifying the
/// // [parentNavigatorKey].
/// GoRoute(
/// path: 'details',
/// parentNavigatorKey: _rootNavigatorKey,
/// builder: (BuildContext context, GoRouterState state) {
/// return const DetailsScreen(label: 'B');
/// },
/// ),
/// ],
/// ),
/// ],
/// ),
/// ],
/// );
/// ```
///
/// The widget built by the matching sub-route becomes the child parameter
/// of the [builder].
///
/// For example:
///
/// ```
/// ShellRoute(
/// builder: (BuildContext context, GoRouterState state, Widget child) {
/// return Scaffold(
/// appBar: AppBar(
/// title: Text('App Shell')
/// ),
/// body: Center(
/// child: child,
/// ),
/// );
/// },
/// routes: [
/// GoRoute(
/// path: 'a'
/// builder: (BuildContext context, GoRouterState state) {
/// return Text('Child Route "/a"');
/// }
/// ),
/// ],
/// ),
/// ```
///
/// {@category Configuration}
class ShellRoute extends ShellRouteBase {
/// Constructs a [ShellRoute].
ShellRoute({
this.builder,
this.pageBuilder,
this.observers,
required super.routes,
super.parentNavigatorKey,
GlobalKey<NavigatorState>? navigatorKey,
this.restorationScopeId,
}) : assert(routes.isNotEmpty),
navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>(),
super._() {
assert(() {
ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
routes, this.navigatorKey);
return true;
}());
}
/// The widget builder for a shell route.
///
/// Similar to [GoRoute.builder], but with an additional child parameter. This
/// child parameter is the Widget managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget.
final ShellRouteBuilder? builder;
/// The page builder for a shell route.
///
/// Similar to [GoRoute.pageBuilder], but with an additional child parameter.
/// This child parameter is the Widget managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget.
final ShellRoutePageBuilder? pageBuilder;
@override
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (builder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
return builder!(context, state, navigator);
}
return null;
}
@override
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (pageBuilder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
return pageBuilder!(context, state, navigator);
}
return null;
}
/// The observers for a shell route.
///
/// The observers parameter is used by the [Navigator] built for this route.
/// sub-route's observers.
final List<NavigatorObserver>? observers;
/// The [GlobalKey] to be used by the [Navigator] built for this route.
/// All ShellRoutes build a Navigator by default. Child GoRoutes
/// are placed onto this Navigator instead of the root Navigator.
final GlobalKey<NavigatorState> navigatorKey;
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
final String? restorationScopeId;
@override
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute) {
assert(routes.contains(subRoute));
return navigatorKey;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<GlobalKey<NavigatorState>>(
'navigatorKey', navigatorKey));
}
}
/// A route that displays a UI shell with separate [Navigator]s for its
/// sub-routes.
///
/// Similar to [ShellRoute], this route class places its sub-route on a
/// different Navigator than the root [Navigator]. However, this route class
/// differs in that it creates separate [Navigator]s for each of its nested
/// branches (i.e. parallel navigation trees), making it possible to build an
/// app with stateful nested navigation. This is convenient when for instance
/// implementing a UI with a [BottomNavigationBar], with a persistent navigation
/// state for each tab.
///
/// A StatefulShellRoute is created by specifying a List of
/// [StatefulShellBranch] items, each representing a separate stateful branch
/// in the route tree. StatefulShellBranch provides the root routes and the
/// Navigator key ([GlobalKey]) for the branch, as well as an optional initial
/// location.
///
/// Like [ShellRoute], either a [builder] or a [pageBuilder] must be provided
/// when creating a StatefulShellRoute. However, these builders differ slightly
/// in that they accept a [StatefulNavigationShell] parameter instead of a
/// child Widget. The StatefulNavigationShell can be used to access information
/// about the state of the route, as well as to switch the active branch (i.e.
/// restoring the navigation stack of another branch). The latter is
/// accomplished by using the method [StatefulNavigationShell.goBranch], for
/// example:
///
/// ```
/// void _onItemTapped(int index) {
/// navigationShell.goBranch(index: index);
/// }
/// ```
///
/// The StatefulNavigationShell is also responsible for managing and maintaining
/// the state of the branch Navigators. Typically, a shell is built around this
/// Widget, for example by using it as the body of [Scaffold] with a
/// [BottomNavigationBar].
///
/// When creating a StatefulShellRoute, a [navigatorContainerBuilder] function
/// must be provided. This function is responsible for building the actual
/// container for the Widgets representing the branch Navigators. Typically,
/// the Widget returned by this function handles the layout (including
/// [Offstage] handling etc) of the branch Navigators and any animations needed
/// when switching active branch.
///
/// For a default implementation of [navigatorContainerBuilder] that is
/// appropriate for most use cases, consider using the constructor
/// [StatefulShellRoute.indexedStack].
///
/// With StatefulShellRoute (and any route below it), animated transitions
/// between routes in the same navigation stack works the same way as with other
/// route classes, and can be customized using pageBuilder. However, since
/// StatefulShellRoute maintains a set of parallel navigation stacks,
/// any transitions when switching between branches is the responsibility of the
/// branch Navigator container (i.e. [navigatorContainerBuilder]). The default
/// [IndexedStack] implementation ([StatefulShellRoute.indexedStack]) does not
/// use animated transitions, but an example is provided on how to accomplish
/// this (see link to custom StatefulShellRoute example below).
///
/// See also:
/// * [StatefulShellRoute.indexedStack] which provides a default
/// StatefulShellRoute implementation suitable for most use cases.
/// * [Stateful Nested Navigation example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stateful_shell_route.dart)
/// for a complete runnable example using StatefulShellRoute.
/// * [Custom StatefulShellRoute example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/others/custom_stateful_shell_route.dart)
/// which demonstrates how to customize the container for the branch Navigators
/// and how to implement animated transitions when switching branches.
class StatefulShellRoute extends ShellRouteBase {
/// Constructs a [StatefulShellRoute] from a list of [StatefulShellBranch]es,
/// each representing a separate nested navigation tree (branch).
///
/// A separate [Navigator] will be created for each of the branches, using
/// the navigator key specified in [StatefulShellBranch]. The Widget
/// implementing the container for the branch Navigators is provided by
/// [navigatorContainerBuilder].
StatefulShellRoute({
required this.branches,
this.builder,
this.pageBuilder,
required this.navigatorContainerBuilder,
super.parentNavigatorKey,
this.restorationScopeId,
}) : assert(branches.isNotEmpty),
assert((pageBuilder != null) || (builder != null),
'One of builder or pageBuilder must be provided'),
assert(_debugUniqueNavigatorKeys(branches).length == branches.length,
'Navigator keys must be unique'),
assert(_debugValidateParentNavigatorKeys(branches)),
assert(_debugValidateRestorationScopeIds(restorationScopeId, branches)),
super._(routes: _routes(branches));
/// Constructs a StatefulShellRoute that uses an [IndexedStack] for its
/// nested [Navigator]s.
///
/// This constructor provides an IndexedStack based implementation for the
/// container ([navigatorContainerBuilder]) used to manage the Widgets
/// representing the branch Navigators. Apart from that, this constructor
/// works the same way as the default constructor.
///
/// See [Stateful Nested Navigation](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stacked_shell_route.dart)
/// for a complete runnable example using StatefulShellRoute.indexedStack.
StatefulShellRoute.indexedStack({
required List<StatefulShellBranch> branches,
StatefulShellRouteBuilder? builder,
GlobalKey<NavigatorState>? parentNavigatorKey,
StatefulShellRoutePageBuilder? pageBuilder,
String? restorationScopeId,
}) : this(
branches: branches,
builder: builder,
pageBuilder: pageBuilder,
parentNavigatorKey: parentNavigatorKey,
restorationScopeId: restorationScopeId,
navigatorContainerBuilder: _indexedStackContainerBuilder,
);
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
final String? restorationScopeId;
/// The widget builder for a stateful shell route.
///
/// Similar to [GoRoute.builder], but with an additional
/// [StatefulNavigationShell] parameter. StatefulNavigationShell is a Widget
/// responsible for managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget. StatefulNavigationShell can also be used to access information
/// about which branch is active, and also to navigate to a different branch
/// (using [StatefulNavigationShell.goBranch]).
///
/// Custom implementations may choose to ignore the child parameter passed to
/// the builder function, and instead use [StatefulNavigationShell] to
/// create a custom container for the branch Navigators.
final StatefulShellRouteBuilder? builder;
/// The page builder for a stateful shell route.
///
/// Similar to [GoRoute.pageBuilder], but with an additional
/// [StatefulNavigationShell] parameter. StatefulNavigationShell is a Widget
/// responsible for managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget. StatefulNavigationShell can also be used to access information
/// about which branch is active, and also to navigate to a different branch
/// (using [StatefulNavigationShell.goBranch]).
///
/// Custom implementations may choose to ignore the child parameter passed to
/// the builder function, and instead use [StatefulNavigationShell] to
/// create a custom container for the branch Navigators.
final StatefulShellRoutePageBuilder? pageBuilder;
/// The builder for the branch Navigator container.
///
/// The function responsible for building the container for the branch
/// Navigators. When this function is invoked, access is provided to a List of
/// Widgets representing the branch Navigators, where the the index
/// corresponds to the index of in [branches].
///
/// The builder function is expected to return a Widget that ensures that the
/// state of the branch Widgets is maintained, for instance by inducting them
/// in the Widget tree.
final ShellNavigationContainerBuilder navigatorContainerBuilder;
/// Representations of the different stateful route branches that this
/// shell route will manage.
///
/// Each branch uses a separate [Navigator], identified
/// [StatefulShellBranch.navigatorKey].
final List<StatefulShellBranch> branches;
final GlobalKey<StatefulNavigationShellState> _shellStateKey =
GlobalKey<StatefulNavigationShellState>();
@override
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (builder != null) {
return builder!(context, state, _createShell(context, shellRouteContext));
}
return null;
}
@override
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (pageBuilder != null) {
return pageBuilder!(
context, state, _createShell(context, shellRouteContext));
}
return null;
}
@override
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute) {
final StatefulShellBranch? branch = branches.firstWhereOrNull(
(StatefulShellBranch e) => e.routes.contains(subRoute));
assert(branch != null);
return branch!.navigatorKey;
}
Iterable<GlobalKey<NavigatorState>> get _navigatorKeys =>
branches.map((StatefulShellBranch b) => b.navigatorKey);
StatefulNavigationShell _createShell(
BuildContext context, ShellRouteContext shellRouteContext) =>
StatefulNavigationShell(
shellRouteContext: shellRouteContext,
router: GoRouter.of(context),
containerBuilder: navigatorContainerBuilder);
static Widget _indexedStackContainerBuilder(BuildContext context,
StatefulNavigationShell navigationShell, List<Widget> children) {
return _IndexedStackedRouteBranchContainer(
currentIndex: navigationShell.currentIndex, children: children);
}
static List<RouteBase> _routes(List<StatefulShellBranch> branches) =>
branches.expand((StatefulShellBranch e) => e.routes).toList();
static Set<GlobalKey<NavigatorState>> _debugUniqueNavigatorKeys(
List<StatefulShellBranch> branches) =>
Set<GlobalKey<NavigatorState>>.from(
branches.map((StatefulShellBranch e) => e.navigatorKey));
static bool _debugValidateParentNavigatorKeys(
List<StatefulShellBranch> branches) {
for (final StatefulShellBranch branch in branches) {
for (final RouteBase route in branch.routes) {
if (route is GoRoute) {
assert(route.parentNavigatorKey == null ||
route.parentNavigatorKey == branch.navigatorKey);
}
}
}
return true;
}
static bool _debugValidateRestorationScopeIds(
String? restorationScopeId, List<StatefulShellBranch> branches) {
if (branches
.map((StatefulShellBranch e) => e.restorationScopeId)
.whereNotNull()
.isNotEmpty) {
assert(
restorationScopeId != null,
'A restorationScopeId must be set for '
'the StatefulShellRoute when using restorationScopeIds on one or more '
'of the branches');
}
return true;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Iterable<GlobalKey<NavigatorState>>>(
'navigatorKeys', _navigatorKeys));
}
}
/// Representation of a separate branch in a stateful navigation tree, used to
/// configure [StatefulShellRoute].
///
/// The only required argument when creating a StatefulShellBranch is the
/// sub-routes ([routes]), however sometimes it may be convenient to also
/// provide a [initialLocation]. The value of this parameter is used when
/// loading the branch for the first time (for instance when switching branch
/// using the goBranch method in [StatefulNavigationShell]).
///
/// A separate [Navigator] will be built for each StatefulShellBranch in a
/// [StatefulShellRoute], and the routes of this branch will be placed onto that
/// Navigator instead of the root Navigator. A custom [navigatorKey] can be
/// provided when creating a StatefulShellBranch, which can be useful when the
/// Navigator needs to be accessed elsewhere. If no key is provided, a default
/// one will be created.
@immutable
class StatefulShellBranch {
/// Constructs a [StatefulShellBranch].
StatefulShellBranch({
required this.routes,
GlobalKey<NavigatorState>? navigatorKey,
this.initialLocation,
this.restorationScopeId,
this.observers,
}) : navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>() {
assert(() {
ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
routes, this.navigatorKey);
return true;
}());
}
/// The [GlobalKey] to be used by the [Navigator] built for this branch.
///
/// A separate Navigator will be built for each StatefulShellBranch in a
/// [StatefulShellRoute] and this key will be used to identify the Navigator.
/// The routes associated with this branch will be placed o onto that
/// Navigator instead of the root Navigator.
final GlobalKey<NavigatorState> navigatorKey;
/// The list of child routes associated with this route branch.
final List<RouteBase> routes;
/// The initial location for this route branch.
///
/// If none is specified, the location of the first descendant [GoRoute] will
/// be used (i.e. [defaultRoute]). The initial location is used when loading
/// the branch for the first time (for instance when switching branch using
/// the goBranch method).
final String? initialLocation;
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
final String? restorationScopeId;
/// The observers for this branch.
///
/// The observers parameter is used by the [Navigator] built for this branch.
final List<NavigatorObserver>? observers;
/// The default route of this branch, i.e. the first descendant [GoRoute].
///
/// This route will be used when loading the branch for the first time, if
/// an [initialLocation] has not been provided.
GoRoute? get defaultRoute =>
RouteBase.routesRecursively(routes).whereType<GoRoute>().firstOrNull;
}
/// Builder for a custom container for the branch Navigators of a
/// [StatefulShellRoute].
typedef ShellNavigationContainerBuilder = Widget Function(BuildContext context,
StatefulNavigationShell navigationShell, List<Widget> children);
/// Widget for managing the state of a [StatefulShellRoute].
///
/// Normally, this widget is not used directly, but is instead created
/// internally by StatefulShellRoute. However, if a custom container for the
/// branch Navigators is required, StatefulNavigationShell can be used in
/// the builder or pageBuilder methods of StatefulShellRoute to facilitate this.
/// The container is created using the provided [ShellNavigationContainerBuilder],
/// where the List of Widgets represent the Navigators for each branch.
///
/// Example:
/// ```
/// builder: (BuildContext context, GoRouterState state,
/// StatefulNavigationShell navigationShell) {
/// return StatefulNavigationShell(
/// shellRouteState: state,
/// containerBuilder: (_, __, List<Widget> children) => MyCustomShell(shellState: state, children: children),
/// );
/// }
/// ```
class StatefulNavigationShell extends StatefulWidget {
/// Constructs an [StatefulNavigationShell].
StatefulNavigationShell({
required this.shellRouteContext,
required GoRouter router,
required this.containerBuilder,
}) : assert(shellRouteContext.route is StatefulShellRoute),
_router = router,
currentIndex = _indexOfBranchNavigatorKey(
shellRouteContext.route as StatefulShellRoute,
shellRouteContext.navigatorKey),
super(
key:
(shellRouteContext.route as StatefulShellRoute)._shellStateKey);
/// The ShellRouteContext responsible for building the Navigator for the
/// current [StatefulShellBranch].
final ShellRouteContext shellRouteContext;
final GoRouter _router;
/// The builder for a custom container for shell route Navigators.
final ShellNavigationContainerBuilder containerBuilder;
/// The index of the currently active [StatefulShellBranch].
///
/// Corresponds to the index in the branches field of [StatefulShellRoute].
final int currentIndex;
/// The associated [StatefulShellRoute].
StatefulShellRoute get route => shellRouteContext.route as StatefulShellRoute;
/// Navigate to the last location of the [StatefulShellBranch] at the provided
/// index in the associated [StatefulShellBranch].
///
/// This method will switch the currently active branch [Navigator] for the
/// [StatefulShellRoute]. If the branch has not been visited before, or if
/// initialLocation is true, this method will navigate to initial location of
/// the branch (see [StatefulShellBranch.initialLocation]).
// TODO(chunhtai): figure out a way to avoid putting navigation API in widget
// class.
void goBranch(int index, {bool initialLocation = false}) {
final StatefulShellRoute route =
shellRouteContext.route as StatefulShellRoute;
final StatefulNavigationShellState? shellState =
route._shellStateKey.currentState;
if (shellState != null) {
shellState.goBranch(index, initialLocation: initialLocation);
} else {
_router.go(_effectiveInitialBranchLocation(index));
}
}
/// Gets the effective initial location for the branch at the provided index
/// in the associated [StatefulShellRoute].
///
/// The effective initial location is either the
/// [StackedShellBranch.initialLocation], if specified, or the location of the
/// [StackedShellBranch.defaultRoute].
String _effectiveInitialBranchLocation(int index) {
final StatefulShellRoute route =
shellRouteContext.route as StatefulShellRoute;
final StatefulShellBranch branch = route.branches[index];
final String? initialLocation = branch.initialLocation;
if (initialLocation != null) {
return initialLocation;
} else {
/// Recursively traverses the routes of the provided StackedShellBranch to
/// find the first GoRoute, from which a full path will be derived.
final GoRoute route = branch.defaultRoute!;
return _router.configuration.locationForRoute(route)!;
}
}
@override
State<StatefulWidget> createState() => StatefulNavigationShellState();
/// Gets the state for the nearest stateful shell route in the Widget tree.
static StatefulNavigationShellState of(BuildContext context) {
final StatefulNavigationShellState? shellState =
context.findAncestorStateOfType<StatefulNavigationShellState>();
assert(shellState != null);
return shellState!;
}
/// Gets the state for the nearest stateful shell route in the Widget tree.
///
/// Returns null if no stateful shell route is found.
static StatefulNavigationShellState? maybeOf(BuildContext context) {
final StatefulNavigationShellState? shellState =
context.findAncestorStateOfType<StatefulNavigationShellState>();
return shellState;
}
static int _indexOfBranchNavigatorKey(
StatefulShellRoute route, GlobalKey<NavigatorState> navigatorKey) {
final int index = route.branches.indexWhere(
(StatefulShellBranch branch) => branch.navigatorKey == navigatorKey);
assert(index >= 0);
return index;
}
}
/// State for StatefulNavigationShell.
class StatefulNavigationShellState extends State<StatefulNavigationShell>
with RestorationMixin {
final Map<Key, Widget> _branchNavigators = <Key, Widget>{};
/// The associated [StatefulShellRoute].
StatefulShellRoute get route => widget.route;
GoRouter get _router => widget._router;
final Map<StatefulShellBranch, _RestorableRouteMatchList> _branchLocations =
<StatefulShellBranch, _RestorableRouteMatchList>{};
@override
String? get restorationId => route.restorationScopeId;
/// Generates a derived restoration ID for the branch location property,
/// falling back to the identity hash code of the branch to ensure an ID is
/// always returned (needed for _RestorableRouteMatchList/RestorableValue).
String _branchLocationRestorationScopeId(StatefulShellBranch branch) {
return branch.restorationScopeId != null
? '${branch.restorationScopeId}-location'
: identityHashCode(branch).toString();
}
_RestorableRouteMatchList _branchLocation(StatefulShellBranch branch,
[bool register = true]) {
return _branchLocations.putIfAbsent(branch, () {
final _RestorableRouteMatchList branchLocation =
_RestorableRouteMatchList(_router.configuration);
if (register) {
registerForRestoration(
branchLocation, _branchLocationRestorationScopeId(branch));
}
return branchLocation;
});
}
RouteMatchList? _matchListForBranch(int index) =>
_branchLocations[route.branches[index]]?.value;
/// Creates a new RouteMatchList that is scoped to the Navigators of the
/// current shell route or it's descendants. This involves removing all the
/// trailing imperative matches from the RouterMatchList that are targeted at
/// any other (often top-level) Navigator.
RouteMatchList _scopedMatchList(RouteMatchList matchList) {
return matchList.copyWith(matches: _scopeMatches(matchList.matches));
}
List<RouteMatchBase> _scopeMatches(List<RouteMatchBase> matches) {
final List<RouteMatchBase> result = <RouteMatchBase>[];
for (final RouteMatchBase match in matches) {
if (match is ShellRouteMatch) {
if (match.route == route) {
result.add(match);
// Discard any other route match after current shell route.
break;
}
result.add(match.copyWith(matches: _scopeMatches(match.matches)));
continue;
}
result.add(match);
}
return result;
}
void _updateCurrentBranchStateFromWidget() {
final StatefulShellBranch branch = route.branches[widget.currentIndex];
final ShellRouteContext shellRouteContext = widget.shellRouteContext;
final RouteMatchList currentBranchLocation =
_scopedMatchList(shellRouteContext.routeMatchList);
final _RestorableRouteMatchList branchLocation =
_branchLocation(branch, false);
final RouteMatchList previousBranchLocation = branchLocation.value;
branchLocation.value = currentBranchLocation;
final bool hasExistingNavigator =
_branchNavigators[branch.navigatorKey] != null;
/// Only update the Navigator of the route match list has changed
final bool locationChanged =
previousBranchLocation != currentBranchLocation;
if (locationChanged || !hasExistingNavigator) {
_branchNavigators[branch.navigatorKey] = shellRouteContext
.navigatorBuilder(branch.observers, branch.restorationScopeId);
}
}
/// The index of the currently active [StatefulShellBranch].
///
/// Corresponds to the index in the branches field of [StatefulShellRoute].
int get currentIndex => widget.currentIndex;
/// Navigate to the last location of the [StatefulShellBranch] at the provided
/// index in the associated [StatefulShellBranch].
///
/// This method will switch the currently active branch [Navigator] for the
/// [StatefulShellRoute]. If the branch has not been visited before, or if
/// initialLocation is true, this method will navigate to initial location of
/// the branch (see [StatefulShellBranch.initialLocation]).
void goBranch(int index, {bool initialLocation = false}) {
assert(index >= 0 && index < route.branches.length);
final RouteMatchList? matchList =
initialLocation ? null : _matchListForBranch(index);
if (matchList != null && matchList.isNotEmpty) {
_router.restore(matchList);
} else {
_router.go(widget._effectiveInitialBranchLocation(index));
}
}
@override
void initState() {
super.initState();
_updateCurrentBranchStateFromWidget();
}
@override
void dispose() {
super.dispose();
for (final StatefulShellBranch branch in route.branches) {
_branchLocations[branch]?.dispose();
}
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
route.branches.forEach(_branchLocation);
}
@override
void didUpdateWidget(covariant StatefulNavigationShell oldWidget) {
super.didUpdateWidget(oldWidget);
_updateCurrentBranchStateFromWidget();
}
@override
Widget build(BuildContext context) {
final List<Widget> children = route.branches
.map((StatefulShellBranch branch) => _BranchNavigatorProxy(
key: ObjectKey(branch),
branch: branch,
navigatorForBranch: (StatefulShellBranch b) =>
_branchNavigators[b.navigatorKey]))
.toList();
return widget.containerBuilder(context, widget, children);
}
}
/// [RestorableProperty] for enabling state restoration of [RouteMatchList]s.
class _RestorableRouteMatchList extends RestorableProperty<RouteMatchList> {
_RestorableRouteMatchList(RouteConfiguration configuration)
: _matchListCodec = RouteMatchListCodec(configuration);
final RouteMatchListCodec _matchListCodec;
RouteMatchList get value => _value;
RouteMatchList _value = RouteMatchList.empty;
set value(RouteMatchList newValue) {
if (newValue != _value) {
_value = newValue;
notifyListeners();
}
}
@override
void initWithValue(RouteMatchList value) {
_value = value;
}
@override
RouteMatchList createDefaultValue() => RouteMatchList.empty;
@override
RouteMatchList fromPrimitives(Object? data) {
return data == null
? RouteMatchList.empty
: _matchListCodec.decode(data as Map<Object?, Object?>);
}
@override
Object? toPrimitives() {
if (value.isNotEmpty) {
return _matchListCodec.encode(value);
}
return null;
}
}
typedef _NavigatorForBranch = Widget? Function(StatefulShellBranch);
/// Widget that serves as the proxy for a branch Navigator Widget, which
/// possibly hasn't been created yet.
///
/// This Widget hides the logic handling whether a Navigator Widget has been
/// created yet for a branch or not, and at the same time ensures that the same
/// Widget class is consistently passed to the containerBuilder. The latter is
/// important for container implementations that cache child widgets,
/// such as [TabBarView].
class _BranchNavigatorProxy extends StatefulWidget {
const _BranchNavigatorProxy({
super.key,
required this.branch,
required this.navigatorForBranch,
});
final StatefulShellBranch branch;
final _NavigatorForBranch navigatorForBranch;
@override
State<StatefulWidget> createState() => _BranchNavigatorProxyState();
}
/// State for _BranchNavigatorProxy, using AutomaticKeepAliveClientMixin to
/// properly handle some scenarios where Slivers are used to manage the branches
/// (such as [TabBarView]).
class _BranchNavigatorProxyState extends State<_BranchNavigatorProxy>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return widget.navigatorForBranch(widget.branch) ?? const SizedBox.shrink();
}
@override
bool get wantKeepAlive => true;
}
/// Default implementation of a container widget for the [Navigator]s of the
/// route branches. This implementation uses an [IndexedStack] as a container.
class _IndexedStackedRouteBranchContainer extends StatelessWidget {
const _IndexedStackedRouteBranchContainer(
{required this.currentIndex, required this.children});
final int currentIndex;
final List<Widget> children;
@override
Widget build(BuildContext context) {
final List<Widget> stackItems = children
.mapIndexed((int index, Widget child) =>
_buildRouteBranchContainer(context, currentIndex == index, child))
.toList();
return IndexedStack(index: currentIndex, children: stackItems);
}
Widget _buildRouteBranchContainer(
BuildContext context, bool isActive, Widget child) {
return Offstage(
offstage: !isActive,
child: TickerMode(
enabled: isActive,
child: child,
),
);
}
}
| packages/packages/go_router/lib/src/route.dart/0 | {
"file_path": "packages/packages/go_router/lib/src/route.dart",
"repo_id": "packages",
"token_count": 17063
} | 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 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router/src/state.dart';
import 'test_helpers.dart';
void main() {
group('GoRouterState from context', () {
testWidgets('works in builder', (WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, _) {
final GoRouterState state = GoRouterState.of(context);
return Text('/ ${state.uri.queryParameters['p']}');
}),
GoRoute(
path: '/a',
builder: (BuildContext context, _) {
final GoRouterState state = GoRouterState.of(context);
return Text('/a ${state.uri.queryParameters['p']}');
}),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/?p=123');
await tester.pumpAndSettle();
expect(find.text('/ 123'), findsOneWidget);
router.go('/a?p=456');
await tester.pumpAndSettle();
expect(find.text('/a 456'), findsOneWidget);
});
testWidgets('works in subtree', (WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text('1 ${GoRouterState.of(context).uri}');
});
},
routes: <GoRoute>[
GoRoute(
path: 'a',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text('2 ${GoRouterState.of(context).uri}');
});
}),
]),
];
final GoRouter router = await createRouter(routes, tester);
router.go('/?p=123');
await tester.pumpAndSettle();
expect(find.text('1 /?p=123'), findsOneWidget);
router.go('/a');
await tester.pumpAndSettle();
expect(find.text('2 /a'), findsOneWidget);
// The query parameter is removed, so is the location in first page.
expect(find.text('1 /a', skipOffstage: false), findsOneWidget);
});
testWidgets('path parameter persists after page is popped',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text('1 ${GoRouterState.of(context).uri}');
});
},
routes: <GoRoute>[
GoRoute(
path: ':id',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text(
'2 ${GoRouterState.of(context).pathParameters['id']}');
});
}),
]),
];
final GoRouter router = await createRouter(routes, tester);
await tester.pumpAndSettle();
expect(find.text('1 /'), findsOneWidget);
router.go('/123');
await tester.pumpAndSettle();
expect(find.text('2 123'), findsOneWidget);
router.pop();
await tester.pump();
// Page 2 is in popping animation but should still be on screen with the
// correct path parameter.
expect(find.text('2 123'), findsOneWidget);
});
testWidgets('registry retains GoRouterState for exiting route',
(WidgetTester tester) async {
final UniqueKey key = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text(GoRouterState.of(context).uri.toString());
});
},
routes: <GoRoute>[
GoRoute(
path: 'a',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text(
key: key, GoRouterState.of(context).uri.toString());
});
}),
]),
];
final GoRouter router =
await createRouter(routes, tester, initialLocation: '/a?p=123');
expect(tester.widget<Text>(find.byKey(key)).data, '/a?p=123');
final GoRouterStateRegistry registry = tester
.widget<GoRouterStateRegistryScope>(
find.byType(GoRouterStateRegistryScope))
.notifier!;
expect(registry.registry.length, 2);
router.go('/');
await tester.pump();
expect(registry.registry.length, 2);
// should retain the same location even if the location has changed.
expect(tester.widget<Text>(find.byKey(key)).data, '/a?p=123');
// Finish the pop animation.
await tester.pumpAndSettle();
expect(registry.registry.length, 1);
expect(find.byKey(key), findsNothing);
});
testWidgets('imperative pop clears out registry',
(WidgetTester tester) async {
final UniqueKey key = UniqueKey();
final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text(GoRouterState.of(context).uri.toString());
});
},
routes: <GoRoute>[
GoRoute(
path: 'a',
builder: (_, __) {
return Builder(builder: (BuildContext context) {
return Text(
key: key, GoRouterState.of(context).uri.toString());
});
}),
]),
];
await createRouter(routes, tester,
initialLocation: '/a?p=123', navigatorKey: nav);
expect(tester.widget<Text>(find.byKey(key)).data, '/a?p=123');
final GoRouterStateRegistry registry = tester
.widget<GoRouterStateRegistryScope>(
find.byType(GoRouterStateRegistryScope))
.notifier!;
expect(registry.registry.length, 2);
nav.currentState!.pop();
await tester.pump();
expect(registry.registry.length, 2);
// should retain the same location even if the location has changed.
expect(tester.widget<Text>(find.byKey(key)).data, '/a?p=123');
// Finish the pop animation.
await tester.pumpAndSettle();
expect(registry.registry.length, 1);
expect(find.byKey(key), findsNothing);
});
testWidgets('GoRouterState topRoute accessible from StatefulShellRoute',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shellNavigatorKey =
GlobalKey<NavigatorState>();
final List<RouteBase> routes = <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKey,
builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: Column(
children: <Widget>[
const Text('Screen 0'),
Expanded(child: child),
],
),
);
},
routes: <RouteBase>[
GoRoute(
name: 'root',
path: '/',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen 1'),
);
},
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
parentNavigatorKey: rootNavigatorKey,
builder: (
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
) {
final String? routeName =
GoRouterState.of(context).topRoute?.name;
final String title = switch (routeName) {
'a' => 'A',
'b' => 'B',
_ => 'Unknown',
};
return Column(
children: <Widget>[
Text(title),
Expanded(child: navigationShell),
],
);
},
branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
name: 'a',
path: 'a',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen 2'),
);
},
),
],
),
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
name: 'b',
path: 'b',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen 2'),
);
},
),
],
)
],
),
],
)
],
),
];
final GoRouter router = await createRouter(routes, tester,
initialLocation: '/a', navigatorKey: rootNavigatorKey);
expect(find.text('A'), findsOneWidget);
router.go('/b');
await tester.pumpAndSettle();
expect(find.text('B'), findsOneWidget);
});
});
}
| packages/packages/go_router/test/go_router_state_test.dart/0 | {
"file_path": "packages/packages/go_router/test/go_router_state_test.dart",
"repo_id": "packages",
"token_count": 5426
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
class _GoRouteDataBuild extends GoRouteData {
const _GoRouteDataBuild();
@override
Widget build(BuildContext context, GoRouterState state) =>
const SizedBox(key: Key('build'));
}
class _ShellRouteDataBuilder extends ShellRouteData {
const _ShellRouteDataBuilder();
@override
Widget builder(
BuildContext context,
GoRouterState state,
Widget navigator,
) =>
SizedBox(
key: const Key('builder'),
child: navigator,
);
}
class _ShellRouteDataWithKey extends ShellRouteData {
const _ShellRouteDataWithKey(this.key);
final Key key;
@override
Widget builder(
BuildContext context,
GoRouterState state,
Widget navigator,
) =>
SizedBox(
key: key,
child: navigator,
);
}
class _GoRouteDataBuildWithKey extends GoRouteData {
const _GoRouteDataBuildWithKey(this.key);
final Key key;
@override
Widget build(BuildContext context, GoRouterState state) => SizedBox(key: key);
}
final GoRoute _goRouteDataBuild = GoRouteData.$route(
path: '/build',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
);
final ShellRoute _shellRouteDataBuilder = ShellRouteData.$route(
factory: (GoRouterState state) => const _ShellRouteDataBuilder(),
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
);
class _GoRouteDataBuildPage extends GoRouteData {
const _GoRouteDataBuildPage();
@override
Page<void> buildPage(BuildContext context, GoRouterState state) =>
const MaterialPage<void>(
child: SizedBox(key: Key('buildPage')),
);
}
class _ShellRouteDataPageBuilder extends ShellRouteData {
const _ShellRouteDataPageBuilder();
@override
Page<void> pageBuilder(
BuildContext context,
GoRouterState state,
Widget navigator,
) =>
MaterialPage<void>(
child: SizedBox(
key: const Key('page-builder'),
child: navigator,
),
);
}
final GoRoute _goRouteDataBuildPage = GoRouteData.$route(
path: '/build-page',
factory: (GoRouterState state) => const _GoRouteDataBuildPage(),
);
final ShellRoute _shellRouteDataPageBuilder = ShellRouteData.$route(
factory: (GoRouterState state) => const _ShellRouteDataPageBuilder(),
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
);
class _StatefulShellRouteDataBuilder extends StatefulShellRouteData {
const _StatefulShellRouteDataBuilder();
@override
Widget builder(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigator,
) =>
SizedBox(
key: const Key('builder'),
child: navigator,
);
}
final StatefulShellRoute _statefulShellRouteDataBuilder =
StatefulShellRouteData.$route(
factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(),
branches: <StatefulShellBranch>[
StatefulShellBranchData.$branch(
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
),
],
);
class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData {
const _StatefulShellRouteDataPageBuilder();
@override
Page<void> pageBuilder(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigator,
) =>
MaterialPage<void>(
child: SizedBox(
key: const Key('page-builder'),
child: navigator,
),
);
}
final StatefulShellRoute _statefulShellRouteDataPageBuilder =
StatefulShellRouteData.$route(
factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(),
branches: <StatefulShellBranch>[
StatefulShellBranchData.$branch(
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
),
],
);
class _GoRouteDataRedirectPage extends GoRouteData {
const _GoRouteDataRedirectPage();
@override
FutureOr<String> redirect(BuildContext context, GoRouterState state) =>
'/build-page';
}
final GoRoute _goRouteDataRedirect = GoRouteData.$route(
path: '/redirect',
factory: (GoRouterState state) => const _GoRouteDataRedirectPage(),
);
final List<GoRoute> _routes = <GoRoute>[
_goRouteDataBuild,
_goRouteDataBuildPage,
_goRouteDataRedirect,
];
void main() {
group('GoRouteData', () {
testWidgets(
'It should build the page from the overridden build method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/build',
routes: _routes,
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('build')), findsOneWidget);
expect(find.byKey(const Key('buildPage')), findsNothing);
},
);
testWidgets(
'It should build the page from the overridden buildPage method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/build-page',
routes: _routes,
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('build')), findsNothing);
expect(find.byKey(const Key('buildPage')), findsOneWidget);
},
);
});
group('ShellRouteData', () {
testWidgets(
'It should build the page from the overridden build method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/child',
routes: <RouteBase>[
_shellRouteDataBuilder,
],
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('builder')), findsOneWidget);
expect(find.byKey(const Key('page-builder')), findsNothing);
},
);
testWidgets(
'It should build the page from the overridden build method',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> inner = GlobalKey<NavigatorState>();
final GoRouter goRouter = GoRouter(
navigatorKey: root,
initialLocation: '/child/test',
routes: <RouteBase>[
ShellRouteData.$route(
factory: (GoRouterState state) =>
const _ShellRouteDataWithKey(Key('under-shell')),
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) =>
const _GoRouteDataBuildWithKey(Key('under')),
routes: <RouteBase>[
ShellRouteData.$route(
factory: (GoRouterState state) =>
const _ShellRouteDataWithKey(Key('above-shell')),
navigatorKey: inner,
parentNavigatorKey: root,
routes: <RouteBase>[
GoRouteData.$route(
parentNavigatorKey: inner,
path: 'test',
factory: (GoRouterState state) =>
const _GoRouteDataBuildWithKey(Key('above')),
),
],
),
]),
],
),
],
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(
routerConfig: goRouter,
));
expect(find.byKey(const Key('under-shell')), findsNothing);
expect(find.byKey(const Key('under')), findsNothing);
expect(find.byKey(const Key('above-shell')), findsOneWidget);
expect(find.byKey(const Key('above')), findsOneWidget);
goRouter.pop();
await tester.pumpAndSettle();
expect(find.byKey(const Key('under-shell')), findsOneWidget);
expect(find.byKey(const Key('under')), findsOneWidget);
expect(find.byKey(const Key('above-shell')), findsNothing);
expect(find.byKey(const Key('above')), findsNothing);
},
);
testWidgets(
'It should build the page from the overridden buildPage method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/child',
routes: <RouteBase>[
_shellRouteDataPageBuilder,
],
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('builder')), findsNothing);
expect(find.byKey(const Key('page-builder')), findsOneWidget);
},
);
});
group('StatefulShellRouteData', () {
testWidgets(
'It should build the page from the overridden build method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/child',
routes: <RouteBase>[
_statefulShellRouteDataBuilder,
],
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('builder')), findsOneWidget);
expect(find.byKey(const Key('page-builder')), findsNothing);
},
);
testWidgets(
'It should build the page from the overridden buildPage method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/child',
routes: <RouteBase>[
_statefulShellRouteDataPageBuilder,
],
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('builder')), findsNothing);
expect(find.byKey(const Key('page-builder')), findsOneWidget);
},
);
test('Can assign parent navigator key', () {
final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
final StatefulShellRoute route = StatefulShellRouteData.$route(
parentNavigatorKey: key,
factory: (GoRouterState state) =>
const _StatefulShellRouteDataPageBuilder(),
branches: <StatefulShellBranch>[
StatefulShellBranchData.$branch(
routes: <RouteBase>[
GoRouteData.$route(
path: '/child',
factory: (GoRouterState state) => const _GoRouteDataBuild(),
),
],
),
],
);
expect(route.parentNavigatorKey, key);
});
});
testWidgets(
'It should redirect using the overridden redirect method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/redirect',
routes: _routes,
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('build')), findsNothing);
expect(find.byKey(const Key('buildPage')), findsOneWidget);
},
);
testWidgets(
'It should redirect using the overridden redirect method',
(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
initialLocation: '/redirect-with-state',
routes: _routes,
);
addTearDown(goRouter.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter));
expect(find.byKey(const Key('build')), findsNothing);
expect(find.byKey(const Key('buildPage')), findsNothing);
},
);
}
| packages/packages/go_router/test/route_data_test.dart/0 | {
"file_path": "packages/packages/go_router/test/route_data_test.dart",
"repo_id": "packages",
"token_count": 5187
} | 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.
// ignore_for_file: public_member_api_docs, unreachable_from_main
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'shared/data.dart';
part 'simple_example.g.dart';
void main() => runApp(App());
class App extends StatelessWidget {
App({super.key});
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: _appTitle,
);
final GoRouter _router = GoRouter(routes: $appRoutes);
}
@TypedGoRoute<HomeRoute>(
path: '/',
name: 'Home',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<FamilyRoute>(path: 'family/:familyId')
],
)
class HomeRoute extends GoRouteData {
const HomeRoute();
@override
Widget build(BuildContext context, GoRouterState state) => const HomeScreen();
}
class FamilyRoute extends GoRouteData {
const FamilyRoute(this.familyId);
final String familyId;
@override
Widget build(BuildContext context, GoRouterState state) =>
FamilyScreen(family: familyById(familyId));
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(_appTitle)),
body: ListView(
children: <Widget>[
for (final Family family in familyData)
ListTile(
title: Text(family.name),
onTap: () => FamilyRoute(family.id).go(context),
)
],
),
);
}
class FamilyScreen extends StatelessWidget {
const FamilyScreen({required this.family, super.key});
final Family family;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(family.name)),
body: ListView(
children: <Widget>[
for (final Person p in family.people)
ListTile(
title: Text(p.name),
),
],
),
);
}
const String _appTitle = 'GoRouter Example: builder';
| packages/packages/go_router_builder/example/lib/simple_example.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/lib/simple_example.dart",
"repo_id": "packages",
"token_count": 861
} | 1,041 |
// 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:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'route_config.dart';
const String _routeDataUrl = 'package:go_router/src/route_data.dart';
const Map<String, String> _annotations = <String, String>{
'TypedGoRoute': 'GoRouteData',
'TypedShellRoute': 'ShellRouteData',
'TypedStatefulShellBranch': 'StatefulShellBranchData',
'TypedStatefulShellRoute': 'StatefulShellRouteData',
};
/// A [Generator] for classes annotated with a typed go route annotation.
class GoRouterGenerator extends Generator {
/// Creates a new instance of [GoRouterGenerator].
const GoRouterGenerator();
TypeChecker get _typeChecker => TypeChecker.any(
_annotations.keys.map((String annotation) =>
TypeChecker.fromUrl('$_routeDataUrl#$annotation')),
);
@override
FutureOr<String> generate(LibraryReader library, BuildStep buildStep) async {
final Set<String> values = <String>{};
final Set<String> getters = <String>{};
generateForAnnotation(library, values, getters);
if (values.isEmpty) {
return '';
}
return <String>[
'''
List<RouteBase> get \$appRoutes => [
${getters.map((String e) => "$e,").join('\n')}
];
''',
...values,
].join('\n\n');
}
/// Generates code for the `library` based on annotation.
///
/// This public method is for testing purposes and should not be called
/// directly.
void generateForAnnotation(
LibraryReader library,
Set<String> values,
Set<String> getters,
) {
for (final AnnotatedElement annotatedElement
in library.annotatedWith(_typeChecker)) {
final InfoIterable generatedValue = _generateForAnnotatedElement(
annotatedElement.element,
annotatedElement.annotation,
);
getters.add(generatedValue.routeGetterName);
for (final String value in generatedValue) {
assert(value.length == value.trim().length);
values.add(value);
}
}
}
InfoIterable _generateForAnnotatedElement(
Element element,
ConstantReader annotation,
) {
final String typedAnnotation =
annotation.objectValue.type!.getDisplayString(withNullability: false);
final String type =
typedAnnotation.substring(0, typedAnnotation.indexOf('<'));
final String routeData = _annotations[type]!;
if (element is! ClassElement) {
throw InvalidGenerationSourceError(
'The @$type annotation can only be applied to classes.',
element: element,
);
}
final TypeChecker dataChecker =
TypeChecker.fromUrl('$_routeDataUrl#$routeData');
if (!element.allSupertypes
.any((InterfaceType element) => dataChecker.isExactlyType(element))) {
throw InvalidGenerationSourceError(
'The @$type annotation can only be applied to classes that '
'extend or implement `$routeData`.',
element: element,
);
}
return RouteBaseConfig.fromAnnotation(annotation, element)
.generateMembers();
}
}
| packages/packages/go_router_builder/lib/src/go_router_generator.dart/0 | {
"file_path": "packages/packages/go_router_builder/lib/src/go_router_generator.dart",
"repo_id": "packages",
"token_count": 1185
} | 1,042 |
## 0.3.1+1
* Uses `TrustedTypes` from `web: ^0.5.1`.
## 0.3.1
* Updates web code to package `web: ^0.5.0`.
* Updates SDK version to Dart `^3.3.0`. Flutter `^3.19.0`.
## 0.3.0+2
* Adds `fedcm_auto` to `CredentialSelectBy` enum.
* Adds `unknown_reason` to all `Moment*Reason` enums.
## 0.3.0+1
* Corrects 0.3.0 changelog entry about the minimum Flutter/Dart dependencies.
## 0.3.0
* Updates minimum supported SDK version to Flutter 3.16/Dart 3.2.
* Migrates from `package:js`/`dart:html` to `package:web` so this package can
compile to WASM.
* Performs the following **breaking API changes (in bold)** and other fixes to
align with the published GIS SDK:
* **Removes the need to explicitly `allowInterop` in all callbacks.**
* `id`:
* **Changes type:**
* `IdConfiguration.intermediate_iframe_close_callback` to
`VoidFn?`.
* Adds: `fedcm` to `CredentialSelectBy` enum.
* Fixes typo in `storeCredential` `callback` positional parameter name.
* `oauth2`:
* **Removes:**
* `CodeClientConfig.auto_select`, `hint` (now `login_hint`), and `hosted_domain` (now `hd`).
* `TokenClientConfig.hint` (now `login_hint`) and `hosted_domain` (now `hd`).
* `OverridableTokenClientConfig.hint` (now `login_hint`).
* **Changes types:**
* `CodeClientConfig.redirect_uri` to `Uri?`.
* `scope` in `CodeClientConfig` and `CodeResponse` to `List<String>`.
* `CodeResponse.code` and `state` to `String?` (now nullable).
* `scope` in `TokenClientConfig`, `OverridableTokenClientConfig`, and `TokenResponse` to `List<String>`.
* The following `TokenResponse` getters are now nullable: `access_token`,
`expires_in`, `hd`, `prompt`, `token_type`, and `state`.
* The `error_callback` functions now receive a `GoogleIdentityServicesError` parameter, instead of `Object`.
* Adds:
* `include_granted_scopes` and `enable_granular_consent` to `CodeClientConfig`.
* `include_granted_scopes` and `enable_granular_consent` to `TokenClientConfig`.
* `enable_granular_consent` to `OverridableTokenClientConfig`.
* `message` to `GoogleIdentityServicesError`.
* Fixes:
* Assert that `scope` is not empty when used to create `CodeClientConfig`,
`TokenClientConfig`, and `OverridableTokenClientConfig` instances.
* Deprecated `enable_serial_consent`.
## 0.2.2
* Adds the following new fields to `IdConfiguration`:
* `login_hint`, `hd` as auto-select hints for users with multiple accounts/domains.
* `use_fedcm_for_prompt` so FedCM can be enabled.
## 0.2.1+1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.2.1
* Relaxes the `renderButton` API so any JS-Interop Object can be its `target`.
* Exposes the `Button*` configuration enums, so the rendered button can be configured.
## 0.2.0
* Adds `renderButton` API to `id.dart`.
* **Breaking Change:** Makes JS-interop API more `dart2wasm`-friendly.
* Removes external getters for function types
* Introduces an external getter for the whole libraries instead.
* Updates `README.md` with the new way of `import`ing the desired libraries.
## 0.1.1
* Add optional `scope` to `OverridableTokenClientConfig` object.
* Mark some callbacks as optional properly.
## 0.1.0
* Initial release.
| packages/packages/google_identity_services_web/CHANGELOG.md/0 | {
"file_path": "packages/packages/google_identity_services_web/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1202
} | 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.
/// Attempts to retrieve an enum value from [haystack] if [needle] is not null.
T? maybeEnum<T extends Enum>(String? needle, List<T> haystack) {
if (needle == null) {
return null;
}
return haystack.byName(needle);
}
/// The type of several functions from the library, that don't receive
/// parameters nor return anything.
typedef VoidFn = void Function();
/*
// Enum: UX Mode
// https://developers.google.com/identity/gsi/web/reference/js-reference#ux_mode
// Used both by `oauth2.initCodeClient` and `id.initialize`.
*/
/// Use this enum to set the UX flow used by the Sign In With Google button.
/// The default value is [popup].
///
/// This attribute has no impact on the OneTap UX.
enum UxMode {
/// Performs sign-in UX flow in a pop-up window.
popup('popup'),
/// Performs sign-in UX flow by a full page redirection.
redirect('redirect');
///
const UxMode(String uxMode) : _uxMode = uxMode;
final String _uxMode;
@override
String toString() => _uxMode;
}
/// Changes the text of the title and messages in the One Tap prompt.
enum OneTapContext {
/// "Sign in with Google"
signin('signin'),
/// "Sign up with Google"
signup('signup'),
/// "Use with Google"
use('use');
///
const OneTapContext(String context) : _context = context;
final String _context;
@override
String toString() => _context;
}
/// The detailed reason why the OneTap UI isn't displayed.
enum MomentNotDisplayedReason {
/// Browser not supported.
///
/// See https://developers.google.com/identity/gsi/web/guides/supported-browsers
browser_not_supported('browser_not_supported'),
/// Invalid Client.
///
/// See https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid
invalid_client('invalid_client'),
/// Missing client_id.
///
/// See https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid
missing_client_id('missing_client_id'),
/// The user has opted out, or they aren't signed in to a Google account.
///
/// https://developers.google.com/identity/gsi/web/guides/features
opt_out_or_no_session('opt_out_or_no_session'),
/// Google One Tap can only be displayed in HTTPS domains.
///
/// See https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid
secure_http_required('secure_http_required'),
/// The user has previously closed the OneTap card.
///
/// See https://developers.google.com/identity/gsi/web/guides/features#exponential_cooldown
suppressed_by_user('suppressed_by_user'),
/// The current `origin` is not associated with the Client ID.
///
/// See https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid
unregistered_origin('unregistered_origin'),
/// Unknown reason
unknown_reason('unknown_reason');
///
const MomentNotDisplayedReason(String reason) : _reason = reason;
final String _reason;
@override
String toString() => _reason;
}
/// The detailed reason for the skipped moment.
enum MomentSkippedReason {
/// auto_cancel
auto_cancel('auto_cancel'),
/// user_cancel
user_cancel('user_cancel'),
/// tap_outside
tap_outside('tap_outside'),
/// issuing_failed
issuing_failed('issuing_failed'),
/// Unknown reason
unknown_reason('unknown_reason');
///
const MomentSkippedReason(String reason) : _reason = reason;
final String _reason;
@override
String toString() => _reason;
}
/// The detailed reason for the dismissal.
enum MomentDismissedReason {
/// credential_returned
credential_returned('credential_returned'),
/// cancel_called
cancel_called('cancel_called'),
/// flow_restarted
flow_restarted('flow_restarted'),
/// Unknown reason
unknown_reason('unknown_reason');
///
const MomentDismissedReason(String reason) : _reason = reason;
final String _reason;
@override
String toString() => _reason;
}
/// The moment type.
enum MomentType {
/// Display moment
display('display'),
/// Skipped moment
skipped('skipped'),
/// Dismissed moment
dismissed('dismissed');
///
const MomentType(String type) : _type = type;
final String _type;
@override
String toString() => _type;
}
/// Represents how a credential was selected.
enum CredentialSelectBy {
/// Automatic sign-in of a user with an existing session who had previously
/// granted consent to share credentials.
auto('auto'),
/// A user with an existing session who had previously granted consent
/// pressed the One Tap 'Continue as' button to share credentials.
user('user'),
/// A user with an existing session pressed the One Tap 'Continue as' button
/// to grant consent and share credentials. Applies only to Chrome v75 and
/// higher.
user_1tap('user_1tap'),
/// A user without an existing session pressed the One Tap 'Continue as'
/// button to select an account and then pressed the Confirm button in a
/// pop-up window to grant consent and share credentials. Applies to
/// non-Chromium based browsers.
user_2tap('user_2tap'),
/// A user with an existing session who previously granted consent pressed
/// the Sign In With Google button and selected a Google Account from
/// 'Choose an Account' to share credentials.
btn('btn'),
/// A user with an existing session pressed the Sign In With Google button
/// and pressed the Confirm button to grant consent and share credentials.
btn_confirm('btn_confirm'),
/// A user without an existing session who previously granted consent
/// pressed the Sign In With Google button to select a Google Account and
/// share credentials.
btn_add_session('btn_add_session'),
/// A user without an existing session first pressed the Sign In With Google
/// button to select a Google Account and then pressed the Confirm button to
/// consent and share credentials.
btn_confirm_add_session('btn_confirm_add_session'),
/// A user with an existing session used the browser's "FedCM" flow.
fedcm('fedcm'),
/// A fedcm authentication without user intervention.
fedcm_auto('fedcm_auto');
///
const CredentialSelectBy(String selectBy) : _selectBy = selectBy;
final String _selectBy;
@override
String toString() => _selectBy;
}
/// The type of button to be rendered.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#type
enum ButtonType {
/// A button with text or personalized information.
standard('standard'),
/// An icon button without text.
icon('icon');
///
const ButtonType(String type) : _type = type;
final String _type;
@override
String toString() => _type;
}
/// The theme of the button to be rendered.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#theme
enum ButtonTheme {
/// A standard button theme.
outline('outline'),
/// A blue-filled button theme.
filled_blue('filled_blue'),
/// A black-filled button theme.
filled_black('filled_black');
///
const ButtonTheme(String theme) : _theme = theme;
final String _theme;
@override
String toString() => _theme;
}
/// The theme of the button to be rendered.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#size
enum ButtonSize {
/// A large button (about 40px tall).
large('large'),
/// A medium-sized button (about 32px tall).
medium('medium'),
/// A small button (about 20px tall).
small('small');
///
const ButtonSize(String size) : _size = size;
final String _size;
@override
String toString() => _size;
}
/// The button text.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#text
enum ButtonText {
/// The button text is "Sign in with Google".
signin_with('signin_with'),
/// The button text is "Sign up with Google".
signup_with('signup_with'),
/// The button text is "Continue with Google".
continue_with('continue_with'),
/// The button text is "Sign in".
signin('signin');
///
const ButtonText(String text) : _text = text;
final String _text;
@override
String toString() => _text;
}
/// The button shape.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#shape
enum ButtonShape {
/// The rectangular-shaped button.
///
/// If used for the [ButtonType.icon], then it's the same as [square].
rectangular('rectangular'),
/// The pill-shaped button.
///
/// If used for the [ButtonType.icon], then it's the same as [circle].
pill('pill'),
/// The circle-shaped button.
///
/// If used for the [ButtonType.standard], then it's the same as [pill].
circle('circle'),
/// The square-shaped button.
///
/// If used for the [ButtonType.standard], then it's the same as [rectangular].
square('square');
///
const ButtonShape(String shape) : _shape = shape;
final String _shape;
@override
String toString() => _shape;
}
/// The type of button to be rendered.
///
/// https://developers.google.com/identity/gsi/web/reference/js-reference#type
enum ButtonLogoAlignment {
/// Left-aligns the Google logo.
left('left'),
/// Center-aligns the Google logo.
center('center');
///
const ButtonLogoAlignment(String alignment) : _alignment = alignment;
final String _alignment;
@override
String toString() => _alignment;
}
/// The `type` of the error object passed into the `error_callback` function.
enum GoogleIdentityServicesErrorType {
/// Missing required parameter.
missing_required_parameter('missing_required_parameter'),
/// The popup was closed before the flow was completed.
popup_closed('popup_closed'),
/// Popup failed to open.
popup_failed_to_open('popup_failed_to_open'),
/// Unknown error.
unknown('unknown');
///
const GoogleIdentityServicesErrorType(String type) : _type = type;
final String _type;
@override
String toString() => _type;
}
| packages/packages/google_identity_services_web/lib/src/js_interop/shared.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/lib/src/js_interop/shared.dart",
"repo_id": "packages",
"token_count": 2994
} | 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.
package io.flutter.plugins.googlemaps;
import com.google.android.gms.maps.model.LatLng;
/** Receiver of Circle configuration options. */
interface CircleOptionsSink {
void setConsumeTapEvents(boolean consumetapEvents);
void setStrokeColor(int strokeColor);
void setFillColor(int fillColor);
void setCenter(LatLng center);
void setRadius(double radius);
void setVisible(boolean visible);
void setStrokeWidth(float strokeWidth);
void setZIndex(float zIndex);
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleOptionsSink.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleOptionsSink.java",
"repo_id": "packages",
"token_count": 189
} | 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.
package io.flutter.plugins.googlemaps;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import java.util.List;
/** Controller of a single Polygon on the map. */
class PolygonController implements PolygonOptionsSink {
private final Polygon polygon;
private final String googleMapsPolygonId;
private final float density;
private boolean consumeTapEvents;
PolygonController(Polygon polygon, boolean consumeTapEvents, float density) {
this.polygon = polygon;
this.density = density;
this.consumeTapEvents = consumeTapEvents;
this.googleMapsPolygonId = polygon.getId();
}
void remove() {
polygon.remove();
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
polygon.setClickable(consumeTapEvents);
}
@Override
public void setFillColor(int color) {
polygon.setFillColor(color);
}
@Override
public void setStrokeColor(int color) {
polygon.setStrokeColor(color);
}
@Override
public void setGeodesic(boolean geodesic) {
polygon.setGeodesic(geodesic);
}
@Override
public void setPoints(List<LatLng> points) {
polygon.setPoints(points);
}
public void setHoles(List<List<LatLng>> holes) {
polygon.setHoles(holes);
}
@Override
public void setVisible(boolean visible) {
polygon.setVisible(visible);
}
@Override
public void setStrokeWidth(float width) {
polygon.setStrokeWidth(width * density);
}
@Override
public void setZIndex(float zIndex) {
polygon.setZIndex(zIndex);
}
String getGoogleMapsPolygonId() {
return googleMapsPolygonId;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonController.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonController.java",
"repo_id": "packages",
"token_count": 641
} | 1,046 |
// 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 org.mockito.Mockito.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.Context;
import android.os.Build;
import androidx.test.core.app.ApplicationProvider;
import com.google.android.gms.maps.MapsInitializer.Renderer;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.P)
public class GoogleMapInitializerTest {
private GoogleMapInitializer googleMapInitializer;
@Mock BinaryMessenger mockMessenger;
@Before
public void before() {
MockitoAnnotations.openMocks(this);
Context context = ApplicationProvider.getApplicationContext();
googleMapInitializer = spy(new GoogleMapInitializer(context, mockMessenger));
}
@Test
public void initializer_OnMapsSdkInitializedWithLatestRenderer() {
doNothing().when(googleMapInitializer).initializeWithRendererRequest(Renderer.LATEST);
MethodChannel.Result result = mock(MethodChannel.Result.class);
googleMapInitializer.onMethodCall(
new MethodCall(
"initializer#preferRenderer",
new HashMap<String, Object>() {
{
put("value", "latest");
}
}),
result);
googleMapInitializer.onMapsSdkInitialized(Renderer.LATEST);
verify(result, times(1)).success("latest");
verify(result, never()).error(any(), any(), any());
}
@Test
public void initializer_OnMapsSdkInitializedWithLegacyRenderer() {
doNothing().when(googleMapInitializer).initializeWithRendererRequest(Renderer.LEGACY);
MethodChannel.Result result = mock(MethodChannel.Result.class);
googleMapInitializer.onMethodCall(
new MethodCall(
"initializer#preferRenderer",
new HashMap<String, Object>() {
{
put("value", "legacy");
}
}),
result);
googleMapInitializer.onMapsSdkInitialized(Renderer.LEGACY);
verify(result, times(1)).success("legacy");
verify(result, never()).error(any(), any(), any());
}
@Test
public void initializer_onMethodCallWithUnknownRenderer() {
doNothing().when(googleMapInitializer).initializeWithRendererRequest(Renderer.LEGACY);
MethodChannel.Result result = mock(MethodChannel.Result.class);
googleMapInitializer.onMethodCall(
new MethodCall(
"initializer#preferRenderer",
new HashMap<String, Object>() {
{
put("value", "wrong_renderer");
}
}),
result);
verify(result, never()).success(any());
verify(result, times(1)).error(eq("Invalid renderer type"), any(), any());
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapInitializerTest.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapInitializerTest.java",
"repo_id": "packages",
"token_count": 1325
} | 1,047 |
// 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/material.dart';
abstract class GoogleMapExampleAppPage extends StatelessWidget {
const GoogleMapExampleAppPage(this.leading, this.title, {super.key});
final Widget leading;
final String title;
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/page.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/page.dart",
"repo_id": "packages",
"token_count": 123
} | 1,048 |
name: google_maps_flutter_android
description: Android implementation of the google_maps_flutter plugin.
repository: https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 2.7.0
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: google_maps_flutter
platforms:
android:
package: io.flutter.plugins.googlemaps
pluginClass: GoogleMapsPlugin
dartPluginClass: GoogleMapsFlutterAndroid
dependencies:
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter_platform_interface: ^2.5.0
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.1.7
topics:
- google-maps
- google-maps-flutter
- map
| packages/packages/google_maps_flutter/google_maps_flutter_android/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 372
} | 1,049 |
// 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_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:maps_example_dart/example_google_map.dart';
import 'fake_google_maps_flutter_platform.dart';
Widget _mapWithObjects({
Set<Circle> circles = const <Circle>{},
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
}) {
return Directionality(
textDirection: TextDirection.ltr,
child: ExampleGoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
circles: circles,
markers: markers,
polygons: polygons,
polylines: polylines,
tileOverlays: tileOverlays,
),
);
}
void main() {
late FakeGoogleMapsFlutterPlatform platform;
setUp(() {
platform = FakeGoogleMapsFlutterPlatform();
GoogleMapsFlutterPlatform.instance = platform;
});
testWidgets('circle updates with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
const Circle c3 = Circle(circleId: CircleId('circle_3'), radius: 1);
const Circle c3updated = Circle(circleId: CircleId('circle_3'), radius: 10);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithObjects(circles: <Circle>{c1, c2}));
await tester.pumpWidget(_mapWithObjects(circles: <Circle>{c1, c3}));
await tester.pumpWidget(_mapWithObjects(circles: <Circle>{c1, c3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.length, 3);
expect(map.circleUpdates[0].circlesToChange.isEmpty, true);
expect(map.circleUpdates[0].circlesToAdd, <Circle>{c1, c2});
expect(map.circleUpdates[0].circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates[1].circlesToChange.isEmpty, true);
expect(map.circleUpdates[1].circlesToAdd, <Circle>{c3});
expect(map.circleUpdates[1].circleIdsToRemove, <CircleId>{c2.circleId});
expect(map.circleUpdates[2].circlesToChange, <Circle>{c3updated});
expect(map.circleUpdates[2].circlesToAdd.isEmpty, true);
expect(map.circleUpdates[2].circleIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
testWidgets('marker updates with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
const Marker m2 = Marker(markerId: MarkerId('marker_2'));
const Marker m3 = Marker(markerId: MarkerId('marker_3'));
const Marker m3updated =
Marker(markerId: MarkerId('marker_3'), draggable: true);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithObjects(markers: <Marker>{m1, m2}));
await tester.pumpWidget(_mapWithObjects(markers: <Marker>{m1, m3}));
await tester.pumpWidget(_mapWithObjects(markers: <Marker>{m1, m3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.markerUpdates.length, 3);
expect(map.markerUpdates[0].markersToChange.isEmpty, true);
expect(map.markerUpdates[0].markersToAdd, <Marker>{m1, m2});
expect(map.markerUpdates[0].markerIdsToRemove.isEmpty, true);
expect(map.markerUpdates[1].markersToChange.isEmpty, true);
expect(map.markerUpdates[1].markersToAdd, <Marker>{m3});
expect(map.markerUpdates[1].markerIdsToRemove, <MarkerId>{m2.markerId});
expect(map.markerUpdates[2].markersToChange, <Marker>{m3updated});
expect(map.markerUpdates[2].markersToAdd.isEmpty, true);
expect(map.markerUpdates[2].markerIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
testWidgets('polygon updates with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
const Polygon p3 =
Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1);
const Polygon p3updated =
Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithObjects(polygons: <Polygon>{p1, p2}));
await tester.pumpWidget(_mapWithObjects(polygons: <Polygon>{p1, p3}));
await tester
.pumpWidget(_mapWithObjects(polygons: <Polygon>{p1, p3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.length, 3);
expect(map.polygonUpdates[0].polygonsToChange.isEmpty, true);
expect(map.polygonUpdates[0].polygonsToAdd, <Polygon>{p1, p2});
expect(map.polygonUpdates[0].polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates[1].polygonsToChange.isEmpty, true);
expect(map.polygonUpdates[1].polygonsToAdd, <Polygon>{p3});
expect(map.polygonUpdates[1].polygonIdsToRemove, <PolygonId>{p2.polygonId});
expect(map.polygonUpdates[2].polygonsToChange, <Polygon>{p3updated});
expect(map.polygonUpdates[2].polygonsToAdd.isEmpty, true);
expect(map.polygonUpdates[2].polygonIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
testWidgets('polyline updates with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2'));
const Polyline p3 =
Polyline(polylineId: PolylineId('polyline_3'), width: 1);
const Polyline p3updated =
Polyline(polylineId: PolylineId('polyline_3'), width: 2);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithObjects(polylines: <Polyline>{p1, p2}));
await tester.pumpWidget(_mapWithObjects(polylines: <Polyline>{p1, p3}));
await tester
.pumpWidget(_mapWithObjects(polylines: <Polyline>{p1, p3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.length, 3);
expect(map.polylineUpdates[0].polylinesToChange.isEmpty, true);
expect(map.polylineUpdates[0].polylinesToAdd, <Polyline>{p1, p2});
expect(map.polylineUpdates[0].polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true);
expect(map.polylineUpdates[1].polylinesToAdd, <Polyline>{p3});
expect(map.polylineUpdates[1].polylineIdsToRemove,
<PolylineId>{p2.polylineId});
expect(map.polylineUpdates[2].polylinesToChange, <Polyline>{p3updated});
expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true);
expect(map.polylineUpdates[2].polylineIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/test/example_google_map_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/test/example_google_map_test.dart",
"repo_id": "packages",
"token_count": 2755
} | 1,050 |
// 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 polygon controllable by Flutter.
@interface FLTGoogleMapPolygonController : NSObject
- (instancetype)initPolygonWithPath:(GMSMutablePath *)path
identifier:(NSString *)identifier
mapView:(GMSMapView *)mapView;
- (void)removePolygon;
@end
@interface FLTPolygonsController : NSObject
- (instancetype)init:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
- (void)addPolygons:(NSArray *)polygonsToAdd;
- (void)changePolygons:(NSArray *)polygonsToChange;
- (void)removePolygonWithIdentifiers:(NSArray *)identifiers;
- (void)didTapPolygonWithIdentifier:(NSString *)identifier;
- (bool)hasPolygonWithIdentifier:(NSString *)identifier;
@end
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolygonController.h/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolygonController.h",
"repo_id": "packages",
"token_count": 375
} | 1,051 |
# google_maps_flutter_platform_interface
A common platform interface for the [`google_maps_flutter`][1] plugin.
This interface allows platform-specific implementations of the `google_maps_flutter`
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.
# Usage
To implement a new platform-specific implementation of `google_maps_flutter`, extend
[`GoogleMapsFlutterPlatform`][2] with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the default
`GoogleMapsFlutterPlatform` by calling
`GoogleMapsFlutterPlatform.instance = MyPlatformGoogleMapsFlutter()`.
# Note on breaking changes
Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.
See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less-clean interface is preferable to a breaking change.
[1]: ../google_maps_flutter
[2]: lib/google_maps_flutter_platform_interface.dart
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/README.md/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/README.md",
"repo_id": "packages",
"token_count": 262
} | 1,052 |
// 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 immutable, objectRuntimeType, visibleForTesting;
/// A pair of latitude and longitude coordinates, stored as degrees.
@immutable
class LatLng {
/// Creates a geographical location specified in degrees [latitude] and
/// [longitude].
///
/// The latitude is clamped to the inclusive interval from -90.0 to +90.0.
///
/// The longitude is normalized to the half-open interval from -180.0
/// (inclusive) to +180.0 (exclusive).
const LatLng(double latitude, double longitude)
: latitude =
latitude < -90.0 ? -90.0 : (90.0 < latitude ? 90.0 : latitude),
// Avoids normalization if possible to prevent unnecessary loss of precision
longitude = longitude >= -180 && longitude < 180
? longitude
: (longitude + 180.0) % 360.0 - 180.0;
/// The latitude in degrees between -90.0 and 90.0, both inclusive.
final double latitude;
/// The longitude in degrees between -180.0 (inclusive) and 180.0 (exclusive).
final double longitude;
/// Converts this object to something serializable in JSON.
Object toJson() {
return <double>[latitude, longitude];
}
/// Initialize a LatLng from an \[lat, lng\] array.
static LatLng? fromJson(Object? json) {
if (json == null) {
return null;
}
assert(json is List && json.length == 2);
final List<Object?> list = json as List<Object?>;
return LatLng(list[0]! as double, list[1]! as double);
}
@override
String toString() =>
'${objectRuntimeType(this, 'LatLng')}($latitude, $longitude)';
@override
bool operator ==(Object other) {
return other is LatLng &&
other.latitude == latitude &&
other.longitude == longitude;
}
@override
int get hashCode => Object.hash(latitude, longitude);
}
/// A latitude/longitude aligned rectangle.
///
/// The rectangle conceptually includes all points (lat, lng) where
/// * lat ∈ [`southwest.latitude`, `northeast.latitude`]
/// * lng ∈ [`southwest.longitude`, `northeast.longitude`],
/// if `southwest.longitude` ≤ `northeast.longitude`,
/// * lng ∈ [-180, `northeast.longitude`] ∪ [`southwest.longitude`, 180],
/// if `northeast.longitude` < `southwest.longitude`
@immutable
class LatLngBounds {
/// Creates geographical bounding box with the specified corners.
///
/// The latitude of the southwest corner cannot be larger than the
/// latitude of the northeast corner.
LatLngBounds({required this.southwest, required this.northeast})
: assert(southwest.latitude <= northeast.latitude);
/// The southwest corner of the rectangle.
final LatLng southwest;
/// The northeast corner of the rectangle.
final LatLng northeast;
/// Converts this object to something serializable in JSON.
Object toJson() {
return <Object>[southwest.toJson(), northeast.toJson()];
}
/// Returns whether this rectangle contains the given [LatLng].
bool contains(LatLng point) {
return _containsLatitude(point.latitude) &&
_containsLongitude(point.longitude);
}
bool _containsLatitude(double lat) {
return (southwest.latitude <= lat) && (lat <= northeast.latitude);
}
bool _containsLongitude(double lng) {
if (southwest.longitude <= northeast.longitude) {
return southwest.longitude <= lng && lng <= northeast.longitude;
} else {
return southwest.longitude <= lng || lng <= northeast.longitude;
}
}
/// Converts a list to [LatLngBounds].
@visibleForTesting
static LatLngBounds? fromList(Object? json) {
if (json == null) {
return null;
}
assert(json is List && json.length == 2);
final List<Object?> list = json as List<Object?>;
return LatLngBounds(
southwest: LatLng.fromJson(list[0])!,
northeast: LatLng.fromJson(list[1])!,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'LatLngBounds')}($southwest, $northeast)';
}
@override
bool operator ==(Object other) {
return other is LatLngBounds &&
other.southwest == southwest &&
other.northeast == northeast;
}
@override
int get hashCode => Object.hash(southwest, northeast);
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart",
"repo_id": "packages",
"token_count": 1489
} | 1,053 |
// 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 'types.dart';
/// Update specification for a set of [TileOverlay]s.
class TileOverlayUpdates extends MapsObjectUpdates<TileOverlay> {
/// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s.
TileOverlayUpdates.from(super.previous, super.current)
: super.from(objectName: 'tileOverlay');
/// Set of TileOverlays to be added in this update.
Set<TileOverlay> get tileOverlaysToAdd => objectsToAdd;
/// Set of TileOverlayIds to be removed in this update.
Set<TileOverlayId> get tileOverlayIdsToRemove =>
objectIdsToRemove.cast<TileOverlayId>();
/// Set of TileOverlays to be changed in this update.
Set<TileOverlay> get tileOverlaysToChange => objectsToChange;
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart",
"repo_id": "packages",
"token_count": 274
} | 1,054 |
// 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';
import 'package:mockito/mockito.dart';
void main() {
// Store the initial instance before any tests change it.
final GoogleMapsInspectorPlatform? initialInstance =
GoogleMapsInspectorPlatform.instance;
test('default instance is null', () {
expect(initialInstance, isNull);
});
test('cannot be implemented with `implements`', () {
expect(() {
GoogleMapsInspectorPlatform.instance =
ImplementsGoogleMapsInspectorPlatform();
}, throwsA(isInstanceOf<AssertionError>()));
});
test('can be implement with `extends`', () {
GoogleMapsInspectorPlatform.instance = ExtendsGoogleMapsInspectorPlatform();
});
}
class ImplementsGoogleMapsInspectorPlatform extends Mock
implements GoogleMapsInspectorPlatform {}
class ExtendsGoogleMapsInspectorPlatform extends GoogleMapsInspectorPlatform {}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart",
"repo_id": "packages",
"token_count": 348
} | 1,055 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(srujzs): Needed for https://github.com/dart-lang/sdk/issues/54801. Once
// we publish a version with a min SDK constraint that contains this fix,
// remove.
@JS()
library;
import 'dart:js_interop';
/// The interop type for a Google Maps Map Styler.
///
/// See: https://developers.google.com/maps/documentation/javascript/style-reference#stylers
@JS()
extension type MapStyler._(JSObject _) implements JSObject {
/// Create a new [MapStyler] instance.
external factory MapStyler({
String? hue,
num? lightness,
num? saturation,
num? gamma,
// ignore: non_constant_identifier_names
bool? invert_lightness,
String? visibility,
String? color,
int? weight,
});
/// Create a new [MapStyler] instance from the given [json].
factory MapStyler.fromJson(Map<String, Object?> json) {
return MapStyler(
hue: json['hue'] as String?,
lightness: json['lightness'] as num?,
saturation: json['saturation'] as num?,
gamma: json['gamma'] as num?,
invert_lightness: json['invert_lightness'] as bool?,
visibility: json['visibility'] as String?,
color: json['color'] as String?,
weight: json['weight'] as int?,
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/map_styler.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/map_styler.dart",
"repo_id": "packages",
"token_count": 481
} | 1,056 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This header is available in the Test module. Import via "@import google_sign_in.Test;"
#import <google_sign_in_ios/FLTGoogleSignInPlugin.h>
#import <GoogleSignIn/GoogleSignIn.h>
NS_ASSUME_NONNULL_BEGIN
@class GIDSignIn;
/// Methods exposed for unit testing.
@interface FLTGoogleSignInPlugin ()
// Configuration wrapping Google Cloud Console, Google Apps, OpenID,
// and other initialization metadata.
@property(strong) GIDConfiguration *configuration;
// Permissions requested during at sign in "init" method call
// unioned with scopes requested later with incremental authorization
// "requestScopes" method call.
// The "email" and "profile" base scopes are always implicitly requested.
@property(copy) NSSet<NSString *> *requestedScopes;
// Instance used to manage Google Sign In authentication including
// sign in, sign out, and requesting additional scopes.
@property(strong, readonly) GIDSignIn *signIn;
/// Inject @c FlutterPluginRegistrar for testing.
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar;
/// Inject @c GIDSignIn for testing.
- (instancetype)initWithSignIn:(GIDSignIn *)signIn
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
/// Inject @c GIDSignIn and @c googleServiceProperties for testing.
- (instancetype)initWithSignIn:(GIDSignIn *)signIn
registrar:(NSObject<FlutterPluginRegistrar> *)registrar
googleServiceProperties:(nullable NSDictionary<NSString *, id> *)googleServiceProperties
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
| packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/FLTGoogleSignInPlugin_Test.h/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/FLTGoogleSignInPlugin_Test.h",
"repo_id": "packages",
"token_count": 555
} | 1,057 |
// Mocks generated by Mockito 5.4.4 from annotations
// in google_sign_in_ios/test/google_sign_in_ios_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:google_sign_in_ios/src/messages.g.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// 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
class _FakeUserData_0 extends _i1.SmartFake implements _i2.UserData {
_FakeUserData_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeTokenData_1 extends _i1.SmartFake implements _i2.TokenData {
_FakeTokenData_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [GoogleSignInApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi {
MockGoogleSignInApi() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> init(_i2.InitParams? arg_params) => (super.noSuchMethod(
Invocation.method(
#init,
[arg_params],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<_i2.UserData> signInSilently() => (super.noSuchMethod(
Invocation.method(
#signInSilently,
[],
),
returnValue: _i3.Future<_i2.UserData>.value(_FakeUserData_0(
this,
Invocation.method(
#signInSilently,
[],
),
)),
) as _i3.Future<_i2.UserData>);
@override
_i3.Future<_i2.UserData> signIn() => (super.noSuchMethod(
Invocation.method(
#signIn,
[],
),
returnValue: _i3.Future<_i2.UserData>.value(_FakeUserData_0(
this,
Invocation.method(
#signIn,
[],
),
)),
) as _i3.Future<_i2.UserData>);
@override
_i3.Future<_i2.TokenData> getAccessToken() => (super.noSuchMethod(
Invocation.method(
#getAccessToken,
[],
),
returnValue: _i3.Future<_i2.TokenData>.value(_FakeTokenData_1(
this,
Invocation.method(
#getAccessToken,
[],
),
)),
) as _i3.Future<_i2.TokenData>);
@override
_i3.Future<void> signOut() => (super.noSuchMethod(
Invocation.method(
#signOut,
[],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<void> disconnect() => (super.noSuchMethod(
Invocation.method(
#disconnect,
[],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<bool> isSignedIn() => (super.noSuchMethod(
Invocation.method(
#isSignedIn,
[],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
@override
_i3.Future<bool> requestScopes(List<String?>? arg_scopes) =>
(super.noSuchMethod(
Invocation.method(
#requestScopes,
[arg_scopes],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
}
| packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart",
"repo_id": "packages",
"token_count": 1911
} | 1,058 |
rootProject.name = 'image_picker_android'
| packages/packages/image_picker/image_picker_android/android/settings.gradle/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/settings.gradle",
"repo_id": "packages",
"token_count": 14
} | 1,059 |
// 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.Application;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.imagepicker.Messages.FlutterError;
import io.flutter.plugins.imagepicker.Messages.GeneralOptions;
import io.flutter.plugins.imagepicker.Messages.ImageSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.MediaSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.SourceSpecification;
import io.flutter.plugins.imagepicker.Messages.VideoSelectionOptions;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ImagePickerPluginTest {
private static final ImageSelectionOptions DEFAULT_IMAGE_OPTIONS =
new ImageSelectionOptions.Builder().setQuality((long) 100).build();
private static final VideoSelectionOptions DEFAULT_VIDEO_OPTIONS =
new VideoSelectionOptions.Builder().build();
private static final MediaSelectionOptions DEFAULT_MEDIA_OPTIONS =
new MediaSelectionOptions.Builder().setImageSelectionOptions(DEFAULT_IMAGE_OPTIONS).build();
private static final GeneralOptions GENERAL_OPTIONS_ALLOW_MULTIPLE_USE_PHOTO_PICKER =
new GeneralOptions.Builder().setUsePhotoPicker(true).setAllowMultiple(true).build();
private static final GeneralOptions GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_USE_PHOTO_PICKER =
new GeneralOptions.Builder().setUsePhotoPicker(true).setAllowMultiple(false).build();
private static final GeneralOptions GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER =
new GeneralOptions.Builder().setUsePhotoPicker(false).setAllowMultiple(false).build();
private static final GeneralOptions GENERAL_OPTIONS_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER =
new GeneralOptions.Builder().setUsePhotoPicker(false).setAllowMultiple(true).build();
private static final SourceSpecification SOURCE_GALLERY =
new SourceSpecification.Builder().setType(Messages.SourceType.GALLERY).build();
private static final SourceSpecification SOURCE_CAMERA_FRONT =
new SourceSpecification.Builder()
.setType(Messages.SourceType.CAMERA)
.setCamera(Messages.SourceCamera.FRONT)
.build();
private static final SourceSpecification SOURCE_CAMERA_REAR =
new SourceSpecification.Builder()
.setType(Messages.SourceType.CAMERA)
.setCamera(Messages.SourceCamera.REAR)
.build();
@SuppressWarnings("deprecation")
@Mock
io.flutter.plugin.common.PluginRegistry.Registrar mockRegistrar;
@Mock ActivityPluginBinding mockActivityBinding;
@Mock FlutterPluginBinding mockPluginBinding;
@Mock Activity mockActivity;
@Mock Application mockApplication;
@Mock ImagePickerDelegate mockImagePickerDelegate;
@Mock Messages.Result<List<String>> mockResult;
ImagePickerPlugin plugin;
AutoCloseable mockCloseable;
@Before
public void setUp() {
mockCloseable = MockitoAnnotations.openMocks(this);
when(mockRegistrar.context()).thenReturn(mockApplication);
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
when(mockPluginBinding.getApplicationContext()).thenReturn(mockApplication);
plugin = new ImagePickerPlugin(mockImagePickerDelegate, mockActivity);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void pickImages_whenActivityIsNull_finishesWithForegroundActivityRequiredError() {
ImagePickerPlugin imagePickerPluginWithNullActivity =
new ImagePickerPlugin(mockImagePickerDelegate, null);
imagePickerPluginWithNullActivity.pickImages(
SOURCE_GALLERY,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_ALLOW_MULTIPLE_USE_PHOTO_PICKER,
mockResult);
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("no_activity", errorCaptor.getValue().code);
assertEquals(
"image_picker plugin requires a foreground activity.", errorCaptor.getValue().getMessage());
verifyNoInteractions(mockImagePickerDelegate);
}
@Test
public void pickVideos_whenActivityIsNull_finishesWithForegroundActivityRequiredError() {
ImagePickerPlugin imagePickerPluginWithNullActivity =
new ImagePickerPlugin(mockImagePickerDelegate, null);
imagePickerPluginWithNullActivity.pickVideos(
SOURCE_CAMERA_REAR,
DEFAULT_VIDEO_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("no_activity", errorCaptor.getValue().code);
assertEquals(
"image_picker plugin requires a foreground activity.", errorCaptor.getValue().getMessage());
verifyNoInteractions(mockImagePickerDelegate);
}
@Test
public void retrieveLostResults_whenActivityIsNull_finishesWithForegroundActivityRequiredError() {
ImagePickerPlugin imagePickerPluginWithNullActivity =
new ImagePickerPlugin(mockImagePickerDelegate, null);
FlutterError error =
assertThrows(FlutterError.class, imagePickerPluginWithNullActivity::retrieveLostResults);
assertEquals("image_picker plugin requires a foreground activity.", error.getMessage());
assertEquals("no_activity", error.code);
verifyNoInteractions(mockImagePickerDelegate);
}
@Test
public void pickImages_whenSourceIsGallery_invokesChooseImageFromGallery() {
plugin.pickImages(
SOURCE_GALLERY,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).chooseImageFromGallery(any(), eq(false), any());
verifyNoInteractions(mockResult);
}
@Test
public void pickImages_whenSourceIsGalleryUsingPhotoPicker_invokesChooseImageFromGallery() {
plugin.pickImages(
SOURCE_GALLERY,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).chooseImageFromGallery(any(), eq(true), any());
verifyNoInteractions(mockResult);
}
@Test
public void pickImages_invokesChooseMultiImageFromGallery() {
plugin.pickImages(
SOURCE_GALLERY,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).chooseMultiImageFromGallery(any(), eq(false), any());
verifyNoInteractions(mockResult);
}
@Test
public void pickImages_usingPhotoPicker_invokesChooseMultiImageFromGallery() {
plugin.pickImages(
SOURCE_GALLERY,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_ALLOW_MULTIPLE_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).chooseMultiImageFromGallery(any(), eq(true), any());
verifyNoInteractions(mockResult);
}
@Test
public void pickMedia_invokesChooseMediaFromGallery() {
MediaSelectionOptions mediaSelectionOptions =
new MediaSelectionOptions.Builder().setImageSelectionOptions(DEFAULT_IMAGE_OPTIONS).build();
plugin.pickMedia(
mediaSelectionOptions,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate)
.chooseMediaFromGallery(
eq(mediaSelectionOptions),
eq(GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER),
any());
verifyNoInteractions(mockResult);
}
@Test
public void pickMedia_usingPhotoPicker_invokesChooseMediaFromGallery() {
MediaSelectionOptions mediaSelectionOptions =
new MediaSelectionOptions.Builder().setImageSelectionOptions(DEFAULT_IMAGE_OPTIONS).build();
plugin.pickMedia(
mediaSelectionOptions, GENERAL_OPTIONS_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER, mockResult);
verify(mockImagePickerDelegate)
.chooseMediaFromGallery(
eq(mediaSelectionOptions),
eq(GENERAL_OPTIONS_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER),
any());
verifyNoInteractions(mockResult);
}
@Test
public void pickImages_whenSourceIsCamera_invokesTakeImageWithCamera() {
plugin.pickImages(
SOURCE_CAMERA_REAR,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).takeImageWithCamera(any(), any());
verifyNoInteractions(mockResult);
}
@Test
public void pickImages_whenSourceIsCamera_invokesTakeImageWithCamera_RearCamera() {
plugin.pickImages(
SOURCE_CAMERA_REAR,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).setCameraDevice(eq(ImagePickerDelegate.CameraDevice.REAR));
}
@Test
public void pickImages_whenSourceIsCamera_invokesTakeImageWithCamera_FrontCamera() {
plugin.pickImages(
SOURCE_CAMERA_FRONT,
DEFAULT_IMAGE_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).setCameraDevice(eq(ImagePickerDelegate.CameraDevice.FRONT));
}
@Test
public void pickVideos_whenSourceIsCamera_invokesTakeImageWithCamera_RearCamera() {
plugin.pickVideos(
SOURCE_CAMERA_REAR,
DEFAULT_VIDEO_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).setCameraDevice(eq(ImagePickerDelegate.CameraDevice.REAR));
}
@Test
public void pickVideos_whenSourceIsCamera_invokesTakeImageWithCamera_FrontCamera() {
plugin.pickVideos(
SOURCE_CAMERA_FRONT,
DEFAULT_VIDEO_OPTIONS,
GENERAL_OPTIONS_DONT_ALLOW_MULTIPLE_DONT_USE_PHOTO_PICKER,
mockResult);
verify(mockImagePickerDelegate).setCameraDevice(eq(ImagePickerDelegate.CameraDevice.FRONT));
}
@Test
public void onRegister_whenActivityIsNull_shouldNotCrash() {
when(mockRegistrar.activity()).thenReturn(null);
ImagePickerPlugin.registerWith((mockRegistrar));
assertTrue(
"No exception thrown when ImagePickerPlugin.registerWith ran with activity = null", true);
}
@Test
public void onConstructor_whenContextTypeIsActivity_shouldNotCrash() {
new ImagePickerPlugin(mockImagePickerDelegate, mockActivity);
assertTrue(
"No exception thrown when ImagePickerPlugin() ran with context instanceof Activity", true);
}
@Test
public void onDetachedFromActivity_shouldReleaseActivityState() {
final BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class);
when(mockPluginBinding.getBinaryMessenger()).thenReturn(mockBinaryMessenger);
final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class);
when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference);
final Lifecycle mockLifecycle = mock(Lifecycle.class);
when(mockLifecycleReference.getLifecycle()).thenReturn(mockLifecycle);
plugin.onAttachedToEngine(mockPluginBinding);
plugin.onAttachedToActivity(mockActivityBinding);
assertNotNull(plugin.getActivityState());
plugin.onDetachedFromActivity();
assertNull(plugin.getActivityState());
}
}
| packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerPluginTest.java/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerPluginTest.java",
"repo_id": "packages",
"token_count": 4506
} | 1,060 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.imagepickerexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Image Picker Example" android:icon="@mipmap/ic_launcher">
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
</manifest>
| packages/packages/image_picker/image_picker_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 431
} | 1,061 |
// 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:typed_data';
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_for_web/src/image_resizer.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/helpers.dart';
import 'package:web/web.dart' as web;
//This is a sample 10x10 png image
const String pngFileBase64Contents =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKAQMAAAC3/F3+AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABlBMVEXqQzX+/v6lfubTAAAAAWJLR0QB/wIt3gAAAAlwSFlzAAAHEwAABxMBziAPCAAAAAd0SU1FB+UJHgsdDM0ErZoAAAALSURBVAjXY2DABwAAHgABboVHMgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMS0wOS0zMFQxMToyOToxMi0wNDowMHCDC24AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjEtMDktMzBUMTE6Mjk6MTItMDQ6MDAB3rPSAAAAAElFTkSuQmCC';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Under test...
late ImageResizer imageResizer;
late XFile pngFile;
setUp(() {
imageResizer = ImageResizer();
final web.Blob pngHtmlFile = _base64ToBlob(pngFileBase64Contents);
pngFile = XFile(web.URL.createObjectURL(pngHtmlFile),
name: 'pngImage.png', mimeType: 'image/png');
});
testWidgets('image is loaded correctly ', (WidgetTester tester) async {
final web.HTMLImageElement imageElement =
await imageResizer.loadImage(pngFile.path);
expect(imageElement.width, 10);
expect(imageElement.height, 10);
});
testWidgets(
"canvas is loaded with image's width and height when max width and max height are null",
(WidgetTester widgetTester) async {
final web.HTMLImageElement imageElement =
await imageResizer.loadImage(pngFile.path);
final web.HTMLCanvasElement canvas =
imageResizer.resizeImageElement(imageElement, null, null);
expect(canvas.width, imageElement.width);
expect(canvas.height, imageElement.height);
});
testWidgets(
'canvas size is scaled when max width and max height are not null',
(WidgetTester widgetTester) async {
final web.HTMLImageElement imageElement =
await imageResizer.loadImage(pngFile.path);
final web.HTMLCanvasElement canvas =
imageResizer.resizeImageElement(imageElement, 8, 8);
expect(canvas.width, 8);
expect(canvas.height, 8);
});
testWidgets('resized image is returned after converting canvas to file',
(WidgetTester widgetTester) async {
final web.HTMLImageElement imageElement =
await imageResizer.loadImage(pngFile.path);
final web.HTMLCanvasElement canvas =
imageResizer.resizeImageElement(imageElement, null, null);
final XFile resizedImage =
await imageResizer.writeCanvasToFile(pngFile, canvas, null);
expect(resizedImage.name, 'scaled_${pngFile.name}');
});
testWidgets('image is scaled when maxWidth is set',
(WidgetTester tester) async {
final XFile scaledImage =
await imageResizer.resizeImageIfNeeded(pngFile, 5, null, null);
expect(scaledImage.name, 'scaled_${pngFile.name}');
final Size scaledImageSize = await _getImageSize(scaledImage);
expect(scaledImageSize, const Size(5, 5));
});
testWidgets('image is scaled when maxHeight is set',
(WidgetTester tester) async {
final XFile scaledImage =
await imageResizer.resizeImageIfNeeded(pngFile, null, 6, null);
expect(scaledImage.name, 'scaled_${pngFile.name}');
final Size scaledImageSize = await _getImageSize(scaledImage);
expect(scaledImageSize, const Size(6, 6));
});
testWidgets('image is scaled when imageQuality is set',
(WidgetTester tester) async {
final XFile scaledImage =
await imageResizer.resizeImageIfNeeded(pngFile, null, null, 89);
expect(scaledImage.name, 'scaled_${pngFile.name}');
});
testWidgets('image is scaled when maxWidth,maxHeight,imageQuality are set',
(WidgetTester tester) async {
final XFile scaledImage =
await imageResizer.resizeImageIfNeeded(pngFile, 3, 4, 89);
expect(scaledImage.name, 'scaled_${pngFile.name}');
});
testWidgets('image is not scaled when maxWidth,maxHeight, is set',
(WidgetTester tester) async {
final XFile scaledImage =
await imageResizer.resizeImageIfNeeded(pngFile, null, null, null);
expect(scaledImage.name, pngFile.name);
});
}
Future<Size> _getImageSize(XFile file) async {
final Completer<Size> completer = Completer<Size>();
final web.HTMLImageElement image = web.HTMLImageElement();
image
..onLoad.listen((web.Event event) {
completer.complete(Size(image.width.toDouble(), image.height.toDouble()));
})
..onError.listen((web.Event event) {
completer.complete(Size.zero);
})
..src = file.path;
return completer.future;
}
web.Blob _base64ToBlob(String data) {
final List<String> arr = data.split(',');
final String bstr = web.window.atob(arr[1]);
int n = bstr.length;
final Uint8List u8arr = Uint8List(n);
while (n >= 1) {
u8arr[n - 1] = bstr.codeUnitAt(n - 1);
n--;
}
return Blob(<JSUint8Array>[u8arr.toJS].toJS);
}
| packages/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart",
"repo_id": "packages",
"token_count": 2066
} | 1,062 |
# image\_picker\_ios
The iOS implementation of [`image_picker`][1].
## Usage
This package is [endorsed][2], which means you can simply use `image_picker`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
[1]: https://pub.dev/packages/image_picker
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| packages/packages/image_picker/image_picker_ios/README.md/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/README.md",
"repo_id": "packages",
"token_count": 177
} | 1,063 |
// 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
@interface GIFInfo : NSObject
@property(strong, nonatomic, readonly) NSArray<UIImage *> *images;
@property(assign, nonatomic, readonly) NSTimeInterval interval;
- (instancetype)initWithImages:(NSArray<UIImage *> *)images interval:(NSTimeInterval)interval;
@end
@interface FLTImagePickerImageUtil : NSObject
// Resizes the given image to fit within maxWidth (if non-nil) and maxHeight (if non-nil)
+ (UIImage *)scaledImage:(UIImage *)image
maxWidth:(nullable NSNumber *)maxWidth
maxHeight:(nullable NSNumber *)maxHeight
isMetadataAvailable:(BOOL)isMetadataAvailable;
// Resize all gif animation frames.
+ (GIFInfo *)scaledGIFImage:(NSData *)data
maxWidth:(NSNumber *)maxWidth
maxHeight:(NSNumber *)maxHeight;
@end
NS_ASSUME_NONNULL_END
| packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.h/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.h",
"repo_id": "packages",
"token_count": 391
} | 1,064 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'image_picker_ios'
s.version = '0.0.1'
s.summary = 'Flutter plugin that shows an image picker.'
s.description = <<-DESC
A Flutter plugin for picking images from the image library, and taking new pictures with the camera.
Downloaded by pub (not CocoaPods).
DESC
s.homepage = 'https://github.com/flutter/packages'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/image_picker_ios' }
s.documentation_url = 'https://pub.dev/packages/image_picker_ios'
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/ImagePickerPlugin.modulemap'
s.dependency 'Flutter'
s.platform = :ios, '12.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.resource_bundles = {'image_picker_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
| packages/packages/image_picker/image_picker_ios/ios/image_picker_ios.podspec/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/ios/image_picker_ios.podspec",
"repo_id": "packages",
"token_count": 503
} | 1,065 |
// 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:typed_data';
import 'package:http/http.dart' as http show readBytes;
import './base.dart';
/// A PickedFile that works on web.
///
/// It wraps the bytes of a selected file.
class PickedFile extends PickedFileBase {
/// Construct a PickedFile object from its ObjectUrl.
///
/// Optionally, this can be initialized with `bytes`
/// so no http requests are performed to retrieve files later.
const PickedFile(this.path, {Uint8List? bytes})
: _initBytes = bytes,
super(path);
@override
final String path;
final Uint8List? _initBytes;
Future<Uint8List> get _bytes async {
if (_initBytes != null) {
return _initBytes.asUnmodifiableView();
}
return http.readBytes(Uri.parse(path));
}
@override
Future<String> readAsString({Encoding encoding = utf8}) async {
return encoding.decode(await _bytes);
}
@override
Future<Uint8List> readAsBytes() async {
return Future<Uint8List>.value(await _bytes);
}
@override
Stream<Uint8List> openRead([int? start, int? end]) async* {
final Uint8List bytes = await _bytes;
yield bytes.sublist(start ?? 0, end ?? bytes.length);
}
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart",
"repo_id": "packages",
"token_count": 460
} | 1,066 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
// Load the build signing secrets from a local `keystore.properties` file.
// TODO(YOU): Create release keys and a `keystore.properties` file. See
// `example/README.md` for more info and `keystore.example.properties` for an
// example.
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
def configured = true
try {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
} catch (IOException e) {
configured = false
logger.error('Release signing information not found.')
}
project.ext {
// TODO(YOU): Create release keys and a `keystore.properties` file. See
// `example/README.md` for more info and `keystore.example.properties` for an
// example.
APP_ID = configured ? keystoreProperties['appId'] : "io.flutter.plugins.inapppurchaseexample.DEFAULT_DO_NOT_USE"
KEYSTORE_STORE_FILE = configured ? rootProject.file(keystoreProperties['storeFile']) : null
KEYSTORE_STORE_PASSWORD = keystoreProperties['storePassword']
KEYSTORE_KEY_ALIAS = keystoreProperties['keyAlias']
KEYSTORE_KEY_PASSWORD = keystoreProperties['keyPassword']
VERSION_CODE = configured ? keystoreProperties['versionCode'].toInteger() : 1
VERSION_NAME = configured ? keystoreProperties['versionName'] : "0.0.1"
}
if (project.APP_ID == "io.flutter.plugins.inapppurchaseexample.DEFAULT_DO_NOT_USE") {
configured = false
logger.error('Unique package name not set, defaulting to "io.flutter.plugins.inapppurchaseexample.DEFAULT_DO_NOT_USE".')
}
// Log a final error message if we're unable to create a release key signed
// build for an app configured in the Play Developer Console. Apks built in this
// condition won't be able to call any of the BillingClient APIs.
if (!configured) {
logger.error('The app could not be configured for release signing. In app purchases will not be testable. See `example/README.md` for more info and instructions.')
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
namespace 'io.flutter.plugins.inapppurchaseexample'
signingConfigs {
release {
storeFile project.KEYSTORE_STORE_FILE
storePassword project.KEYSTORE_STORE_PASSWORD
keyAlias project.KEYSTORE_KEY_ALIAS
keyPassword project.KEYSTORE_KEY_PASSWORD
}
}
compileSdk flutter.compileSdkVersion
defaultConfig {
applicationId project.APP_ID
minSdkVersion flutter.minSdkVersion
targetSdkVersion 28
versionCode project.VERSION_CODE
versionName project.VERSION_NAME
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
// Google Play Billing APIs only work with apps signed for production.
debug {
if (configured) {
signingConfig signingConfigs.release
} else {
signingConfig signingConfigs.debug
}
}
release {
if (configured) {
signingConfig signingConfigs.release
} else {
signingConfig signingConfigs.debug
}
}
}
testOptions {
unitTests.returnDefaultValues = true
}
lint {
disable 'InvalidPackage'
}
}
flutter {
source '../..'
}
dependencies {
implementation 'com.android.billingclient:billing:3.0.2'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.0.0'
testImplementation 'org.json:json:20240303'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
| packages/packages/in_app_purchase/in_app_purchase/example/android/app/build.gradle/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase/example/android/app/build.gradle",
"repo_id": "packages",
"token_count": 1544
} | 1,067 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.ACTIVITY_UNAVAILABLE;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.ACKNOWLEDGE_PURCHASE;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.CONSUME_PURCHASE_ASYNC;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.END_CONNECTION;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.GET_BILLING_CONFIG;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.IS_FEATURE_SUPPORTED;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.IS_READY;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.LAUNCH_BILLING_FLOW;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.ON_DISCONNECT;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.QUERY_PRODUCT_DETAILS;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.QUERY_PURCHASES_ASYNC;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.QUERY_PURCHASE_HISTORY_ASYNC;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.START_CONNECTION;
import static io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodNames.USER_SELECTED_ALTERNATIVE_BILLING;
import static io.flutter.plugins.inapppurchase.PluginPurchaseListener.ON_PURCHASES_UPDATED;
import static io.flutter.plugins.inapppurchase.Translator.fromAlternativeBillingOnlyReportingDetails;
import static io.flutter.plugins.inapppurchase.Translator.fromBillingConfig;
import static io.flutter.plugins.inapppurchase.Translator.fromBillingResult;
import static io.flutter.plugins.inapppurchase.Translator.fromProductDetailsList;
import static io.flutter.plugins.inapppurchase.Translator.fromPurchaseHistoryRecordList;
import static io.flutter.plugins.inapppurchase.Translator.fromPurchasesList;
import static io.flutter.plugins.inapppurchase.Translator.fromUserChoiceDetails;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.refEq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
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.app.Activity;
import android.content.Context;
import androidx.annotation.Nullable;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.AlternativeBillingOnlyAvailabilityListener;
import com.android.billingclient.api.AlternativeBillingOnlyInformationDialogListener;
import com.android.billingclient.api.AlternativeBillingOnlyReportingDetails;
import com.android.billingclient.api.AlternativeBillingOnlyReportingDetailsListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.BillingResponseCode;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingConfig;
import com.android.billingclient.api.BillingConfigResponseListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.GetBillingConfigParams;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.ProductDetailsResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryPurchaseHistoryParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.android.billingclient.api.UserChoiceBillingListener;
import com.android.billingclient.api.UserChoiceDetails;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.BillingChoiceMode;
import io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.MethodArgs;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.stubbing.Answer;
public class MethodCallHandlerTest {
private MethodCallHandlerImpl methodChannelHandler;
@Mock BillingClientFactory factory;
@Mock BillingClient mockBillingClient;
@Mock MethodChannel mockMethodChannel;
@Spy Result result;
@Mock Activity activity;
@Mock Context context;
@Mock ActivityPluginBinding mockActivityPluginBinding;
@Captor ArgumentCaptor<HashMap<String, Object>> resultCaptor;
private final int DEFAULT_HANDLE = 1;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
// Use the same client no matter if alternative billing is enabled or not.
when(factory.createBillingClient(
context, mockMethodChannel, BillingChoiceMode.PLAY_BILLING_ONLY, null))
.thenReturn(mockBillingClient);
when(factory.createBillingClient(
context, mockMethodChannel, BillingChoiceMode.ALTERNATIVE_BILLING_ONLY, null))
.thenReturn(mockBillingClient);
when(factory.createBillingClient(
any(Context.class),
any(MethodChannel.class),
eq(BillingChoiceMode.USER_CHOICE_BILLING),
any(UserChoiceBillingListener.class)))
.thenReturn(mockBillingClient);
methodChannelHandler = new MethodCallHandlerImpl(activity, context, mockMethodChannel, factory);
when(mockActivityPluginBinding.getActivity()).thenReturn(activity);
}
@Test
public void invalidMethod() {
MethodCall call = new MethodCall("invalid", null);
methodChannelHandler.onMethodCall(call, result);
verify(result, times(1)).notImplemented();
}
@Test
public void isReady_true() {
mockStartConnection();
MethodCall call = new MethodCall(IS_READY, null);
when(mockBillingClient.isReady()).thenReturn(true);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(true);
}
@Test
public void isReady_false() {
mockStartConnection();
MethodCall call = new MethodCall(IS_READY, null);
when(mockBillingClient.isReady()).thenReturn(false);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(false);
}
@Test
public void isReady_clientDisconnected() {
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
MethodCall isReadyCall = new MethodCall(IS_READY, null);
methodChannelHandler.onMethodCall(isReadyCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void startConnection() {
ArgumentCaptor<BillingClientStateListener> captor =
mockStartConnection(BillingChoiceMode.PLAY_BILLING_ONLY);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(context, mockMethodChannel, BillingChoiceMode.PLAY_BILLING_ONLY, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void startConnectionAlternativeBillingOnly() {
ArgumentCaptor<BillingClientStateListener> captor =
mockStartConnection(BillingChoiceMode.ALTERNATIVE_BILLING_ONLY);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(
context, mockMethodChannel, BillingChoiceMode.ALTERNATIVE_BILLING_ONLY, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void startConnectionAlternativeBillingUnset() {
// Logic is identical to mockStartConnection but does not set a value for
// ENABLE_ALTERNATIVE_BILLING to verify fallback behavior.
Map<String, Object> arguments = new HashMap<>();
arguments.put(MethodArgs.HANDLE, 1);
MethodCall call = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(call, result);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(context, mockMethodChannel, BillingChoiceMode.PLAY_BILLING_ONLY, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void startConnectionUserChoiceBilling() {
ArgumentCaptor<BillingClientStateListener> captor =
mockStartConnection(BillingChoiceMode.USER_CHOICE_BILLING);
ArgumentCaptor<UserChoiceBillingListener> billingCaptor =
ArgumentCaptor.forClass(UserChoiceBillingListener.class);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(
any(Context.class),
any(MethodChannel.class),
eq(BillingChoiceMode.USER_CHOICE_BILLING),
billingCaptor.capture());
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
UserChoiceDetails details = mock(UserChoiceDetails.class);
final String externalTransactionToken = "someLongTokenId1234";
final String originalTransactionId = "originalTransactionId123456";
when(details.getExternalTransactionToken()).thenReturn(externalTransactionToken);
when(details.getOriginalExternalTransactionId()).thenReturn(originalTransactionId);
when(details.getProducts()).thenReturn(Collections.emptyList());
billingCaptor.getValue().userSelectedAlternativeBilling(details);
verify(mockMethodChannel, times(1))
.invokeMethod(USER_SELECTED_ALTERNATIVE_BILLING, fromUserChoiceDetails(details));
}
@Test
public void userChoiceBillingOnSecondConnection() {
// First connection.
ArgumentCaptor<BillingClientStateListener> captor1 =
mockStartConnection(BillingChoiceMode.PLAY_BILLING_ONLY);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(context, mockMethodChannel, BillingChoiceMode.PLAY_BILLING_ONLY, null);
BillingResult billingResult1 =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
final BillingClientStateListener stateListener = captor1.getValue();
stateListener.onBillingSetupFinished(billingResult1);
verify(result, times(1)).success(fromBillingResult(billingResult1));
Mockito.reset(result, mockMethodChannel, mockBillingClient);
// Disconnect
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, result);
// Verify that the client is disconnected and that the OnDisconnect callback has
// been triggered
verify(result, times(1)).success(any());
verify(mockBillingClient, times(1)).endConnection();
stateListener.onBillingServiceDisconnected();
Map<String, Integer> expectedInvocation = new HashMap<>();
expectedInvocation.put("handle", DEFAULT_HANDLE);
verify(mockMethodChannel, times(1)).invokeMethod(ON_DISCONNECT, expectedInvocation);
Mockito.reset(result, mockMethodChannel, mockBillingClient);
// Second connection.
ArgumentCaptor<BillingClientStateListener> captor2 =
mockStartConnection(BillingChoiceMode.USER_CHOICE_BILLING);
ArgumentCaptor<UserChoiceBillingListener> billingCaptor =
ArgumentCaptor.forClass(UserChoiceBillingListener.class);
verify(result, never()).success(any());
verify(factory, times(1))
.createBillingClient(
any(Context.class),
any(MethodChannel.class),
eq(BillingChoiceMode.USER_CHOICE_BILLING),
billingCaptor.capture());
BillingResult billingResult2 =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor2.getValue().onBillingSetupFinished(billingResult2);
verify(result, times(1)).success(fromBillingResult(billingResult2));
UserChoiceDetails details = mock(UserChoiceDetails.class);
final String externalTransactionToken = "someLongTokenId1234";
final String originalTransactionId = "originalTransactionId123456";
when(details.getExternalTransactionToken()).thenReturn(externalTransactionToken);
when(details.getOriginalExternalTransactionId()).thenReturn(originalTransactionId);
when(details.getProducts()).thenReturn(Collections.emptyList());
billingCaptor.getValue().userSelectedAlternativeBilling(details);
verify(mockMethodChannel, times(1))
.invokeMethod(USER_SELECTED_ALTERNATIVE_BILLING, fromUserChoiceDetails(details));
}
@Test
public void startConnection_multipleCalls() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", 1);
MethodCall call = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(call, result);
verify(result, never()).success(any());
BillingResult billingResult1 =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
BillingResult billingResult2 =
BillingResult.newBuilder()
.setResponseCode(200)
.setDebugMessage("dummy debug message")
.build();
BillingResult billingResult3 =
BillingResult.newBuilder()
.setResponseCode(300)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult1);
captor.getValue().onBillingSetupFinished(billingResult2);
captor.getValue().onBillingSetupFinished(billingResult3);
verify(result, times(1)).success(fromBillingResult(billingResult1));
verify(result, times(1)).success(any());
}
@Test
public void getBillingConfigSuccess() {
mockStartConnection();
ArgumentCaptor<GetBillingConfigParams> paramsCaptor =
ArgumentCaptor.forClass(GetBillingConfigParams.class);
ArgumentCaptor<BillingConfigResponseListener> listenerCaptor =
ArgumentCaptor.forClass(BillingConfigResponseListener.class);
MethodCall billingCall = new MethodCall(GET_BILLING_CONFIG, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
final String expectedCountryCode = "US";
final BillingConfig expectedConfig = mock(BillingConfig.class);
when(expectedConfig.getCountryCode()).thenReturn(expectedCountryCode);
doNothing()
.when(mockBillingClient)
.getBillingConfigAsync(paramsCaptor.capture(), listenerCaptor.capture());
methodChannelHandler.onMethodCall(billingCall, result);
listenerCaptor.getValue().onBillingConfigResponse(billingResult, expectedConfig);
verify(result, times(1)).success(fromBillingConfig(billingResult, expectedConfig));
}
@Test
public void getBillingConfig_serviceDisconnected() {
MethodCall billingCall = new MethodCall(GET_BILLING_CONFIG, null);
methodChannelHandler.onMethodCall(billingCall, mock(Result.class));
methodChannelHandler.onMethodCall(billingCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
}
@Test
public void createAlternativeBillingOnlyReportingDetailsSuccess() {
mockStartConnection();
ArgumentCaptor<AlternativeBillingOnlyReportingDetailsListener> listenerCaptor =
ArgumentCaptor.forClass(AlternativeBillingOnlyReportingDetailsListener.class);
MethodCall createABOReportingDetailsCall =
new MethodCall(CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
final AlternativeBillingOnlyReportingDetails expectedDetails =
mock(AlternativeBillingOnlyReportingDetails.class);
final String expectedExternalTransactionToken = "abc123youandme";
when(expectedDetails.getExternalTransactionToken())
.thenReturn(expectedExternalTransactionToken);
doNothing()
.when(mockBillingClient)
.createAlternativeBillingOnlyReportingDetailsAsync(listenerCaptor.capture());
methodChannelHandler.onMethodCall(createABOReportingDetailsCall, result);
listenerCaptor.getValue().onAlternativeBillingOnlyTokenResponse(billingResult, expectedDetails);
verify(result, times(1))
.success(fromAlternativeBillingOnlyReportingDetails(billingResult, expectedDetails));
}
@Test
public void createAlternativeBillingOnlyReportingDetails_serviceDisconnected() {
MethodCall createCall = new MethodCall(CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS, null);
methodChannelHandler.onMethodCall(createCall, mock(Result.class));
methodChannelHandler.onMethodCall(createCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
}
@Test
public void isAlternativeBillingOnlyAvailableSuccess() {
mockStartConnection();
ArgumentCaptor<AlternativeBillingOnlyAvailabilityListener> listenerCaptor =
ArgumentCaptor.forClass(AlternativeBillingOnlyAvailabilityListener.class);
MethodCall billingCall = new MethodCall(IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
final HashMap<String, Object> expectedResult = fromBillingResult(billingResult);
doNothing()
.when(mockBillingClient)
.isAlternativeBillingOnlyAvailableAsync(listenerCaptor.capture());
methodChannelHandler.onMethodCall(billingCall, result);
listenerCaptor.getValue().onAlternativeBillingOnlyAvailabilityResponse(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void isAlternativeBillingOnlyAvailable_serviceDisconnected() {
MethodCall billingCall = new MethodCall(IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE, null);
methodChannelHandler.onMethodCall(billingCall, mock(Result.class));
methodChannelHandler.onMethodCall(billingCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
}
@Test
public void showAlternativeBillingOnlyInformationDialogSuccess() {
mockStartConnection();
ArgumentCaptor<AlternativeBillingOnlyInformationDialogListener> listenerCaptor =
ArgumentCaptor.forClass(AlternativeBillingOnlyInformationDialogListener.class);
MethodCall showDialogCall =
new MethodCall(SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.showAlternativeBillingOnlyInformationDialog(
eq(activity), listenerCaptor.capture()))
.thenReturn(billingResult);
methodChannelHandler.onMethodCall(showDialogCall, result);
listenerCaptor.getValue().onAlternativeBillingOnlyInformationDialogResponse(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void showAlternativeBillingOnlyInformationDialog_serviceDisconnected() {
MethodCall billingCall = new MethodCall(SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG, null);
methodChannelHandler.onMethodCall(billingCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
}
@Test
public void showAlternativeBillingOnlyInformationDialog_NullActivity() {
mockStartConnection();
MethodCall showDialogCall =
new MethodCall(SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG, null);
methodChannelHandler.setActivity(null);
methodChannelHandler.onMethodCall(showDialogCall, result);
verify(result)
.error(contains(ACTIVITY_UNAVAILABLE), contains("Not attempting to show dialog"), any());
}
@Test
public void endConnection() {
// Set up a connected BillingClient instance
final int disconnectCallbackHandle = 22;
Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", disconnectCallbackHandle);
MethodCall connectCall = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(connectCall, mock(Result.class));
final BillingClientStateListener stateListener = captor.getValue();
// Disconnect the connected client
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, result);
// Verify that the client is disconnected and that the OnDisconnect callback has
// been triggered
verify(result, times(1)).success(any());
verify(mockBillingClient, times(1)).endConnection();
stateListener.onBillingServiceDisconnected();
Map<String, Integer> expectedInvocation = new HashMap<>();
expectedInvocation.put("handle", disconnectCallbackHandle);
verify(mockMethodChannel, times(1)).invokeMethod(ON_DISCONNECT, expectedInvocation);
}
@Test
public void queryProductDetailsAsync() {
// Connect a billing client and set up the product query listeners
establishConnectedBillingClient(/* arguments= */ null, /* result= */ null);
String productType = BillingClient.ProductType.INAPP;
List<String> productsList = asList("id1", "id2");
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("productList", buildProductMap(productsList, productType));
MethodCall queryCall = new MethodCall(QUERY_PRODUCT_DETAILS, arguments);
// Query for product details
methodChannelHandler.onMethodCall(queryCall, result);
// Assert the arguments were forwarded correctly to BillingClient
ArgumentCaptor<QueryProductDetailsParams> paramCaptor =
ArgumentCaptor.forClass(QueryProductDetailsParams.class);
ArgumentCaptor<ProductDetailsResponseListener> listenerCaptor =
ArgumentCaptor.forClass(ProductDetailsResponseListener.class);
verify(mockBillingClient)
.queryProductDetailsAsync(paramCaptor.capture(), listenerCaptor.capture());
// Assert that we handed result BillingClient's response
int responseCode = 200;
List<ProductDetails> productDetailsResponse = asList(buildProductDetails("foo"));
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
listenerCaptor.getValue().onProductDetailsResponse(billingResult, productDetailsResponse);
verify(result).success(resultCaptor.capture());
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(resultData.get("billingResult"), fromBillingResult(billingResult));
assertEquals(
resultData.get("productDetailsList"), fromProductDetailsList(productDetailsResponse));
}
@Test
public void queryProductDetailsAsync_clientDisconnected() {
// Disconnect the Billing client and prepare a queryProductDetails call
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
String productType = BillingClient.ProductType.INAPP;
List<String> productsList = asList("id1", "id2");
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("productList", buildProductMap(productsList, productType));
MethodCall queryCall = new MethodCall(QUERY_PRODUCT_DETAILS, arguments);
// Query for product details
methodChannelHandler.onMethodCall(queryCall, result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
// Test launchBillingFlow not crash if `accountId` is `null`
// Ideally, we should check if the `accountId` is null in the parameter; however,
// since PBL 3.0, the `accountId` variable is not public.
@Test
public void launchBillingFlow_null_AccountId_do_not_crash() {
// Fetch the product details first and then prepare the launch billing flow call
String productId = "foo";
queryForProducts(singletonList(productId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", null);
arguments.put("obfuscatedProfileId", null);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_null_OldProduct() {
// Fetch the product details first and then prepare the launch billing flow call
String productId = "foo";
String accountId = "account";
queryForProducts(singletonList(productId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", null);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_null_Activity() {
methodChannelHandler.setActivity(null);
// Fetch the product details first and then prepare the launch billing flow call
String productId = "foo";
String accountId = "account";
queryForProducts(singletonList(productId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the response code to result
verify(result).error(contains("ACTIVITY_UNAVAILABLE"), contains("foreground"), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_ok_oldProduct() {
// Fetch the product details first and query the method call
String productId = "foo";
String accountId = "account";
String oldProductId = "oldFoo";
queryForProducts(unmodifiableList(asList(productId, oldProductId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", oldProductId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_AccountId() {
// Fetch the product details first and query the method call
String productId = "foo";
String accountId = "account";
queryForProducts(singletonList(productId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
// TODO(gmackall): Replace uses of deprecated ProrationMode enum values with new
// ReplacementMode enum values.
// https://github.com/flutter/flutter/issues/128957.
@Test
@SuppressWarnings(value = "deprecation")
public void launchBillingFlow_ok_Proration() {
// Fetch the product details first and query the method call
String productId = "foo";
String oldProductId = "oldFoo";
String purchaseToken = "purchaseTokenFoo";
String accountId = "account";
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_PRORATED_PRICE;
queryForProducts(unmodifiableList(asList(productId, oldProductId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", oldProductId);
arguments.put("purchaseToken", purchaseToken);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
// TODO(gmackall): Replace uses of deprecated ProrationMode enum values with new
// ReplacementMode enum values.
// https://github.com/flutter/flutter/issues/128957.
@Test
@SuppressWarnings(value = "deprecation")
public void launchBillingFlow_ok_Proration_with_null_OldProduct() {
// Fetch the product details first and query the method call
String productId = "foo";
String accountId = "account";
String queryOldProductId = "oldFoo";
String oldProductId = null;
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_PRORATED_PRICE;
queryForProducts(unmodifiableList(asList(productId, queryOldProductId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", oldProductId);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result)
.error(
contains("IN_APP_PURCHASE_REQUIRE_OLD_PRODUCT"),
contains("launchBillingFlow failed because oldProduct is null"),
any());
verify(result, never()).success(any());
}
// TODO(gmackall): Replace uses of deprecated ProrationMode enum values with new
// ReplacementMode enum values.
// https://github.com/flutter/flutter/issues/128957.
@Test
@SuppressWarnings(value = "deprecation")
public void launchBillingFlow_ok_Full() {
// Fetch the product details first and query the method call
String productId = "foo";
String oldProductId = "oldFoo";
String purchaseToken = "purchaseTokenFoo";
String accountId = "account";
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_FULL_PRICE;
queryForProducts(unmodifiableList(asList(productId, oldProductId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", oldProductId);
arguments.put("purchaseToken", purchaseToken);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_clientDisconnected() {
// Prepare the launch call after disconnecting the client
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
String productId = "foo";
String accountId = "account";
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_productNotFound() {
// Try to launch the billing flow for a random product ID
establishConnectedBillingClient(null, null);
String productId = "foo";
String accountId = "account";
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result).error(contains("NOT_FOUND"), contains(productId), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_oldProductNotFound() {
// Try to launch the billing flow for a random product ID
establishConnectedBillingClient(null, null);
String productId = "foo";
String accountId = "account";
String oldProductId = "oldProduct";
queryForProducts(singletonList(productId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("product", productId);
arguments.put("accountId", accountId);
arguments.put("oldProduct", oldProductId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result)
.error(contains("IN_APP_PURCHASE_INVALID_OLD_PRODUCT"), contains(oldProductId), any());
verify(result, never()).success(any());
}
@Test
public void queryPurchases_clientDisconnected() {
// Prepare the launch call after disconnecting the client
methodChannelHandler.onMethodCall(new MethodCall(END_CONNECTION, null), mock(Result.class));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("type", BillingClient.ProductType.INAPP);
methodChannelHandler.onMethodCall(new MethodCall(QUERY_PURCHASES_ASYNC, arguments), result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void queryPurchases_returns_success() throws Exception {
establishConnectedBillingClient(null, null);
CountDownLatch lock = new CountDownLatch(1);
doAnswer(
(Answer<Object>)
invocation -> {
lock.countDown();
return null;
})
.when(result)
.success(any(HashMap.class));
ArgumentCaptor<PurchasesResponseListener> purchasesResponseListenerArgumentCaptor =
ArgumentCaptor.forClass(PurchasesResponseListener.class);
doAnswer(
(Answer<Object>)
invocation -> {
BillingResult.Builder resultBuilder =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("hello message");
purchasesResponseListenerArgumentCaptor
.getValue()
.onQueryPurchasesResponse(resultBuilder.build(), new ArrayList<Purchase>());
return null;
})
.when(mockBillingClient)
.queryPurchasesAsync(
any(QueryPurchasesParams.class), purchasesResponseListenerArgumentCaptor.capture());
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("productType", BillingClient.ProductType.INAPP);
methodChannelHandler.onMethodCall(new MethodCall(QUERY_PURCHASES_ASYNC, arguments), result);
lock.await(5000, TimeUnit.MILLISECONDS);
verify(result, never()).error(any(), any(), any());
@SuppressWarnings("unchecked")
ArgumentCaptor<HashMap<String, Object>> hashMapCaptor = ArgumentCaptor.forClass(HashMap.class);
verify(result, times(1)).success(hashMapCaptor.capture());
HashMap<String, Object> map = hashMapCaptor.getValue();
assert (map.containsKey("responseCode"));
assert (map.containsKey("billingResult"));
assert (map.containsKey("purchasesList"));
assert ((int) map.get("responseCode") == 0);
}
@Test
public void queryPurchaseHistoryAsync() {
// Set up an established billing client and all our mocked responses
establishConnectedBillingClient(null, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
List<PurchaseHistoryRecord> purchasesList = asList(buildPurchaseHistoryRecord("foo"));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("productType", BillingClient.ProductType.INAPP);
ArgumentCaptor<PurchaseHistoryResponseListener> listenerCaptor =
ArgumentCaptor.forClass(PurchaseHistoryResponseListener.class);
methodChannelHandler.onMethodCall(
new MethodCall(QUERY_PURCHASE_HISTORY_ASYNC, arguments), result);
// Verify we pass the data to result
verify(mockBillingClient)
.queryPurchaseHistoryAsync(any(QueryPurchaseHistoryParams.class), listenerCaptor.capture());
listenerCaptor.getValue().onPurchaseHistoryResponse(billingResult, purchasesList);
verify(result).success(resultCaptor.capture());
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(fromBillingResult(billingResult), resultData.get("billingResult"));
assertEquals(
fromPurchaseHistoryRecordList(purchasesList), resultData.get("purchaseHistoryRecordList"));
}
@Test
public void queryPurchaseHistoryAsync_clientDisconnected() {
// Prepare the launch call after disconnecting the client
methodChannelHandler.onMethodCall(new MethodCall(END_CONNECTION, null), mock(Result.class));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("type", BillingClient.ProductType.INAPP);
methodChannelHandler.onMethodCall(
new MethodCall(QUERY_PURCHASE_HISTORY_ASYNC, arguments), result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void onPurchasesUpdatedListener() {
PluginPurchaseListener listener = new PluginPurchaseListener(mockMethodChannel);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
List<Purchase> purchasesList = asList(buildPurchase("foo"));
doNothing()
.when(mockMethodChannel)
.invokeMethod(eq(ON_PURCHASES_UPDATED), resultCaptor.capture());
listener.onPurchasesUpdated(billingResult, purchasesList);
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(fromBillingResult(billingResult), resultData.get("billingResult"));
assertEquals(fromPurchasesList(purchasesList), resultData.get("purchasesList"));
}
@Test
public void consumeAsync() {
establishConnectedBillingClient(null, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("purchaseToken", "mockToken");
arguments.put("developerPayload", "mockPayload");
ArgumentCaptor<ConsumeResponseListener> listenerCaptor =
ArgumentCaptor.forClass(ConsumeResponseListener.class);
methodChannelHandler.onMethodCall(new MethodCall(CONSUME_PURCHASE_ASYNC, arguments), result);
ConsumeParams params = ConsumeParams.newBuilder().setPurchaseToken("mockToken").build();
// Verify we pass the data to result
verify(mockBillingClient).consumeAsync(refEq(params), listenerCaptor.capture());
listenerCaptor.getValue().onConsumeResponse(billingResult, "mockToken");
verify(result).success(resultCaptor.capture());
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void acknowledgePurchase() {
establishConnectedBillingClient(null, null);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("purchaseToken", "mockToken");
arguments.put("developerPayload", "mockPayload");
ArgumentCaptor<AcknowledgePurchaseResponseListener> listenerCaptor =
ArgumentCaptor.forClass(AcknowledgePurchaseResponseListener.class);
methodChannelHandler.onMethodCall(new MethodCall(ACKNOWLEDGE_PURCHASE, arguments), result);
AcknowledgePurchaseParams params =
AcknowledgePurchaseParams.newBuilder().setPurchaseToken("mockToken").build();
// Verify we pass the data to result
verify(mockBillingClient).acknowledgePurchase(refEq(params), listenerCaptor.capture());
listenerCaptor.getValue().onAcknowledgePurchaseResponse(billingResult);
verify(result).success(resultCaptor.capture());
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void endConnection_if_activity_detached() {
InAppPurchasePlugin plugin = new InAppPurchasePlugin();
plugin.setMethodCallHandler(methodChannelHandler);
mockStartConnection();
plugin.onDetachedFromActivity();
verify(mockBillingClient).endConnection();
}
@Test
public void isFutureSupported_true() {
mockStartConnection();
final String feature = "subscriptions";
Map<String, Object> arguments = new HashMap<>();
arguments.put("feature", feature);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
MethodCall call = new MethodCall(IS_FEATURE_SUPPORTED, arguments);
when(mockBillingClient.isFeatureSupported(feature)).thenReturn(billingResult);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(true);
}
@Test
public void isFutureSupported_false() {
mockStartConnection();
final String feature = "subscriptions";
Map<String, Object> arguments = new HashMap<>();
arguments.put("feature", feature);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED)
.setDebugMessage("dummy debug message")
.build();
MethodCall call = new MethodCall(IS_FEATURE_SUPPORTED, arguments);
when(mockBillingClient.isFeatureSupported(feature)).thenReturn(billingResult);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(false);
}
/**
* Call {@link MethodCallHandlerImpl.START_CONNECTION] with startup params.
*
* Defaults to play billing only which is the default.
*/
private ArgumentCaptor<BillingClientStateListener> mockStartConnection() {
return mockStartConnection(BillingChoiceMode.PLAY_BILLING_ONLY);
}
/**
* Call {@link MethodCallHandlerImpl.START_CONNECTION] with startup params.
*
*{@link billingChoiceMode} is one of the int value used from {@link BillingChoiceMode}.
*/
private ArgumentCaptor<BillingClientStateListener> mockStartConnection(int billingChoiceMode) {
Map<String, Object> arguments = new HashMap<>();
arguments.put(MethodArgs.HANDLE, DEFAULT_HANDLE);
arguments.put(MethodArgs.BILLING_CHOICE_MODE, billingChoiceMode);
MethodCall call = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(call, result);
return captor;
}
private void establishConnectedBillingClient(
@Nullable Map<String, Object> arguments, @Nullable Result result) {
if (arguments == null) {
arguments = new HashMap<>();
arguments.put(MethodArgs.HANDLE, 1);
}
if (result == null) {
result = mock(Result.class);
}
MethodCall connectCall = new MethodCall(START_CONNECTION, arguments);
methodChannelHandler.onMethodCall(connectCall, result);
}
private void queryForProducts(List<String> productIdList) {
// Set up the query method call
establishConnectedBillingClient(/* arguments= */ null, /* result= */ null);
HashMap<String, Object> arguments = new HashMap<>();
String productType = BillingClient.ProductType.INAPP;
List<Map<String, Object>> productList = buildProductMap(productIdList, productType);
arguments.put("productList", productList);
MethodCall queryCall = new MethodCall(QUERY_PRODUCT_DETAILS, arguments);
// Call the method.
methodChannelHandler.onMethodCall(queryCall, mock(Result.class));
// Respond to the call with a matching set of product details.
ArgumentCaptor<ProductDetailsResponseListener> listenerCaptor =
ArgumentCaptor.forClass(ProductDetailsResponseListener.class);
verify(mockBillingClient).queryProductDetailsAsync(any(), listenerCaptor.capture());
List<ProductDetails> productDetailsResponse =
productIdList.stream().map(this::buildProductDetails).collect(toList());
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
listenerCaptor.getValue().onProductDetailsResponse(billingResult, productDetailsResponse);
}
private List<Map<String, Object>> buildProductMap(List<String> productIds, String productType) {
List<Map<String, Object>> productList = new ArrayList<>();
for (String productId : productIds) {
Map<String, Object> productMap = new HashMap<>();
productMap.put("productId", productId);
productMap.put("productType", productType);
productList.add(productMap);
}
return productList;
}
private ProductDetails buildProductDetails(String id) {
String json =
String.format(
"{\"title\":\"Example title\",\"description\":\"Example description\",\"productId\":\"%s\",\"type\":\"inapp\",\"name\":\"Example name\",\"oneTimePurchaseOfferDetails\":{\"priceAmountMicros\":990000,\"priceCurrencyCode\":\"USD\",\"formattedPrice\":\"$0.99\"}}",
id);
try {
Constructor<ProductDetails> productDetailsConstructor =
ProductDetails.class.getDeclaredConstructor(String.class);
productDetailsConstructor.setAccessible(true);
return productDetailsConstructor.newInstance(json);
} catch (NoSuchMethodException e) {
fail("buildProductDetails failed with NoSuchMethodException " + e);
} catch (InvocationTargetException e) {
fail("buildProductDetails failed with InvocationTargetException " + e);
} catch (IllegalAccessException e) {
fail("buildProductDetails failed with IllegalAccessException " + e);
} catch (InstantiationException e) {
fail("buildProductDetails failed with InstantiationException " + e);
}
return null;
}
private Purchase buildPurchase(String orderId) {
Purchase purchase = mock(Purchase.class);
when(purchase.getOrderId()).thenReturn(orderId);
return purchase;
}
private PurchaseHistoryRecord buildPurchaseHistoryRecord(String purchaseToken) {
PurchaseHistoryRecord purchase = mock(PurchaseHistoryRecord.class);
when(purchase.getPurchaseToken()).thenReturn(purchaseToken);
return purchase;
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/MethodCallHandlerTest.java/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/MethodCallHandlerTest.java",
"repo_id": "packages",
"token_count": 18752
} | 1,068 |
// 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:json_annotation/json_annotation.dart';
import '../../billing_client_wrappers.dart';
// WARNING: Changes to `@JsonSerializable` classes need to be reflected in the
// below generated file. Run `flutter packages pub run build_runner watch` to
// rebuild and watch for further changes.
part 'alternative_billing_only_reporting_details_wrapper.g.dart';
/// The error message shown when the map representing details is invalid from method channel.
///
/// This usually indicates a serious underlying code issue in the plugin.
@visibleForTesting
const String kInvalidAlternativeBillingReportingDetailsErrorMessage =
'Invalid AlternativeBillingReportingDetails map from method channel.';
/// Params containing the response code and the debug message from the Play Billing API response.
@JsonSerializable()
@BillingResponseConverter()
@immutable
class AlternativeBillingOnlyReportingDetailsWrapper
implements HasBillingResponse {
/// Constructs the object with [responseCode] and [debugMessage].
const AlternativeBillingOnlyReportingDetailsWrapper(
{required this.responseCode,
this.debugMessage,
this.externalTransactionToken = ''});
/// Constructs an instance of this from a key value map of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class.
factory AlternativeBillingOnlyReportingDetailsWrapper.fromJson(
Map<String, dynamic>? map) {
if (map == null || map.isEmpty) {
return const AlternativeBillingOnlyReportingDetailsWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidAlternativeBillingReportingDetailsErrorMessage,
);
}
return _$AlternativeBillingOnlyReportingDetailsWrapperFromJson(map);
}
/// Response code returned in the Play Billing API calls.
@override
final BillingResponse responseCode;
/// Debug message returned in the Play Billing API calls.
///
/// Defaults to `null`.
/// This message uses an en-US locale and should not be shown to users.
@JsonKey(defaultValue: '')
final String? debugMessage;
/// https://developer.android.com/reference/com/android/billingclient/api/AlternativeBillingOnlyReportingDetails#getExternalTransactionToken()
@JsonKey(defaultValue: '')
final String externalTransactionToken;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is AlternativeBillingOnlyReportingDetailsWrapper &&
other.responseCode == responseCode &&
other.debugMessage == debugMessage &&
other.externalTransactionToken == externalTransactionToken;
}
@override
int get hashCode =>
Object.hash(responseCode, debugMessage, externalTransactionToken);
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart",
"repo_id": "packages",
"token_count": 843
} | 1,069 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'purchase_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
PurchaseWrapper _$PurchaseWrapperFromJson(Map json) => PurchaseWrapper(
orderId: json['orderId'] as String? ?? '',
packageName: json['packageName'] as String? ?? '',
purchaseTime: json['purchaseTime'] as int? ?? 0,
purchaseToken: json['purchaseToken'] as String? ?? '',
signature: json['signature'] as String? ?? '',
products: (json['products'] as List<dynamic>?)
?.map((e) => e as String)
.toList() ??
[],
isAutoRenewing: json['isAutoRenewing'] as bool,
originalJson: json['originalJson'] as String? ?? '',
developerPayload: json['developerPayload'] as String?,
isAcknowledged: json['isAcknowledged'] as bool? ?? false,
purchaseState: const PurchaseStateConverter()
.fromJson(json['purchaseState'] as int?),
obfuscatedAccountId: json['obfuscatedAccountId'] as String?,
obfuscatedProfileId: json['obfuscatedProfileId'] as String?,
);
PurchaseHistoryRecordWrapper _$PurchaseHistoryRecordWrapperFromJson(Map json) =>
PurchaseHistoryRecordWrapper(
purchaseTime: json['purchaseTime'] as int? ?? 0,
purchaseToken: json['purchaseToken'] as String? ?? '',
signature: json['signature'] as String? ?? '',
products: (json['products'] as List<dynamic>?)
?.map((e) => e as String)
.toList() ??
[],
originalJson: json['originalJson'] as String? ?? '',
developerPayload: json['developerPayload'] as String?,
);
PurchasesResultWrapper _$PurchasesResultWrapperFromJson(Map json) =>
PurchasesResultWrapper(
responseCode: const BillingResponseConverter()
.fromJson(json['responseCode'] as int?),
billingResult:
BillingResultWrapper.fromJson((json['billingResult'] as Map?)?.map(
(k, e) => MapEntry(k as String, e),
)),
purchasesList: (json['purchasesList'] as List<dynamic>?)
?.map((e) =>
PurchaseWrapper.fromJson(Map<String, dynamic>.from(e as Map)))
.toList() ??
[],
);
PurchasesHistoryResult _$PurchasesHistoryResultFromJson(Map json) =>
PurchasesHistoryResult(
billingResult:
BillingResultWrapper.fromJson((json['billingResult'] as Map?)?.map(
(k, e) => MapEntry(k as String, e),
)),
purchaseHistoryRecordList:
(json['purchaseHistoryRecordList'] as List<dynamic>?)
?.map((e) => PurchaseHistoryRecordWrapper.fromJson(
Map<String, dynamic>.from(e as Map)))
.toList() ??
[],
);
const _$PurchaseStateWrapperEnumMap = {
PurchaseStateWrapper.unspecified_state: 0,
PurchaseStateWrapper.purchased: 1,
PurchaseStateWrapper.pending: 2,
};
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.g.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.g.dart",
"repo_id": "packages",
"token_count": 1215
} | 1,070 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.