text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/magic_link_prompt/magic_link_prompt.dart';
class MagicLinkPromptPage extends StatelessWidget {
const MagicLinkPromptPage({required this.email, super.key});
final String email;
static Route<void> route({required String email}) {
return MaterialPageRoute<void>(
builder: (_) => MagicLinkPromptPage(email: email),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: const AppBackButton(),
actions: [
IconButton(
key: const Key('magicLinkPrompt_closeIcon'),
icon: const Icon(Icons.close),
onPressed: () => Navigator.of(context)
.popUntil((route) => route.settings.name == LoginModal.name),
)
],
),
body: MagicLinkPromptView(
email: email,
),
);
}
}
| news_toolkit/flutter_news_example/lib/magic_link_prompt/view/magic_link_prompt_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/magic_link_prompt/view/magic_link_prompt_page.dart",
"repo_id": "news_toolkit",
"token_count": 421
} | 879 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
/// {@template network_error}
/// A network error alert.
/// {@endtemplate}
class NetworkError extends StatelessWidget {
/// {@macro network_error}
const NetworkError({super.key, this.onRetry});
/// An optional callback which is invoked when the retry button is pressed.
final VoidCallback? onRetry;
/// Route constructor to display the widget inside a [Scaffold].
static Route<void> route({VoidCallback? onRetry}) {
return PageRouteBuilder<void>(
pageBuilder: (_, __, ___) => Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
leading: const AppBackButton(),
),
body: Center(
child: NetworkError(onRetry: onRetry),
),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: AppSpacing.xlg),
const Icon(
Icons.error_outline,
size: 80,
color: AppColors.mediumHighEmphasisSurface,
),
const SizedBox(height: AppSpacing.lg),
Text(
l10n.networkError,
style: theme.textTheme.bodyLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: AppSpacing.lg),
Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxxlg),
child: AppButton.darkAqua(
onPressed: onRetry,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
flex: 0,
child: Icon(Icons.refresh, size: UITextStyle.button.fontSize),
),
const SizedBox(width: AppSpacing.xs),
Flexible(
child: Text(
l10n.networkErrorButton,
style: UITextStyle.button,
),
),
],
),
),
),
const SizedBox(height: AppSpacing.xlg),
],
);
}
}
| news_toolkit/flutter_news_example/lib/network_error/view/network_error.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/network_error/view/network_error.dart",
"repo_id": "news_toolkit",
"token_count": 1110
} | 880 |
part of 'onboarding_bloc.dart';
abstract class OnboardingState extends Equatable {
const OnboardingState();
@override
List<Object> get props => [];
}
class OnboardingInitial extends OnboardingState {
const OnboardingInitial();
}
class EnablingAdTracking extends OnboardingState {
const EnablingAdTracking();
}
class EnablingAdTrackingSucceeded extends OnboardingState {
const EnablingAdTrackingSucceeded();
}
class EnablingAdTrackingFailed extends OnboardingState {
const EnablingAdTrackingFailed();
}
class EnablingNotifications extends OnboardingState {
const EnablingNotifications();
}
class EnablingNotificationsSucceeded extends OnboardingState
with AnalyticsEventMixin {
const EnablingNotificationsSucceeded();
@override
AnalyticsEvent get event => PushNotificationSubscriptionEvent();
@override
List<Object> get props => [event];
}
class EnablingNotificationsFailed extends OnboardingState {
const EnablingNotificationsFailed();
}
| news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_state.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_state.dart",
"repo_id": "news_toolkit",
"token_count": 276
} | 881 |
export 'search_filter_chip.dart';
export 'search_headline_text.dart';
export 'search_text_field.dart';
| news_toolkit/flutter_news_example/lib/search/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/search/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 37
} | 882 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:intl/intl.dart';
class SubscriptionCard extends StatelessWidget {
const SubscriptionCard({
required this.subscription,
this.isExpanded = false,
this.isBestValue = false,
super.key,
});
final bool isExpanded;
final bool isBestValue;
final Subscription subscription;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final monthlyCost = NumberFormat.currency(
decimalDigits: subscription.cost.monthly % 100 == 0 ? 0 : 2,
symbol: r'$',
).format(subscription.cost.monthly / 100);
final annualCost = NumberFormat.currency(
decimalDigits: subscription.cost.annual % 100 == 0 ? 0 : 2,
symbol: r'$',
).format(
subscription.cost.annual / 100,
);
final isLoggedIn = context.select<AppBloc, bool>(
(AppBloc bloc) => bloc.state.status.isLoggedIn,
);
return Card(
shadowColor: AppColors.black,
shape: RoundedRectangleBorder(
side: const BorderSide(
color: AppColors.borderOutline,
),
borderRadius: BorderRadius.circular(AppSpacing.lg),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xlg + AppSpacing.sm,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: AppSpacing.xlg + AppSpacing.sm,
),
Text(
subscription.name.name.toUpperCase(),
style: theme.textTheme.titleLarge
?.copyWith(color: AppColors.secondary),
),
Text(
'$monthlyCost/${l10n.monthAbbreviation} | $annualCost/${l10n.yearAbbreviation}',
style: theme.textTheme.headlineSmall,
),
if (isBestValue) ...[
Assets.icons.bestValue
.svg(key: const Key('subscriptionCard_bestValueSvg')),
const SizedBox(height: AppSpacing.md),
],
if (isExpanded) ...[
const Divider(indent: 0, endIndent: 0),
const SizedBox(height: AppSpacing.md),
Text(
l10n.subscriptionPurchaseBenefits.toUpperCase(),
style: theme.textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.w600),
),
],
for (final paragraph in subscription.benefits)
ListTile(
key: ValueKey(paragraph),
dense: true,
contentPadding: const EdgeInsets.symmetric(
vertical: AppSpacing.sm,
),
horizontalTitleGap: 0,
leading: const Icon(
Icons.check,
color: AppColors.mediumHighEmphasisSurface,
),
title: Text(
paragraph,
style: theme.textTheme.labelLarge?.copyWith(
color: AppColors.mediumHighEmphasisSurface,
),
),
),
if (isExpanded) ...[
const Divider(indent: 0, endIndent: 0),
const SizedBox(height: AppSpacing.md),
Align(
child: Text(
l10n.subscriptionPurchaseCancelAnytime,
style: theme.textTheme.labelLarge?.copyWith(
color: AppColors.mediumHighEmphasisSurface,
),
),
),
const SizedBox(height: AppSpacing.md),
AppButton.smallRedWine(
key: const Key('subscriptionCard_subscribe_appButton'),
onPressed: isLoggedIn
? () => context.read<SubscriptionsBloc>().add(
SubscriptionPurchaseRequested(
subscription: subscription,
),
)
: () => showAppModal<void>(
context: context,
builder: (_) => const LoginModal(),
routeSettings:
const RouteSettings(name: LoginModal.name),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (isLoggedIn)
Text(l10n.subscriptionPurchaseButton)
else
Text(l10n.subscriptionUnauthenticatedPurchaseButton)
],
),
),
] else
AppButton.smallOutlineTransparent(
key: const Key('subscriptionCard_viewDetails_appButton'),
onPressed: () => ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
key: const Key(
'subscriptionCard_unimplemented_snackBar',
),
content: Text(
l10n.subscriptionViewDetailsButtonSnackBar,
),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text(l10n.subscriptionViewDetailsButton)],
),
),
const SizedBox(height: AppSpacing.lg + AppSpacing.sm),
],
),
),
);
}
}
| news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscription_card.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscription_card.dart",
"repo_id": "news_toolkit",
"token_count": 3289
} | 883 |
export 'bloc/user_profile_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| news_toolkit/flutter_news_example/lib/user_profile/user_profile.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/user_profile/user_profile.dart",
"repo_id": "news_toolkit",
"token_count": 38
} | 884 |
import 'package:equatable/equatable.dart';
/// {@template analytics_event}
/// An analytic event which can be tracked.
/// Consists of the unique event name and an optional
/// map of properties.
/// {@endtemplate}
class AnalyticsEvent extends Equatable {
/// {@macro analytics_event}
const AnalyticsEvent(this.name, {this.properties});
/// Unique event name.
final String name;
/// Optional map of event properties.
final Map<String, dynamic>? properties;
@override
List<Object?> get props => [name, properties];
}
/// Mixin for tracking analytics events.
mixin AnalyticsEventMixin on Equatable {
/// Analytics event which will be tracked.
AnalyticsEvent get event;
@override
List<Object> get props => [event];
}
| news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/models/analytics_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/models/analytics_event.dart",
"repo_id": "news_toolkit",
"token_count": 206
} | 885 |
<svg width="18" height="14" viewBox="0 0 18 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.75 0.25H2.25C1.4175 0.25 0.75 0.9175 0.75 1.75V10.75C0.75 11.575 1.4175 12.25 2.25 12.25H6V13.75H12V12.25H15.75C16.575 12.25 17.2425 11.575 17.2425 10.75L17.25 1.75C17.25 0.9175 16.575 0.25 15.75 0.25ZM15.75 10.75H2.25V1.75H15.75V10.75ZM12 6.25L6.75 9.25V3.25L12 6.25Z" fill="white"/>
</svg>
| news_toolkit/flutter_news_example/packages/app_ui/assets/icons/video.svg/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/assets/icons/video.svg",
"repo_id": "news_toolkit",
"token_count": 223
} | 886 |
// ignore_for_file: avoid_field_initializers_in_const_classes
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
class AppSwitchPage extends StatelessWidget {
AppSwitchPage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => AppSwitchPage());
}
final appSwitchList = [
const _AppSwitch(switchType: SwitchType.on),
const _AppSwitch(switchType: SwitchType.off),
const _AppSwitch(switchType: SwitchType.noLabelOn),
const _AppSwitch(switchType: SwitchType.noLabelOff),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('App Switches')),
body: ListView(children: appSwitchList),
);
}
}
enum SwitchType {
on,
off,
noLabelOn,
noLabelOff,
}
class _AppSwitch extends StatelessWidget {
const _AppSwitch({required this.switchType});
AppSwitch get appSwitch {
switch (switchType) {
case SwitchType.on:
return AppSwitch(
onChanged: (_) {},
onText: 'On',
value: true,
);
case SwitchType.off:
return AppSwitch(
onChanged: (_) {},
onText: 'Off',
value: false,
);
case SwitchType.noLabelOn:
return AppSwitch(
onChanged: (_) {},
value: true,
);
case SwitchType.noLabelOff:
return AppSwitch(
onChanged: (_) {},
value: false,
);
}
}
final SwitchType switchType;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.lg,
),
child: appSwitch,
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_switch_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_switch_page.dart",
"repo_id": "news_toolkit",
"token_count": 742
} | 887 |
export 'date_time_extension.dart';
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/extensions/extensions.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/extensions/extensions.dart",
"repo_id": "news_toolkit",
"token_count": 13
} | 888 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template content_theme_override_builder}
/// The builder widget that overrides the default [TextTheme]
/// to [AppTheme.contentTextTheme] in the widget tree
/// below the given [builder] widget.
/// {@endtemplate}
class ContentThemeOverrideBuilder extends StatelessWidget {
/// {@macro content_theme_override_builder}
const ContentThemeOverrideBuilder({required this.builder, super.key});
/// The widget builder below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final WidgetBuilder builder;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Theme(
data: theme.copyWith(
textTheme: AppTheme.contentTextTheme,
),
child: Builder(builder: builder),
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/content_theme_override_builder.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/content_theme_override_builder.dart",
"repo_id": "news_toolkit",
"token_count": 274
} | 889 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('AppTheme', () {
group('themeData', () {
group('color', () {
test('primary is blue', () {
expect(
const AppTheme().themeData.primaryColor,
AppColors.blue,
);
});
test('secondary is AppColors.secondary', () {
expect(
const AppTheme().themeData.colorScheme.secondary,
AppColors.secondary,
);
});
});
group('divider', () {
test('horizontal padding is AppSpacing.lg', () {
expect(
const AppTheme().themeData.dividerTheme.indent,
AppSpacing.lg,
);
expect(
const AppTheme().themeData.dividerTheme.endIndent,
AppSpacing.lg,
);
});
test('space is AppSpacing.lg', () {
expect(
const AppTheme().themeData.dividerTheme.space,
AppSpacing.lg,
);
});
});
group('switchTheme', () {
group('thumbColor', () {
test('returns darkAqua when selected', () {
expect(
const AppTheme()
.themeData
.switchTheme
.thumbColor
?.resolve({MaterialState.selected}),
equals(AppColors.darkAqua),
);
});
test('returns eerieBlack when not selected', () {
expect(
const AppTheme().themeData.switchTheme.thumbColor?.resolve({}),
equals(AppColors.eerieBlack),
);
});
});
group('trackColor', () {
test('returns primaryContainer when selected', () {
expect(
const AppTheme()
.themeData
.switchTheme
.trackColor
?.resolve({MaterialState.selected}),
equals(AppColors.primaryContainer),
);
});
test('returns paleSky when not selected', () {
expect(
const AppTheme().themeData.switchTheme.trackColor?.resolve({}),
equals(AppColors.paleSky),
);
});
});
});
group('progressIndicatorTheme', () {
test('color is AppColors.darkAqua', () {
expect(
const AppTheme().themeData.progressIndicatorTheme.color,
equals(AppColors.darkAqua),
);
});
test('circularTrackColor is AppColors.borderOutline', () {
expect(
const AppTheme()
.themeData
.progressIndicatorTheme
.circularTrackColor,
equals(AppColors.borderOutline),
);
});
});
});
});
group('AppDarkTheme', () {
group('themeData', () {
group('color', () {
test('primary is blue', () {
expect(
const AppDarkTheme().themeData.primaryColor,
AppColors.blue,
);
});
test('secondary is AppColors.secondary', () {
expect(
const AppDarkTheme().themeData.colorScheme.secondary,
AppColors.secondary,
);
});
test('background is grey.shade900', () {
expect(
const AppDarkTheme().themeData.colorScheme.background,
AppColors.grey.shade900,
);
});
});
group('divider', () {
test('horizontal padding is AppSpacing.lg', () {
expect(
const AppTheme().themeData.dividerTheme.indent,
AppSpacing.lg,
);
expect(
const AppTheme().themeData.dividerTheme.endIndent,
AppSpacing.lg,
);
});
test('space is AppSpacing.lg', () {
expect(
const AppTheme().themeData.dividerTheme.space,
AppSpacing.lg,
);
});
});
});
});
}
| news_toolkit/flutter_news_example/packages/app_ui/test/theme/app_theme_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/theme/app_theme_test.dart",
"repo_id": "news_toolkit",
"token_count": 2162
} | 890 |
export 'authentication_user.dart';
| news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/models/models.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/models/models.dart",
"repo_id": "news_toolkit",
"token_count": 11
} | 891 |
name: token_storage
description: Token storage for the authentication client.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dev_dependencies:
coverage: ^1.3.2
mocktail: ^1.0.2
test: ^1.21.4
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/authentication_client/token_storage/pubspec.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/token_storage/pubspec.yaml",
"repo_id": "news_toolkit",
"token_count": 109
} | 892 |
# form_inputs
A Dart package which exposes reusable form inputs and validation rules
| news_toolkit/flutter_news_example/packages/form_inputs/README.md/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/form_inputs/README.md",
"repo_id": "news_toolkit",
"token_count": 19
} | 893 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template newsletter_container}
/// A reusable newsletter container widget.
/// {@endtemplate}
class NewsletterContainer extends StatelessWidget {
/// {@macro newsletter_container}
const NewsletterContainer({
super.key,
this.child,
});
/// The widget displayed in newsletter container.
final Widget? child;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: ColoredBox(
color: AppColors.secondary.shade800,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.xlg + AppSpacing.sm),
child: child,
),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/newsletter_container.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/newsletter_container.dart",
"repo_id": "news_toolkit",
"token_count": 281
} | 894 |
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
/// {@template spacer}
/// A reusable spacer news block widget.
/// {@endtemplate}
class Spacer extends StatelessWidget {
/// {@macro spacer}
const Spacer({required this.block, super.key});
/// The associated [SpacerBlock] instance.
final SpacerBlock block;
/// The spacing values of this spacer.
static const _spacingValues = <Spacing, double>{
Spacing.extraSmall: 4,
Spacing.small: 8,
Spacing.medium: 16,
Spacing.large: 32,
Spacing.veryLarge: 48,
Spacing.extraLarge: 64,
};
@override
Widget build(BuildContext context) {
final spacing = _spacingValues.containsKey(block.spacing)
? _spacingValues[block.spacing]
: 0.0;
return SizedBox(
width: double.infinity,
height: spacing,
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/spacer.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/spacer.dart",
"repo_id": "news_toolkit",
"token_count": 319
} | 895 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template post_content_category}
/// A widget displaying the category of a post.
/// {@endtemplate}
class PostContentCategory extends StatelessWidget {
/// {@macro post_content_category}
const PostContentCategory({
required this.categoryName,
required this.isContentOverlaid,
required this.isVideoContent,
super.key,
});
/// Category of post.
final String categoryName;
/// Whether this category should be overlaid on the image.
final bool isContentOverlaid;
/// Whether content is a part of a video article.
final bool isVideoContent;
@override
Widget build(BuildContext context) {
// Category label hierarchy
final backgroundColor =
isContentOverlaid ? AppColors.secondary : AppColors.transparent;
final isCategoryBackgroundDark = isContentOverlaid;
final textColor = isVideoContent
? AppColors.orange
: isCategoryBackgroundDark
? AppColors.white
: AppColors.secondary;
final horizontalSpacing = isCategoryBackgroundDark ? AppSpacing.xs : 0.0;
return Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: DecoratedBox(
decoration: BoxDecoration(color: backgroundColor),
child: Padding(
padding: EdgeInsets.fromLTRB(
horizontalSpacing,
0,
horizontalSpacing,
AppSpacing.xxs,
),
child: Text(
categoryName.toUpperCase(),
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(color: textColor),
),
),
),
),
const SizedBox(height: AppSpacing.sm),
],
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_content_category.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_content_category.dart",
"repo_id": "news_toolkit",
"token_count": 818
} | 896 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 897 |
import 'package:notifications_client/notifications_client.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
/// {@template one_signal_notifications_client}
/// OneSignal notifications client.
/// {@endtemplate}
class OneSignalNotificationsClient implements NotificationsClient {
/// {@macro one_signal_notifications_client}
const OneSignalNotificationsClient({
required OneSignal oneSignal,
}) : _oneSignal = oneSignal;
/// OneSignal instance.
final OneSignal _oneSignal;
@override
Future<void> subscribeToCategory(String category) async {
try {
await _oneSignal.sendTag(category, true);
} catch (error, stackTrace) {
Error.throwWithStackTrace(
SubscribeToCategoryFailure(error),
stackTrace,
);
}
}
@override
Future<void> unsubscribeFromCategory(String category) async {
try {
await _oneSignal.deleteTag(category);
} catch (error, stackTrace) {
Error.throwWithStackTrace(
UnsubscribeFromCategoryFailure(error),
stackTrace,
);
}
}
}
| news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/lib/src/one_signal_notifications_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/lib/src/one_signal_notifications_client.dart",
"repo_id": "news_toolkit",
"token_count": 388
} | 898 |
/// {@template package_info_client}
/// A client that provides information about the app's package metadata
/// like app name, package name or version.
/// {@endtemplate}
class PackageInfoClient {
/// {@macro package_info_client}
PackageInfoClient({
required this.appName,
required this.packageName,
required this.packageVersion,
});
/// The app name.
final String appName;
/// The package name.
final String packageName;
/// The package version.
final String packageVersion;
}
| news_toolkit/flutter_news_example/packages/package_info_client/lib/src/package_info_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/package_info_client/lib/src/package_info_client.dart",
"repo_id": "news_toolkit",
"token_count": 144
} | 899 |
name: purchase_client
description: A PurchaseClient stubbing InAppPurchase implementation.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
clock: ^1.1.0
equatable: ^2.0.3
flutter:
sdk: flutter
in_app_purchase: ^3.0.5
in_app_purchase_platform_interface: ^1.3.2
dev_dependencies:
flutter_test:
sdk: flutter
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/purchase_client/pubspec.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/purchase_client/pubspec.yaml",
"repo_id": "news_toolkit",
"token_count": 171
} | 900 |
# Secure Storage
[](https://pub.dev/packages/very_good_analysis)
A Key/Value Secure Storage Client.
| news_toolkit/flutter_news_example/packages/storage/secure_storage/README.md/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/storage/secure_storage/README.md",
"repo_id": "news_toolkit",
"token_count": 68
} | 901 |
import 'dart:async';
import 'package:authentication_client/authentication_client.dart';
import 'package:deep_link_client/deep_link_client.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_news_example_api/client.dart' hide User;
import 'package:package_info_client/package_info_client.dart';
import 'package:rxdart/rxdart.dart';
import 'package:storage/storage.dart';
import 'package:user_repository/user_repository.dart';
part 'user_storage.dart';
/// {@template user_failure}
/// A base failure for the user repository failures.
/// {@endtemplate}
abstract class UserFailure with EquatableMixin implements Exception {
/// {@macro user_failure}
const UserFailure(this.error);
/// The error which was caught.
final Object error;
@override
List<Object> get props => [error];
}
/// {@template fetch_app_opened_count_failure}
/// Thrown when fetching app opened count fails.
/// {@endtemplate}
class FetchAppOpenedCountFailure extends UserFailure {
/// {@macro fetch_app_opened_count_failure}
const FetchAppOpenedCountFailure(super.error);
}
/// {@template increment_app_opened_count_failure}
/// Thrown when incrementing app opened count fails.
/// {@endtemplate}
class IncrementAppOpenedCountFailure extends UserFailure {
/// {@macro increment_app_opened_count_failure}
const IncrementAppOpenedCountFailure(super.error);
}
/// {@template fetch_current_subscription_failure}
/// An exception thrown when fetching current subscription fails.
class FetchCurrentSubscriptionFailure extends UserFailure {
/// {@macro fetch_current_subscription_failure}
const FetchCurrentSubscriptionFailure(super.error);
}
/// {@template user_repository}
/// Repository which manages the user domain.
/// {@endtemplate}
class UserRepository {
/// {@macro user_repository}
UserRepository({
required FlutterNewsExampleApiClient apiClient,
required AuthenticationClient authenticationClient,
required PackageInfoClient packageInfoClient,
required DeepLinkClient deepLinkClient,
required UserStorage storage,
}) : _apiClient = apiClient,
_authenticationClient = authenticationClient,
_packageInfoClient = packageInfoClient,
_deepLinkClient = deepLinkClient,
_storage = storage;
final FlutterNewsExampleApiClient _apiClient;
final AuthenticationClient _authenticationClient;
final PackageInfoClient _packageInfoClient;
final DeepLinkClient _deepLinkClient;
final UserStorage _storage;
/// Stream of [User] which will emit the current user when
/// the authentication state or the subscription plan changes.
///
Stream<User> get user =>
Rx.combineLatest2<AuthenticationUser, SubscriptionPlan, User>(
_authenticationClient.user,
_currentSubscriptionPlanSubject.stream,
(authenticationUser, subscriptionPlan) => User.fromAuthenticationUser(
authenticationUser: authenticationUser,
subscriptionPlan: authenticationUser != AuthenticationUser.anonymous
? subscriptionPlan
: SubscriptionPlan.none,
),
).asBroadcastStream();
final BehaviorSubject<SubscriptionPlan> _currentSubscriptionPlanSubject =
BehaviorSubject.seeded(SubscriptionPlan.none);
/// A stream of incoming email links used to authenticate the user.
///
/// Emits when a new email link is emitted on [DeepLinkClient.deepLinkStream],
/// which is validated using [AuthenticationClient.isLogInWithEmailLink].
Stream<Uri> get incomingEmailLinks => _deepLinkClient.deepLinkStream.where(
(deepLink) => _authenticationClient.isLogInWithEmailLink(
emailLink: deepLink.toString(),
),
);
/// Starts the Sign In with Apple Flow.
///
/// Throws a [LogInWithAppleFailure] if an exception occurs.
Future<void> logInWithApple() async {
try {
await _authenticationClient.logInWithApple();
} on LogInWithAppleFailure {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogInWithAppleFailure(error), stackTrace);
}
}
/// Starts the Sign In with Google Flow.
///
/// Throws a [LogInWithGoogleCanceled] if the flow is canceled by the user.
/// Throws a [LogInWithGoogleFailure] if an exception occurs.
Future<void> logInWithGoogle() async {
try {
await _authenticationClient.logInWithGoogle();
} on LogInWithGoogleFailure {
rethrow;
} on LogInWithGoogleCanceled {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogInWithGoogleFailure(error), stackTrace);
}
}
/// Starts the Sign In with Twitter Flow.
///
/// Throws a [LogInWithTwitterCanceled] if the flow is canceled by the user.
/// Throws a [LogInWithTwitterFailure] if an exception occurs.
Future<void> logInWithTwitter() async {
try {
await _authenticationClient.logInWithTwitter();
} on LogInWithTwitterFailure {
rethrow;
} on LogInWithTwitterCanceled {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogInWithTwitterFailure(error), stackTrace);
}
}
/// Starts the Sign In with Facebook Flow.
///
/// Throws a [LogInWithFacebookCanceled] if the flow is canceled by the user.
/// Throws a [LogInWithFacebookFailure] if an exception occurs.
Future<void> logInWithFacebook() async {
try {
await _authenticationClient.logInWithFacebook();
} on LogInWithFacebookFailure {
rethrow;
} on LogInWithFacebookCanceled {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogInWithFacebookFailure(error), stackTrace);
}
}
/// Sends an authentication link to the provided [email].
///
/// Throws a [SendLoginEmailLinkFailure] if an exception occurs.
Future<void> sendLoginEmailLink({
required String email,
}) async {
try {
await _authenticationClient.sendLoginEmailLink(
email: email,
appPackageName: _packageInfoClient.packageName,
);
} on SendLoginEmailLinkFailure {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(SendLoginEmailLinkFailure(error), stackTrace);
}
}
/// Signs in with the provided [email] and [emailLink].
///
/// Throws a [LogInWithEmailLinkFailure] if an exception occurs.
Future<void> logInWithEmailLink({
required String email,
required String emailLink,
}) async {
try {
await _authenticationClient.logInWithEmailLink(
email: email,
emailLink: emailLink,
);
} on LogInWithEmailLinkFailure {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogInWithEmailLinkFailure(error), stackTrace);
}
}
/// Signs out the current user which will emit
/// [User.anonymous] from the [user] Stream.
///
/// Throws a [LogOutFailure] if an exception occurs.
Future<void> logOut() async {
try {
await _authenticationClient.logOut();
} on LogOutFailure {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(LogOutFailure(error), stackTrace);
}
}
/// Returns the number of times the app was opened.
Future<int> fetchAppOpenedCount() async {
try {
return await _storage.fetchAppOpenedCount();
} catch (error, stackTrace) {
Error.throwWithStackTrace(
FetchAppOpenedCountFailure(error),
stackTrace,
);
}
}
/// Increments the number of times the app was opened by 1.
Future<void> incrementAppOpenedCount() async {
try {
final value = await fetchAppOpenedCount();
final result = value + 1;
await _storage.setAppOpenedCount(count: result);
} catch (error, stackTrace) {
Error.throwWithStackTrace(
IncrementAppOpenedCountFailure(error),
stackTrace,
);
}
}
/// Updates the current subscription plan of the user.
Future<void> updateSubscriptionPlan() async {
try {
final response = await _apiClient.getCurrentUser();
_currentSubscriptionPlanSubject.add(response.user.subscription);
} catch (error, stackTrace) {
Error.throwWithStackTrace(
FetchCurrentSubscriptionFailure(error),
stackTrace,
);
}
}
}
| news_toolkit/flutter_news_example/packages/user_repository/lib/src/user_repository.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/user_repository/lib/src/user_repository.dart",
"repo_id": "news_toolkit",
"token_count": 2785
} | 902 |
// ignore_for_file: prefer_const_constructors, must_be_immutable
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:notifications_repository/notifications_repository.dart';
import 'package:user_repository/user_repository.dart';
class MockUserRepository extends Mock implements UserRepository {}
class MockNotificationsRepository extends Mock
implements NotificationsRepository {}
class MockUser extends Mock implements User {}
void main() {
group('AppBloc', () {
late User user;
late UserRepository userRepository;
late NotificationsRepository notificationsRepository;
setUp(() {
userRepository = MockUserRepository();
notificationsRepository = MockNotificationsRepository();
user = MockUser();
when(() => userRepository.user).thenAnswer((_) => Stream.empty());
when(() => user.isNewUser).thenReturn(User.anonymous.isNewUser);
when(() => user.id).thenReturn(User.anonymous.id);
when(() => user.subscriptionPlan)
.thenReturn(User.anonymous.subscriptionPlan);
});
test('initial state is unauthenticated when user is anonymous', () {
expect(
AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: User.anonymous,
).state.status,
equals(AppStatus.unauthenticated),
);
});
group('AppUserChanged', () {
late User returningUser;
late User newUser;
setUp(() {
returningUser = MockUser();
newUser = MockUser();
when(() => returningUser.isNewUser).thenReturn(false);
when(() => returningUser.id).thenReturn('id');
when(() => returningUser.subscriptionPlan)
.thenReturn(SubscriptionPlan.none);
when(() => newUser.isNewUser).thenReturn(true);
when(() => newUser.id).thenReturn('id');
when(() => newUser.subscriptionPlan).thenReturn(SubscriptionPlan.none);
});
blocTest<AppBloc, AppState>(
'emits nothing when '
'state is unauthenticated and user is anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(User.anonymous),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
seed: AppState.unauthenticated,
expect: () => <AppState>[],
);
blocTest<AppBloc, AppState>(
'emits unauthenticated when '
'state is onboardingRequired and user is anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(User.anonymous),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
seed: () => AppState.onboardingRequired(user),
expect: () => <AppState>[AppState.unauthenticated()],
);
blocTest<AppBloc, AppState>(
'emits onboardingRequired when user is new and not anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(newUser),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
expect: () => [AppState.onboardingRequired(newUser)],
);
blocTest<AppBloc, AppState>(
'emits authenticated when user is returning and not anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(returningUser),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
expect: () => [AppState.authenticated(returningUser)],
);
blocTest<AppBloc, AppState>(
'emits authenticated '
'when authenticated user changes',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(returningUser),
);
},
seed: () => AppState.authenticated(user),
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
expect: () => [AppState.authenticated(returningUser)],
);
blocTest<AppBloc, AppState>(
'emits authenticated when '
'user is not anonymous and onboarding is complete',
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
seed: () => AppState.onboardingRequired(user),
act: (bloc) => bloc.add(AppOnboardingCompleted()),
expect: () => [AppState.authenticated(user)],
);
blocTest<AppBloc, AppState>(
'emits unauthenticated when '
'user is anonymous and onboarding is complete',
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: User.anonymous,
),
seed: () => AppState.onboardingRequired(User.anonymous),
act: (bloc) => bloc.add(AppOnboardingCompleted()),
expect: () => [AppState.unauthenticated()],
);
blocTest<AppBloc, AppState>(
'emits unauthenticated when user is anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(User.anonymous),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
expect: () => [AppState.unauthenticated()],
);
blocTest<AppBloc, AppState>(
'emits nothing when '
'state is unauthenticated and user is anonymous',
setUp: () {
when(() => userRepository.user).thenAnswer(
(_) => Stream.value(User.anonymous),
);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
seed: AppState.unauthenticated,
expect: () => <AppState>[],
);
});
group('AppLogoutRequested', () {
setUp(() {
when(
() => notificationsRepository.toggleNotifications(
enable: any(named: 'enable'),
),
).thenAnswer((_) async {});
when(() => userRepository.logOut()).thenAnswer((_) async {});
});
blocTest<AppBloc, AppState>(
'calls toggleNotifications off on NotificationsRepository',
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
act: (bloc) => bloc.add(AppLogoutRequested()),
verify: (_) {
verify(
() => notificationsRepository.toggleNotifications(enable: false),
).called(1);
},
);
blocTest<AppBloc, AppState>(
'calls logOut on UserRepository',
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
act: (bloc) => bloc.add(AppLogoutRequested()),
verify: (_) {
verify(() => userRepository.logOut()).called(1);
},
);
});
group('close', () {
late StreamController<User> userController;
setUp(() {
userController = StreamController<User>();
when(() => userRepository.user)
.thenAnswer((_) => userController.stream);
});
blocTest<AppBloc, AppState>(
'cancels UserRepository.user subscription',
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
tearDown: () => expect(userController.hasListener, isFalse),
);
});
group('AppOpened', () {
blocTest<AppBloc, AppState>(
'calls UserRepository.incrementAppOpenedCount '
'and emits showLoginOverlay as true '
'when fetchAppOpenedCount returns a count value of 4 '
'and user is anonymous',
setUp: () {
when(() => userRepository.fetchAppOpenedCount())
.thenAnswer((_) async => 4);
when(() => userRepository.incrementAppOpenedCount())
.thenAnswer((_) async {});
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
act: (bloc) => bloc.add(AppOpened()),
seed: AppState.unauthenticated,
expect: () => <AppState>[
AppState(
showLoginOverlay: true,
status: AppStatus.unauthenticated,
)
],
verify: (_) {
verify(
() => userRepository.incrementAppOpenedCount(),
).called(1);
},
);
blocTest<AppBloc, AppState>(
'calls UserRepository.incrementAppOpenedCount '
'when fetchAppOpenedCount returns a count value of 3 '
'and user is anonymous',
setUp: () {
when(() => userRepository.fetchAppOpenedCount())
.thenAnswer((_) async => 3);
when(() => userRepository.incrementAppOpenedCount())
.thenAnswer((_) async {});
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
act: (bloc) => bloc.add(AppOpened()),
seed: AppState.unauthenticated,
expect: () => <AppState>[],
verify: (_) {
verify(
() => userRepository.incrementAppOpenedCount(),
).called(1);
},
);
blocTest<AppBloc, AppState>(
'does not call UserRepository.incrementAppOpenedCount '
'when fetchAppOpenedCount returns a count value of 6 '
'and user is anonymous',
setUp: () {
when(() => userRepository.fetchAppOpenedCount())
.thenAnswer((_) async => 6);
},
build: () => AppBloc(
userRepository: userRepository,
notificationsRepository: notificationsRepository,
user: user,
),
act: (bloc) => bloc.add(AppOpened()),
seed: AppState.unauthenticated,
expect: () => <AppState>[],
verify: (_) {
verifyNever(
() => userRepository.incrementAppOpenedCount(),
);
},
);
});
});
}
| news_toolkit/flutter_news_example/test/app/bloc/app_bloc_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/app/bloc/app_bloc_test.dart",
"repo_id": "news_toolkit",
"token_count": 4966
} | 903 |
// ignore_for_file: prefer_const_constructors, avoid_redundant_argument_values
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_news_example_api/client.dart' hide User;
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:user_repository/user_repository.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../helpers/helpers.dart';
class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState>
implements ArticleBloc {}
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
class MockUser extends Mock implements User {}
void main() {
group('ArticleTrailingContent', () {
late ArticleBloc articleBloc;
late AppBloc appBloc;
final postSmallBlock = PostSmallBlock(
id: '36f4a017-d099-4fce-8727-1d9ca6a0398c',
category: PostCategory.technology,
author: 'Tom Phillips',
publishedAt: DateTime(2022, 6, 2),
imageUrl:
'https://assets.reedpopcdn.com/stray_XlfRQmc.jpg/BROK/thumbnail/'
'1600x900/format/jpg/quality/80/stray_XlfRQmc.jpg',
title: 'Stray launches next month, included in pricier PlayStation '
'Plus tiers on day one',
description: "Stray, everyone's favorite upcoming cyberpunk cat game, "
'launches for PC, PlayStation 4 and PS5 on 19th July.',
action: const NavigateToArticleAction(
articleId: '36f4a017-d099-4fce-8727-1d9ca6a0398c',
),
);
final relatedArticles = [
postSmallBlock,
PostSmallBlock.fromJson(postSmallBlock.toJson()..['id'] = 'newId'),
];
setUp(() {
articleBloc = MockArticleBloc();
appBloc = MockAppBloc();
});
testWidgets(
'renders relatedArticles '
'when article is not preview', (tester) async {
final user = MockUser();
when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.premium);
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: false,
),
);
when(() => appBloc.state).thenReturn(
AppState.authenticated(user),
);
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
for (final article in relatedArticles) {
expect(
find.byWidgetPredicate(
(widget) => widget is CategoryFeedItem && widget.block == article,
),
findsOneWidget,
);
}
});
testWidgets(
'renders only ArticleComments when '
'relatedArticles is empty', (tester) async {
when(() => articleBloc.state).thenAnswer(
(invocation) => ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: [],
hasReachedArticleViewsLimit: false,
),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: CustomScrollView(slivers: [ArticleTrailingContent()]),
),
);
expect(find.byType(CategoryFeedItem), findsNothing);
expect(find.byType(ArticleComments), findsOneWidget);
});
group('when article is preview', () {
setUp(() {
final user = MockUser();
when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.none);
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: true,
),
);
when(() => appBloc.state).thenReturn(AppState.authenticated(user));
});
testWidgets('does not render relatedArticles', (tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
expect(find.byType(CategoryFeedItem), findsNothing);
});
testWidgets('does not render ArticleComments', (tester) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
expect(find.byType(ArticleComments), findsNothing);
});
testWidgets(
'renders SubscribeModal '
'when article is premium and user is not a subscriber',
(tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: true,
isPremium: true,
),
);
VisibilityDetectorController.instance.updateInterval = Duration.zero;
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
expect(find.byType(SubscribeModal), findsOneWidget);
expect(find.byType(SubscribeWithArticleLimitModal), findsNothing);
});
testWidgets(
'does not render SubscribeModal '
'when article is premium and user is a subscriber', (tester) async {
final user = MockUser();
when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.premium);
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: true,
isPremium: true,
),
);
when(() => appBloc.state).thenReturn(
AppState.authenticated(
user,
),
);
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
expect(find.byType(SubscribeModal), findsNothing);
expect(find.byType(SubscribeWithArticleLimitModal), findsNothing);
});
testWidgets(
'renders SubscribeWithArticleLimitModal '
'when article is not premium '
'and user has reached article views limit '
'and user is not a subscriber', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: true,
hasReachedArticleViewsLimit: true,
),
);
await tester.runAsync(() async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
});
expect(find.byType(SubscribeWithArticleLimitModal), findsOneWidget);
expect(find.byType(SubscribeModal), findsNothing);
});
testWidgets(
'does not render SubscribeWithArticleLimitModal '
'when article is not premium '
'and user has reached article views limit '
'and user is a subscriber', (tester) async {
final user = MockUser();
when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.premium);
when(() => articleBloc.state).thenReturn(
ArticleState(
content: const [
TextCaptionBlock(text: 'text', color: TextCaptionColor.normal),
TextParagraphBlock(text: 'text'),
],
status: ArticleStatus.populated,
hasMoreContent: false,
relatedArticles: relatedArticles,
isPreview: true,
hasReachedArticleViewsLimit: true,
),
);
when(() => appBloc.state).thenReturn(
AppState.authenticated(user),
);
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(value: articleBloc),
BlocProvider.value(value: appBloc),
],
child: CustomScrollView(
slivers: [ArticleTrailingContent()],
),
),
);
expect(find.byType(SubscribeWithArticleLimitModal), findsNothing);
expect(find.byType(SubscribeModal), findsNothing);
});
});
});
}
| news_toolkit/flutter_news_example/test/article/widgets/article_trailing_content_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_trailing_content_test.dart",
"repo_id": "news_toolkit",
"token_count": 5089
} | 904 |
import 'package:ads_consent_client/ads_consent_client.dart';
import 'package:article_repository/article_repository.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_news_example/ads/ads.dart';
import 'package:flutter_news_example/analytics/analytics.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/theme_selector/theme_selector.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:mockingjay/mockingjay.dart'
show MockNavigator, MockNavigatorProvider;
import 'package:mocktail/mocktail.dart';
import 'package:news_repository/news_repository.dart';
import 'package:notifications_repository/notifications_repository.dart';
import 'package:user_repository/user_repository.dart';
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {
@override
AppState get state => const AppState.unauthenticated();
}
class MockAnalyticsBloc extends MockBloc<AnalyticsEvent, AnalyticsState>
implements AnalyticsBloc {}
class MockThemeModeBloc extends MockBloc<ThemeModeEvent, ThemeMode>
implements ThemeModeBloc {
@override
ThemeMode get state => ThemeMode.system;
}
class MockFullScreenAdsBloc
extends MockBloc<FullScreenAdsEvent, FullScreenAdsState>
implements FullScreenAdsBloc {
@override
FullScreenAdsState get state => const FullScreenAdsState.initial();
}
class MockUserRepository extends Mock implements UserRepository {
@override
Stream<Uri> get incomingEmailLinks => const Stream.empty();
@override
Stream<User> get user => const Stream.empty();
}
class MockNewsRepository extends Mock implements NewsRepository {}
class MockNotificationsRepository extends Mock
implements NotificationsRepository {}
class MockArticleRepository extends Mock implements ArticleRepository {
@override
Future<ArticleViews> fetchArticleViews() async => ArticleViews(0, null);
@override
Future<void> incrementArticleViews() async {}
@override
Future<void> resetArticleViews() async {}
}
class MockInAppPurchaseRepository extends Mock
implements InAppPurchaseRepository {}
class MockAdsConsentClient extends Mock implements AdsConsentClient {}
extension AppTester on WidgetTester {
Future<void> pumpApp(
Widget widgetUnderTest, {
AppBloc? appBloc,
AnalyticsBloc? analyticsBloc,
FullScreenAdsBloc? fullScreenAdsBloc,
UserRepository? userRepository,
NewsRepository? newsRepository,
NotificationsRepository? notificationRepository,
ArticleRepository? articleRepository,
InAppPurchaseRepository? inAppPurchaseRepository,
AdsConsentClient? adsConsentClient,
TargetPlatform? platform,
ThemeModeBloc? themeModeBloc,
NavigatorObserver? navigatorObserver,
MockNavigator? navigator,
}) async {
await pumpWidget(
MultiRepositoryProvider(
providers: [
RepositoryProvider.value(
value: userRepository ?? MockUserRepository(),
),
RepositoryProvider.value(
value: newsRepository ?? MockNewsRepository(),
),
RepositoryProvider.value(
value: notificationRepository ?? MockNotificationsRepository(),
),
RepositoryProvider.value(
value: articleRepository ?? MockArticleRepository(),
),
RepositoryProvider.value(
value: inAppPurchaseRepository ?? MockInAppPurchaseRepository(),
),
RepositoryProvider.value(
value: adsConsentClient ?? MockAdsConsentClient(),
),
],
child: MultiBlocProvider(
providers: [
BlocProvider.value(value: appBloc ?? MockAppBloc()),
BlocProvider.value(value: analyticsBloc ?? MockAnalyticsBloc()),
BlocProvider.value(value: themeModeBloc ?? MockThemeModeBloc()),
BlocProvider.value(
value: fullScreenAdsBloc ?? MockFullScreenAdsBloc(),
),
],
child: MaterialApp(
title: 'Flutter News Example',
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: Theme(
data: ThemeData(platform: platform),
child: navigator == null
? Scaffold(body: widgetUnderTest)
: MockNavigatorProvider(
navigator: navigator,
child: Scaffold(body: widgetUnderTest),
),
),
navigatorObservers: [
if (navigatorObserver != null) navigatorObserver
],
),
),
),
);
await pump();
}
}
| news_toolkit/flutter_news_example/test/helpers/pump_app.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/helpers/pump_app.dart",
"repo_id": "news_toolkit",
"token_count": 1995
} | 905 |
import 'package:email_launcher/email_launcher.dart';
import 'package:flutter_news_example/magic_link_prompt/magic_link_prompt.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockEmailLauncher extends Mock implements EmailLauncher {}
void main() {
const testEmail = '[email protected]';
late EmailLauncher emailLauncher;
setUp(() {
emailLauncher = MockEmailLauncher();
});
group('MagicLinkPromptView', () {
group('renders', () {
testWidgets('MagicLinkPromptHeader', (tester) async {
await tester.pumpApp(const MagicLinkPromptView(email: testEmail));
expect(find.byType(MagicLinkPromptHeader), findsOneWidget);
});
testWidgets('MagicLinkPromptSubtitle', (tester) async {
await tester.pumpApp(const MagicLinkPromptView(email: testEmail));
expect(find.byType(MagicLinkPromptSubtitle), findsOneWidget);
});
testWidgets('MagicLinkPromptOpenEmailButton', (tester) async {
await tester.pumpApp(const MagicLinkPromptView(email: testEmail));
expect(find.byType(MagicLinkPromptOpenEmailButton), findsOneWidget);
});
});
group('opens default email app', () {
testWidgets(
'when MagicLinkPromptOpenEmailButton is pressed',
(tester) async {
when(emailLauncher.launchEmailApp).thenAnswer((_) async {});
await tester.pumpApp(
MagicLinkPromptOpenEmailButton(
emailLauncher: emailLauncher,
),
);
await tester.tap(find.byType(MagicLinkPromptOpenEmailButton));
await tester.pumpAndSettle();
verify(emailLauncher.launchEmailApp).called(1);
},
);
});
});
}
| news_toolkit/flutter_news_example/test/magic_link_prompt/view/magic_link_prompt_view_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/magic_link_prompt/view/magic_link_prompt_view_test.dart",
"repo_id": "news_toolkit",
"token_count": 714
} | 906 |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/notification_preferences/notification_preferences.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
group('NotificationCategoryTile', () {
testWidgets('renders trailing', (tester) async {
await tester.pumpApp(
const NotificationCategoryTile(
title: 'title',
trailing: Icon(Icons.image),
),
);
expect(find.byType(Icon), findsOneWidget);
});
testWidgets('calls onTap on ListTile click', (tester) async {
final completer = Completer<void>();
await tester.pumpApp(
NotificationCategoryTile(
title: 'title',
trailing: const Icon(Icons.image),
onTap: completer.complete,
),
);
await tester.tap(find.byType(ListTile));
expect(completer.isCompleted, isTrue);
});
});
}
| news_toolkit/flutter_news_example/test/notification_preferences/widgets/notification_category_tile_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/notification_preferences/widgets/notification_category_tile_test.dart",
"repo_id": "news_toolkit",
"token_count": 406
} | 907 |
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
void main() {
group('SubscriptionsEvent', () {
group('SubscriptionsRequested', () {
test('supports value comparisons', () {
final event1 = SubscriptionsRequested();
final event2 = SubscriptionsRequested();
expect(event1, equals(event2));
});
});
group('SubscriptionPurchaseRequested', () {
test('supports value comparisons', () {
final event1 = SubscriptionPurchaseRequested(
subscription: const Subscription(
benefits: [],
cost: SubscriptionCost(
annual: 0,
monthly: 0,
),
id: '1',
name: SubscriptionPlan.none,
),
);
final event2 = SubscriptionPurchaseRequested(
subscription: const Subscription(
benefits: [],
cost: SubscriptionCost(
annual: 0,
monthly: 0,
),
id: '1',
name: SubscriptionPlan.none,
),
);
expect(event1, equals(event2));
});
});
group('SubscriptionPurchaseCompleted', () {
test('supports value comparisons', () {
final event1 = SubscriptionPurchaseCompleted(
subscription: const Subscription(
benefits: [],
cost: SubscriptionCost(
annual: 0,
monthly: 0,
),
id: '1',
name: SubscriptionPlan.none,
),
);
final event2 = SubscriptionPurchaseCompleted(
subscription: const Subscription(
benefits: [],
cost: SubscriptionCost(
annual: 0,
monthly: 0,
),
id: '1',
name: SubscriptionPlan.none,
),
);
expect(event1, equals(event2));
});
});
group('SubscriptionPurchaseUpdated', () {
test('supports value comparisons', () {
final event1 = SubscriptionPurchaseUpdated(
purchase: const PurchaseCanceled(),
);
final event2 = SubscriptionPurchaseUpdated(
purchase: const PurchaseCanceled(),
);
expect(event1, equals(event2));
});
});
});
}
| news_toolkit/flutter_news_example/test/subscriptions/dialog/bloc/subscriptions_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/subscriptions/dialog/bloc/subscriptions_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 1145
} | 908 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/user_profile/user_profile.dart';
import 'package:flutter_news_example_api/client.dart' hide User;
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:user_repository/user_repository.dart';
import '../../helpers/helpers.dart';
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
class MockUser extends Mock implements User {}
class MockNavigatorObserver extends Mock implements NavigatorObserver {}
class MockRoute extends Mock implements Route<dynamic> {}
void main() {
group('UserProfileButton', () {
late AppBloc appBloc;
late User user;
setUp(() {
appBloc = MockAppBloc();
user = User(id: 'id', subscriptionPlan: SubscriptionPlan.none);
});
setUpAll(() {
registerFallbackValue(MockRoute());
});
testWidgets(
'renders LoginButton '
'when user is unauthenticated', (tester) async {
whenListen(
appBloc,
Stream.value(AppState.unauthenticated()),
initialState: AppState.unauthenticated(),
);
await tester.pumpApp(
UserProfileButton(),
appBloc: appBloc,
);
expect(find.byType(LoginButton), findsOneWidget);
expect(find.byType(OpenProfileButton), findsNothing);
});
testWidgets(
'renders OpenProfileButton '
'when user is authenticated', (tester) async {
whenListen(
appBloc,
Stream.value(AppState.authenticated(user)),
initialState: AppState.authenticated(user),
);
await tester.pumpApp(
UserProfileButton(),
appBloc: appBloc,
);
expect(find.byType(OpenProfileButton), findsOneWidget);
expect(find.byType(LoginButton), findsNothing);
});
testWidgets(
'navigates to UserProfilePage '
'when tapped on OpenProfileButton', (tester) async {
whenListen(
appBloc,
Stream.value(AppState.authenticated(user)),
initialState: AppState.authenticated(user),
);
await tester.pumpApp(
UserProfileButton(),
appBloc: appBloc,
);
await tester.tap(find.byType(OpenProfileButton));
await tester.pumpAndSettle();
expect(find.byType(UserProfilePage), findsOneWidget);
});
testWidgets(
'renders LoginButton '
'when user is unauthenticated', (tester) async {
whenListen(
appBloc,
Stream.value(AppState.unauthenticated()),
initialState: AppState.unauthenticated(),
);
await tester.pumpApp(
UserProfileButton(),
appBloc: appBloc,
);
expect(find.byType(LoginButton), findsOneWidget);
expect(find.byType(OpenProfileButton), findsNothing);
});
testWidgets(
'shows LoginModal '
'when tapped on LoginButton', (tester) async {
whenListen(
appBloc,
Stream.value(AppState.unauthenticated()),
initialState: AppState.unauthenticated(),
);
await tester.pumpApp(
UserProfileButton(),
appBloc: appBloc,
);
await tester.tap(find.byType(LoginButton));
await tester.pumpAndSettle();
expect(find.byType(LoginModal), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/test/user_profile/widgets/user_profile_button_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/user_profile/widgets/user_profile_button_test.dart",
"repo_id": "news_toolkit",
"token_count": 1448
} | 909 |
This directory contains a partial snapshot of an old Flutter project; it is
intended to replace the corresponding parts of a newly Flutter-created project
to allow testing plugin builds with a legacy project.
It was originally created with Flutter 2.0.6. In general the guidelines are:
- Pieces here should be largely self-contained rather than portions of
major project components; for instance, it currently contains the entire
`android/` directory from a legacy project, rather than a subset of it
which would be combined with a subset of a new project's `android/`
directory. This is to avoid random breakage in the future due to
conflicts between those subsets. For instance, we could probably get
away with not including android/app/src/main/res for a while, and
instead layer in the versions from a new project, but then someday
if the resources were renamed, there would be dangling references to
the old resources in files that are included here.
- Updates over time should be minimal. We don't expect that an unchanged
project will keep working forever, but this directory should simulate
a developer who has done the bare minimum to keep their project working
as they have updated Flutter.
- Updates should be logged below.
The reason for the hybrid model, rather than checking in a full legacy
project, is to minimize unnecessary maintenance work. E.g., there's no
need to manually keep Dart code updated for Flutter changes just to
test legacy native Android build behaviors.
## Manual changes to files
The following are the changes relative to running:
```bash
flutter create -a java all_packages
```
and then deleting everything but `android/` from it:
- Added license boilerplate.
- Replaced `jcenter` in build.gradle with `mavenCentral`, due to the
jcenter.bintray.com shutdown.
- Update `compileSdkVersion` from 30 to 33 to maintain compatibility
with plugins that use API 34.
- Updates `gradle-wrapper.properties` from `6.7` to `6.7.1`, to add
support for the Kotlin gradle plugin. If a user runs into this
error, the error message is clear on how to upgrade.
| packages/.ci/legacy_project/README.md/0 | {
"file_path": "packages/.ci/legacy_project/README.md",
"repo_id": "packages",
"token_count": 512
} | 910 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
# Does a sanity check that packages at least pass analysis on the N-1 and N-2
# versions of Flutter stable if the package claims to support that version.
# This is to minimize accidentally making changes that break old versions
# (which we don't commit to supporting, but don't want to actively break)
# without updating the constraints.
# See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#supported-flutter-versions
- name: analyze - legacy
script: .ci/scripts/analyze_legacy.sh
| packages/.ci/targets/analyze_legacy.yaml/0 | {
"file_path": "packages/.ci/targets/analyze_legacy.yaml",
"repo_id": "packages",
"token_count": 195
} | 911 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: tool unit tests
script: .ci/scripts/plugin_tools_tests.sh
- name: format
script: .ci/scripts/tool_runner.sh
# Skip Swift formatting on Linux builders.
args: ["format", "--fail-on-change", "--no-swift"]
always: true
- name: license validation
script: .ci/scripts/tool_runner.sh
args: ["license-check"]
always: true
# The major and minor version here should match the lowest version analyzed
# in legacy version analysis (.ci.yaml analyze_legacy).
- name: pubspec validation
script: .ci/scripts/tool_runner.sh
args:
- "pubspec-check"
- "--min-min-flutter-version=3.13.0"
- "--allow-dependencies=script/configs/allowed_unpinned_deps.yaml"
- "--allow-pinned-dependencies=script/configs/allowed_pinned_deps.yaml"
always: true
- name: README validation
script: .ci/scripts/tool_runner.sh
args: ["readme-check"]
always: true
# Re-run with --require-excerpts, skipping packages that still need
# to be converted. Once https://github.com/flutter/flutter/issues/102679
# has been fixed, this can be removed --require-excerpts added to the
# run above.
- name: README snippet configuration validation
script: .ci/scripts/tool_runner.sh
args: ["readme-check", "--require-excerpts", "--exclude=script/configs/temp_exclude_excerpt.yaml"]
always: true
- name: README snippet validation
script: .ci/scripts/tool_runner.sh
args: ["update-excerpts", "--fail-on-change"]
always: true
- name: Gradle validation
script: .ci/scripts/tool_runner.sh
args: ["gradle-check"]
always: true
- name: Repository-level package metadata validation
script: .ci/scripts/tool_runner.sh
args: ["check-repo-package-info"]
always: true
- name: Dependabot coverage validation
script: .ci/scripts/tool_runner.sh
args: ["dependabot-check"]
always: true
- name: CHANGELOG and version validation
script: .ci/scripts/check_version.sh
always: true
- name: federated safety check
script: .ci/scripts/check_federated_safety.sh
always: true
# This is the slowest test, so prefer keeping it last.
- name: publishability
script: .ci/scripts/tool_runner.sh
args: ["publish-check", "--allow-pre-release"]
always: true
| packages/.ci/targets/repo_checks.yaml/0 | {
"file_path": "packages/.ci/targets/repo_checks.yaml",
"repo_id": "packages",
"token_count": 882
} | 912 |
## Welcome
For an introduction to contributing to Flutter, see [our contributor
guide](https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md).
Additional resources specific to the packages repository:
- [Setting up the Packages development
environment](https://github.com/flutter/flutter/wiki/Setting-up-the-Packages-development-environment),
which covers the setup process for this repository.
- [Packages repository structure](https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure),
to get an overview of how this repository is laid out.
- [Contributing to Plugins and Packages](https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages),
for more information about how to make PRs for this repository, especially when
changing federated plugins.
- [Plugin tests](https://github.com/flutter/flutter/wiki/Plugin-Tests), which explains
the different kinds of tests used for plugins, where to find them, and how to run them.
As explained in the Flutter guide,
[**PRs need tests**](https://github.com/flutter/flutter/wiki/Tree-hygiene#tests), so
this is critical to read before submitting a plugin PR.
### Code review processes and automation
PRs will automatically be assigned to
[code owners](https://github.com/flutter/packages/blob/main/CODEOWNERS)
for review.
If a code owner is creating a PR, they should explicitly pick another
[Flutter team member](https://github.com/flutter/flutter/wiki/Contributor-access)
as a code reviewer.
### Style
Flutter packages and plugins follow Google style—or Flutter style for Dart—for the languages they
use, and use auto-formatters:
- [Dart](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo) formatted
with `dart format`
- [C++](https://google.github.io/styleguide/cppguide.html) formatted with `clang-format`
- **Note**: The Linux plugins generally follow idiomatic GObject-based C
style. See [the engine style
notes](https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style)
for more details, and exceptions.
- [Java](https://google.github.io/styleguide/javaguide.html) formatted with
`google-java-format`
- [Kotlin](https://developer.android.com/kotlin/style-guide) formatted with
`ktfmt`
- [Objective-C](https://google.github.io/styleguide/objcguide.html) formatted with
`clang-format`
- [Swift](https://google.github.io/swift/) formatted with `swift-format`
### Releasing
If you are a team member landing a PR, or just want to know what the release
process is for package changes, see [the release
documentation](https://github.com/flutter/flutter/wiki/Releasing-a-Plugin-or-Package).
| packages/CONTRIBUTING.md/0 | {
"file_path": "packages/CONTRIBUTING.md",
"repo_id": "packages",
"token_count": 797
} | 913 |
name: animations_example
description: A catalog containing example animations from package:animations.
publish_to: none
version: 0.0.1
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
animations:
path: ../../animations
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/avatar_logo.png
- assets/placeholder_image.png
| packages/packages/animations/example/pubspec.yaml/0 | {
"file_path": "packages/packages/animations/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 182
} | 914 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:animations/src/fade_through_transition.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition',
(WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
);
await tester.pumpWidget(
const FadeThroughPageTransitionsBuilder().buildTransitions<void>(
null,
null,
animation,
secondaryAnimation,
const Placeholder(),
));
expect(find.byType(FadeThroughTransition), findsOneWidget);
});
testWidgets('FadeThroughTransition runs forward',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
// Bottom route is full size and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
// top route is at 95% of full size and not visible yet.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump to half-way through the fade out (total duration is 300ms, 6/12th of
// that are fade out, so half-way is 300 * 6/12 / 2 = 45ms.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is fading out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomOpacity, lessThan(1.0));
expect(bottomOpacity, greaterThan(0.0));
// Top route is still invisible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Let's jump to the end of the fade-out.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is completely faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is still invisible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Let's jump to the middle of the fade-in.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(topRoute), findsOneWidget);
final double topScale = _getScale(topRoute, tester);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topScale, greaterThan(0.92));
expect(topScale, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
expect(topOpacity, lessThan(1.0));
// Let's jump to the end of the animation.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route fully scaled in and visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(bottomRoute), findsNothing);
expect(find.text(topRoute), findsOneWidget);
});
testWidgets('FadeThroughTransition runs backwards',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
navigator.currentState!.pop();
await tester.pump();
// Top route is full size and fully visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
// Bottom route is at 95% of full size and not visible yet.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 0.92);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump to half-way through the fade out (total duration is 300ms, 6/12th of
// that are fade out, so half-way is 300 * 6/12 / 2 = 45ms.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is fading out.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topOpacity, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
// Top route is still invisible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 0.92);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Let's jump to the end of the fade-out.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is completely faded out.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is still invisible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getScale(bottomRoute, tester),
moreOrLessEquals(0.92, epsilon: 0.005),
);
expect(
_getOpacity(bottomRoute, tester),
moreOrLessEquals(0.0, epsilon: 0.005),
);
// Let's jump to the middle of the fade-in.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(bottomRoute), findsOneWidget);
final double bottomScale = _getScale(bottomRoute, tester);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomScale, greaterThan(0.96));
expect(bottomScale, lessThan(1.0));
expect(bottomOpacity, greaterThan(0.1));
expect(bottomOpacity, lessThan(1.0));
// Let's jump to the end of the animation.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route fully scaled in and visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
});
testWidgets('FadeThroughTransition does not jump when interrupted',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
// Bottom route is fully faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(topRoute), findsOneWidget);
final double topScale = _getScale(topRoute, tester);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topScale, greaterThan(0.92));
expect(topScale, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
expect(topOpacity, lessThan(1.0));
// Interrupt the transition with a pop.
navigator.currentState!.pop();
await tester.pump();
// Noting changed.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), topScale);
expect(_getOpacity(topRoute, tester), topOpacity);
// Jump to the halfway point.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomOpacity, greaterThan(0.0));
expect(bottomOpacity, lessThan(1.0));
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), lessThan(topScale));
expect(_getOpacity(topRoute, tester), lessThan(topOpacity));
// Jump to the end.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
});
testWidgets('State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
return _StatefulTestWidget(
key: ValueKey<String?>(settings.name),
name: settings.name,
);
},
),
);
final _StatefulTestWidgetState bottomState =
tester.state(find.byKey(const ValueKey<String?>(bottomRoute)));
expect(bottomState.widget.name, bottomRoute);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
const ValueKey<String?>(bottomRoute),
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
navigator.currentState!.pop();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
testWidgets('should keep state', (WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: FadeThroughTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state = tester.state(
find.byType(_StatefulTestWidget),
);
expect(state, isNotNull);
animation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
animation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
}
double _getOpacity(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(FadeTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final FadeTransition transition = widget as FadeTransition;
return a * transition.opacity.value;
});
}
double _getScale(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(ScaleTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final ScaleTransition transition = widget as ScaleTransition;
return a * transition.scale.value;
});
}
class _TestWidget extends StatelessWidget {
const _TestWidget({this.navigatorKey, this.contentBuilder});
final Key? navigatorKey;
final _ContentBuilder? contentBuilder;
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey as GlobalKey<NavigatorState>?,
theme: ThemeData(
platform: TargetPlatform.android,
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeThroughPageTransitionsBuilder(),
},
),
),
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
return contentBuilder != null
? contentBuilder!(settings)
: Center(
key: ValueKey<String?>(settings.name),
child: Text(settings.name!),
);
},
);
},
);
}
}
class _StatefulTestWidget extends StatefulWidget {
const _StatefulTestWidget({super.key, this.name});
final String? name;
@override
State<_StatefulTestWidget> createState() => _StatefulTestWidgetState();
}
class _StatefulTestWidgetState extends State<_StatefulTestWidget> {
@override
Widget build(BuildContext context) {
return Text(widget.name!);
}
}
typedef _ContentBuilder = Widget Function(RouteSettings settings);
| packages/packages/animations/test/fade_through_transition_test.dart/0 | {
"file_path": "packages/packages/animations/test/fade_through_transition_test.dart",
"repo_id": "packages",
"token_count": 6765
} | 915 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:camera/camera.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
List<CameraDescription> get mockAvailableCameras => <CameraDescription>[
const CameraDescription(
name: 'camBack',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
const CameraDescription(
name: 'camFront',
lensDirection: CameraLensDirection.front,
sensorOrientation: 180),
];
int get mockInitializeCamera => 13;
CameraInitializedEvent get mockOnCameraInitializedEvent =>
const CameraInitializedEvent(
13,
75,
75,
ExposureMode.auto,
true,
FocusMode.auto,
true,
);
DeviceOrientationChangedEvent get mockOnDeviceOrientationChangedEvent =>
const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
CameraClosingEvent get mockOnCameraClosingEvent => const CameraClosingEvent(13);
CameraErrorEvent get mockOnCameraErrorEvent =>
const CameraErrorEvent(13, 'closing');
XFile mockTakePicture = XFile('foo/bar.png');
XFile mockVideoRecordingXFile = XFile('foo/bar.mpeg');
bool mockPlatformException = false;
void main() {
WidgetsFlutterBinding.ensureInitialized();
group('camera', () {
test('debugCheckIsDisposed should not throw assertion error when disposed',
() {
const MockCameraDescription description = MockCameraDescription();
final CameraController controller = CameraController(
description,
ResolutionPreset.low,
);
controller.dispose();
expect(controller.debugCheckIsDisposed, returnsNormally);
});
test('debugCheckIsDisposed should throw assertion error when not disposed',
() {
const MockCameraDescription description = MockCameraDescription();
final CameraController controller = CameraController(
description,
ResolutionPreset.low,
);
expect(
() => controller.debugCheckIsDisposed(),
throwsAssertionError,
);
});
test('availableCameras() has camera', () async {
CameraPlatform.instance = MockCameraPlatform();
final List<CameraDescription> camList = await availableCameras();
expect(camList, equals(mockAvailableCameras));
});
});
group('$CameraController', () {
setUpAll(() {
CameraPlatform.instance = MockCameraPlatform();
});
test('Can be initialized', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
expect(cameraController.value.aspectRatio, 1);
expect(cameraController.value.previewSize, const Size(75, 75));
expect(cameraController.value.isInitialized, isTrue);
});
test('can be disposed', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
expect(cameraController.value.aspectRatio, 1);
expect(cameraController.value.previewSize, const Size(75, 75));
expect(cameraController.value.isInitialized, isTrue);
await cameraController.dispose();
verify(CameraPlatform.instance.dispose(13)).called(1);
});
test('initialize() throws CameraException when disposed', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
expect(cameraController.value.aspectRatio, 1);
expect(cameraController.value.previewSize, const Size(75, 75));
expect(cameraController.value.isInitialized, isTrue);
await cameraController.dispose();
verify(CameraPlatform.instance.dispose(13)).called(1);
expect(
cameraController.initialize,
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'Error description',
'initialize was called on a disposed CameraController',
)));
});
test('initialize() throws $CameraException on $PlatformException ',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
mockPlatformException = true;
expect(
cameraController.initialize,
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'foo',
'bar',
)));
mockPlatformException = false;
});
test('initialize() sets imageFormat', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max,
imageFormatGroup: ImageFormatGroup.yuv420,
);
await cameraController.initialize();
verify(CameraPlatform.instance
.initializeCamera(13, imageFormatGroup: ImageFormatGroup.yuv420))
.called(1);
});
test('setDescription waits for initialize before calling dispose',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90,
),
ResolutionPreset.max,
imageFormatGroup: ImageFormatGroup.bgra8888,
);
final Completer<void> initializeCompleter = Completer<void>();
when(CameraPlatform.instance.initializeCamera(
mockInitializeCamera,
imageFormatGroup: ImageFormatGroup.bgra8888,
)).thenAnswer(
(_) => initializeCompleter.future,
);
unawaited(cameraController.initialize());
final Future<void> setDescriptionFuture = cameraController.setDescription(
const CameraDescription(
name: 'cam2',
lensDirection: CameraLensDirection.front,
sensorOrientation: 90),
);
verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera));
initializeCompleter.complete();
await setDescriptionFuture;
verify(CameraPlatform.instance.dispose(mockInitializeCamera));
});
test('prepareForVideoRecording() calls $CameraPlatform ', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.prepareForVideoRecording();
verify(CameraPlatform.instance.prepareForVideoRecording()).called(1);
});
test('takePicture() throws $CameraException when uninitialized ', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
expect(
cameraController.takePicture(),
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Uninitialized CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'takePicture() was called on an uninitialized CameraController.',
),
),
);
});
test('takePicture() throws $CameraException when takePicture is true',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isTakingPicture: true);
expect(
cameraController.takePicture(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'Previous capture has not returned yet.',
'takePicture was called before the previous capture returned.',
)));
});
test('takePicture() returns $XFile', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
final XFile xFile = await cameraController.takePicture();
expect(xFile.path, mockTakePicture.path);
});
test('takePicture() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
mockPlatformException = true;
expect(
cameraController.takePicture(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'foo',
'bar',
)));
mockPlatformException = false;
});
test('startVideoRecording() throws $CameraException when uninitialized',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
expect(
cameraController.startVideoRecording(),
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Uninitialized CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'startVideoRecording() was called on an uninitialized CameraController.',
),
),
);
});
test('startVideoRecording() throws $CameraException when recording videos',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isRecordingVideo: true);
expect(
cameraController.startVideoRecording(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'A video recording is already started.',
'startVideoRecording was called when a recording is already started.',
)));
});
test('getMaxZoomLevel() throws $CameraException when uninitialized',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
expect(
cameraController.getMaxZoomLevel,
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Uninitialized CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'getMaxZoomLevel() was called on an uninitialized CameraController.',
),
),
);
});
test('getMaxZoomLevel() throws $CameraException when disposed', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.dispose();
expect(
cameraController.getMaxZoomLevel,
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Disposed CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'getMaxZoomLevel() was called on a disposed CameraController.',
),
),
);
});
test(
'getMaxZoomLevel() throws $CameraException when a platform exception occured.',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera))
.thenThrow(CameraException(
'TEST_ERROR',
'This is a test error messge',
));
expect(
cameraController.getMaxZoomLevel,
throwsA(isA<CameraException>()
.having(
(CameraException error) => error.code, 'code', 'TEST_ERROR')
.having(
(CameraException error) => error.description,
'description',
'This is a test error messge',
)));
});
test('getMaxZoomLevel() returns max zoom level.', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera))
.thenAnswer((_) => Future<double>.value(42.0));
final double maxZoomLevel = await cameraController.getMaxZoomLevel();
expect(maxZoomLevel, 42.0);
});
test('getMinZoomLevel() throws $CameraException when uninitialized',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
expect(
cameraController.getMinZoomLevel,
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Uninitialized CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'getMinZoomLevel() was called on an uninitialized CameraController.',
),
),
);
});
test('getMinZoomLevel() throws $CameraException when disposed', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.dispose();
expect(
cameraController.getMinZoomLevel,
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Disposed CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'getMinZoomLevel() was called on a disposed CameraController.',
),
),
);
});
test(
'getMinZoomLevel() throws $CameraException when a platform exception occured.',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera))
.thenThrow(CameraException(
'TEST_ERROR',
'This is a test error messge',
));
expect(
cameraController.getMinZoomLevel,
throwsA(isA<CameraException>()
.having(
(CameraException error) => error.code, 'code', 'TEST_ERROR')
.having(
(CameraException error) => error.description,
'description',
'This is a test error messge',
)));
});
test('getMinZoomLevel() returns max zoom level.', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera))
.thenAnswer((_) => Future<double>.value(42.0));
final double maxZoomLevel = await cameraController.getMinZoomLevel();
expect(maxZoomLevel, 42.0);
});
test('setZoomLevel() throws $CameraException when uninitialized', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
expect(
() => cameraController.setZoomLevel(42.0),
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Uninitialized CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'setZoomLevel() was called on an uninitialized CameraController.',
),
),
);
});
test('setZoomLevel() throws $CameraException when disposed', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.dispose();
expect(
() => cameraController.setZoomLevel(42.0),
throwsA(
isA<CameraException>()
.having(
(CameraException error) => error.code,
'code',
'Disposed CameraController',
)
.having(
(CameraException error) => error.description,
'description',
'setZoomLevel() was called on a disposed CameraController.',
),
),
);
});
test(
'setZoomLevel() throws $CameraException when a platform exception occured.',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0))
.thenThrow(CameraException(
'TEST_ERROR',
'This is a test error messge',
));
expect(
() => cameraController.setZoomLevel(42),
throwsA(isA<CameraException>()
.having(
(CameraException error) => error.code, 'code', 'TEST_ERROR')
.having(
(CameraException error) => error.description,
'description',
'This is a test error messge',
)));
reset(CameraPlatform.instance);
});
test(
'setZoomLevel() completes and calls method channel with correct value.',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.setZoomLevel(42.0);
verify(CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0))
.called(1);
});
test('setFlashMode() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.setFlashMode(FlashMode.always);
verify(CameraPlatform.instance
.setFlashMode(cameraController.cameraId, FlashMode.always))
.called(1);
});
test('setFlashMode() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.setFlashMode(cameraController.cameraId, FlashMode.always))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.setFlashMode(FlashMode.always),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('setExposureMode() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.setExposureMode(ExposureMode.auto);
verify(CameraPlatform.instance
.setExposureMode(cameraController.cameraId, ExposureMode.auto))
.called(1);
});
test('setExposureMode() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.setExposureMode(cameraController.cameraId, ExposureMode.auto))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.setExposureMode(ExposureMode.auto),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('setExposurePoint() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.setExposurePoint(const Offset(0.5, 0.5));
verify(CameraPlatform.instance.setExposurePoint(
cameraController.cameraId, const Point<double>(0.5, 0.5)))
.called(1);
});
test('setExposurePoint() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.setExposurePoint(
cameraController.cameraId, const Point<double>(0.5, 0.5)))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.setExposurePoint(const Offset(0.5, 0.5)),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('getMinExposureOffset() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenAnswer((_) => Future<double>.value(0.0));
await cameraController.getMinExposureOffset();
verify(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.called(1);
});
test('getMinExposureOffset() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenThrow(
CameraException(
'TEST_ERROR',
'This is a test error message',
),
);
expect(
cameraController.getMinExposureOffset(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('getMaxExposureOffset() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenAnswer((_) => Future<double>.value(1.0));
await cameraController.getMaxExposureOffset();
verify(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.called(1);
});
test('getMaxExposureOffset() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenThrow(
CameraException(
'TEST_ERROR',
'This is a test error message',
),
);
expect(
cameraController.getMaxExposureOffset(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('getExposureOffsetStepSize() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenAnswer((_) => Future<double>.value(0.0));
await cameraController.getExposureOffsetStepSize();
verify(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.called(1);
});
test(
'getExposureOffsetStepSize() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenThrow(
CameraException(
'TEST_ERROR',
'This is a test error message',
),
);
expect(
cameraController.getExposureOffsetStepSize(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('setExposureOffset() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => -1.0);
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => 2.0);
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenAnswer((_) async => 1.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 1.0))
.thenAnswer((_) async => 1.0);
await cameraController.setExposureOffset(1.0);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 1.0))
.called(1);
});
test('setExposureOffset() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => -1.0);
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => 2.0);
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenAnswer((_) async => 1.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 1.0))
.thenThrow(
CameraException(
'TEST_ERROR',
'This is a test error message',
),
);
expect(
cameraController.setExposureOffset(1.0),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test(
'setExposureOffset() throws $CameraException when offset is out of bounds',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => -1.0);
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => 2.0);
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenAnswer((_) async => 1.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.0))
.thenAnswer((_) async => 0.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -1.0))
.thenAnswer((_) async => 0.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 2.0))
.thenAnswer((_) async => 0.0);
expect(
cameraController.setExposureOffset(3.0),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'exposureOffsetOutOfBounds',
'The provided exposure offset was outside the supported range for this device.',
)));
expect(
cameraController.setExposureOffset(-2.0),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'exposureOffsetOutOfBounds',
'The provided exposure offset was outside the supported range for this device.',
)));
await cameraController.setExposureOffset(0.0);
await cameraController.setExposureOffset(-1.0);
await cameraController.setExposureOffset(2.0);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.0))
.called(1);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -1.0))
.called(1);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 2.0))
.called(1);
});
test('setExposureOffset() rounds offset to nearest step', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.getMinExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => -1.2);
when(CameraPlatform.instance
.getMaxExposureOffset(cameraController.cameraId))
.thenAnswer((_) async => 1.2);
when(CameraPlatform.instance
.getExposureOffsetStepSize(cameraController.cameraId))
.thenAnswer((_) async => 0.4);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -1.2))
.thenAnswer((_) async => -1.2);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -0.8))
.thenAnswer((_) async => -0.8);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -0.4))
.thenAnswer((_) async => -0.4);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.0))
.thenAnswer((_) async => 0.0);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.4))
.thenAnswer((_) async => 0.4);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.8))
.thenAnswer((_) async => 0.8);
when(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 1.2))
.thenAnswer((_) async => 1.2);
await cameraController.setExposureOffset(1.2);
await cameraController.setExposureOffset(-1.2);
await cameraController.setExposureOffset(0.1);
await cameraController.setExposureOffset(0.2);
await cameraController.setExposureOffset(0.3);
await cameraController.setExposureOffset(0.4);
await cameraController.setExposureOffset(0.5);
await cameraController.setExposureOffset(0.6);
await cameraController.setExposureOffset(0.7);
await cameraController.setExposureOffset(-0.1);
await cameraController.setExposureOffset(-0.2);
await cameraController.setExposureOffset(-0.3);
await cameraController.setExposureOffset(-0.4);
await cameraController.setExposureOffset(-0.5);
await cameraController.setExposureOffset(-0.6);
await cameraController.setExposureOffset(-0.7);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.8))
.called(2);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -0.8))
.called(2);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.0))
.called(2);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, 0.4))
.called(4);
verify(CameraPlatform.instance
.setExposureOffset(cameraController.cameraId, -0.4))
.called(4);
});
test('pausePreview() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value = cameraController.value
.copyWith(deviceOrientation: DeviceOrientation.portraitUp);
await cameraController.pausePreview();
verify(CameraPlatform.instance.pausePreview(cameraController.cameraId))
.called(1);
expect(cameraController.value.isPreviewPaused, equals(true));
expect(cameraController.value.previewPauseOrientation,
DeviceOrientation.portraitUp);
});
test('pausePreview() does not call $CameraPlatform when already paused',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isPreviewPaused: true);
await cameraController.pausePreview();
verifyNever(
CameraPlatform.instance.pausePreview(cameraController.cameraId));
expect(cameraController.value.isPreviewPaused, equals(true));
});
test(
'pausePreview() sets previewPauseOrientation according to locked orientation',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value = cameraController.value.copyWith(
isPreviewPaused: false,
deviceOrientation: DeviceOrientation.portraitUp,
lockedCaptureOrientation:
Optional<DeviceOrientation>.of(DeviceOrientation.landscapeRight));
await cameraController.pausePreview();
expect(cameraController.value.deviceOrientation,
equals(DeviceOrientation.portraitUp));
expect(cameraController.value.previewPauseOrientation,
equals(DeviceOrientation.landscapeRight));
});
test('pausePreview() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.pausePreview(cameraController.cameraId))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.pausePreview(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('resumePreview() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isPreviewPaused: true);
await cameraController.resumePreview();
verify(CameraPlatform.instance.resumePreview(cameraController.cameraId))
.called(1);
expect(cameraController.value.isPreviewPaused, equals(false));
});
test('resumePreview() does not call $CameraPlatform when not paused',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isPreviewPaused: false);
await cameraController.resumePreview();
verifyNever(
CameraPlatform.instance.resumePreview(cameraController.cameraId));
expect(cameraController.value.isPreviewPaused, equals(false));
});
test('resumePreview() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
cameraController.value =
cameraController.value.copyWith(isPreviewPaused: true);
when(CameraPlatform.instance.resumePreview(cameraController.cameraId))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.resumePreview(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('lockCaptureOrientation() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.lockCaptureOrientation();
expect(cameraController.value.lockedCaptureOrientation,
equals(DeviceOrientation.portraitUp));
await cameraController
.lockCaptureOrientation(DeviceOrientation.landscapeRight);
expect(cameraController.value.lockedCaptureOrientation,
equals(DeviceOrientation.landscapeRight));
verify(CameraPlatform.instance.lockCaptureOrientation(
cameraController.cameraId, DeviceOrientation.portraitUp))
.called(1);
verify(CameraPlatform.instance.lockCaptureOrientation(
cameraController.cameraId, DeviceOrientation.landscapeRight))
.called(1);
});
test(
'lockCaptureOrientation() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance.lockCaptureOrientation(
cameraController.cameraId, DeviceOrientation.portraitUp))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
test('unlockCaptureOrientation() calls $CameraPlatform', () async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
await cameraController.unlockCaptureOrientation();
expect(cameraController.value.lockedCaptureOrientation, equals(null));
verify(CameraPlatform.instance
.unlockCaptureOrientation(cameraController.cameraId))
.called(1);
});
test(
'unlockCaptureOrientation() throws $CameraException on $PlatformException',
() async {
final CameraController cameraController = CameraController(
const CameraDescription(
name: 'cam',
lensDirection: CameraLensDirection.back,
sensorOrientation: 90),
ResolutionPreset.max);
await cameraController.initialize();
when(CameraPlatform.instance
.unlockCaptureOrientation(cameraController.cameraId))
.thenThrow(
PlatformException(
code: 'TEST_ERROR',
message: 'This is a test error message',
),
);
expect(
cameraController.unlockCaptureOrientation(),
throwsA(isA<CameraException>().having(
(CameraException error) => error.description,
'TEST_ERROR',
'This is a test error message',
)));
});
});
}
class MockCameraPlatform extends Mock
with MockPlatformInterfaceMixin
implements CameraPlatform {
@override
Future<void> initializeCamera(
int? cameraId, {
ImageFormatGroup? imageFormatGroup = ImageFormatGroup.unknown,
}) async =>
super.noSuchMethod(Invocation.method(
#initializeCamera,
<Object?>[cameraId],
<Symbol, dynamic>{
#imageFormatGroup: imageFormatGroup,
},
));
@override
Future<void> dispose(int? cameraId) async {
return super.noSuchMethod(Invocation.method(#dispose, <Object?>[cameraId]));
}
@override
Future<List<CameraDescription>> availableCameras() =>
Future<List<CameraDescription>>.value(mockAvailableCameras);
@override
Future<int> createCamera(
CameraDescription description,
ResolutionPreset? resolutionPreset, {
bool enableAudio = false,
}) =>
mockPlatformException
? throw PlatformException(code: 'foo', message: 'bar')
: Future<int>.value(mockInitializeCamera);
@override
Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) =>
Stream<CameraInitializedEvent>.value(mockOnCameraInitializedEvent);
@override
Stream<CameraClosingEvent> onCameraClosing(int cameraId) =>
Stream<CameraClosingEvent>.value(mockOnCameraClosingEvent);
@override
Stream<CameraErrorEvent> onCameraError(int cameraId) =>
Stream<CameraErrorEvent>.value(mockOnCameraErrorEvent);
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() =>
Stream<DeviceOrientationChangedEvent>.value(
mockOnDeviceOrientationChangedEvent);
@override
Future<XFile> takePicture(int cameraId) => mockPlatformException
? throw PlatformException(code: 'foo', message: 'bar')
: Future<XFile>.value(mockTakePicture);
@override
Future<void> prepareForVideoRecording() async =>
super.noSuchMethod(Invocation.method(#prepareForVideoRecording, null));
@override
Future<XFile> startVideoRecording(int cameraId,
{Duration? maxVideoDuration}) =>
Future<XFile>.value(mockVideoRecordingXFile);
@override
Future<void> startVideoCapturing(VideoCaptureOptions options) {
return startVideoRecording(options.cameraId,
maxVideoDuration: options.maxDuration);
}
@override
Future<void> lockCaptureOrientation(
int? cameraId, DeviceOrientation? orientation) async =>
super.noSuchMethod(Invocation.method(
#lockCaptureOrientation, <Object?>[cameraId, orientation]));
@override
Future<void> unlockCaptureOrientation(int? cameraId) async =>
super.noSuchMethod(
Invocation.method(#unlockCaptureOrientation, <Object?>[cameraId]));
@override
Future<void> pausePreview(int? cameraId) async =>
super.noSuchMethod(Invocation.method(#pausePreview, <Object?>[cameraId]));
@override
Future<void> resumePreview(int? cameraId) async => super
.noSuchMethod(Invocation.method(#resumePreview, <Object?>[cameraId]));
@override
Future<double> getMaxZoomLevel(int? cameraId) async => super.noSuchMethod(
Invocation.method(#getMaxZoomLevel, <Object?>[cameraId]),
returnValue: Future<double>.value(1.0),
) as Future<double>;
@override
Future<double> getMinZoomLevel(int? cameraId) async => super.noSuchMethod(
Invocation.method(#getMinZoomLevel, <Object?>[cameraId]),
returnValue: Future<double>.value(0.0),
) as Future<double>;
@override
Future<void> setZoomLevel(int? cameraId, double? zoom) async =>
super.noSuchMethod(
Invocation.method(#setZoomLevel, <Object?>[cameraId, zoom]));
@override
Future<void> setFlashMode(int? cameraId, FlashMode? mode) async =>
super.noSuchMethod(
Invocation.method(#setFlashMode, <Object?>[cameraId, mode]));
@override
Future<void> setExposureMode(int? cameraId, ExposureMode? mode) async =>
super.noSuchMethod(
Invocation.method(#setExposureMode, <Object?>[cameraId, mode]));
@override
Future<void> setExposurePoint(int? cameraId, Point<double>? point) async =>
super.noSuchMethod(
Invocation.method(#setExposurePoint, <Object?>[cameraId, point]));
@override
Future<double> getMinExposureOffset(int? cameraId) async =>
super.noSuchMethod(
Invocation.method(#getMinExposureOffset, <Object?>[cameraId]),
returnValue: Future<double>.value(0.0),
) as Future<double>;
@override
Future<double> getMaxExposureOffset(int? cameraId) async =>
super.noSuchMethod(
Invocation.method(#getMaxExposureOffset, <Object?>[cameraId]),
returnValue: Future<double>.value(1.0),
) as Future<double>;
@override
Future<double> getExposureOffsetStepSize(int? cameraId) async =>
super.noSuchMethod(
Invocation.method(#getExposureOffsetStepSize, <Object?>[cameraId]),
returnValue: Future<double>.value(1.0),
) as Future<double>;
@override
Future<double> setExposureOffset(int? cameraId, double? offset) async =>
super.noSuchMethod(
Invocation.method(#setExposureOffset, <Object?>[cameraId, offset]),
returnValue: Future<double>.value(1.0),
) as Future<double>;
}
class MockCameraDescription extends CameraDescription {
/// Creates a new camera description with the given properties.
const MockCameraDescription()
: super(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
);
@override
CameraLensDirection get lensDirection => CameraLensDirection.back;
@override
String get name => 'back';
}
| packages/packages/camera/camera/test/camera_test.dart/0 | {
"file_path": "packages/packages/camera/camera/test/camera_test.dart",
"repo_id": "packages",
"token_count": 22816
} | 916 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import android.annotation.TargetApi;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.MeteringRectangle;
import android.os.Build;
import android.util.Size;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import java.util.Arrays;
/**
* Utility class offering functions to calculate values regarding the camera boundaries.
*
* <p>The functions are used to calculate focus and exposure settings.
*/
public final class CameraRegionUtils {
/**
* Obtains the boundaries for the currently active camera, that can be used for calculating
* MeteringRectangle instances required for setting focus or exposure settings.
*
* @param cameraProperties - Collection of the characteristics for the current camera device.
* @param requestBuilder - The request builder for the current capture request.
* @return The boundaries for the current camera device.
*/
@NonNull
public static Size getCameraBoundaries(
@NonNull CameraProperties cameraProperties, @NonNull CaptureRequest.Builder requestBuilder) {
if (SdkCapabilityChecker.supportsDistortionCorrection()
&& supportsDistortionCorrection(cameraProperties)) {
// Get the current distortion correction mode.
Integer distortionCorrectionMode =
requestBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE);
// Return the correct boundaries depending on the mode.
android.graphics.Rect rect;
if (distortionCorrectionMode == null
|| distortionCorrectionMode == CaptureRequest.DISTORTION_CORRECTION_MODE_OFF) {
rect = cameraProperties.getSensorInfoPreCorrectionActiveArraySize();
} else {
rect = cameraProperties.getSensorInfoActiveArraySize();
}
return SizeFactory.create(rect.width(), rect.height());
} else {
// No distortion correction support.
return cameraProperties.getSensorInfoPixelArraySize();
}
}
/**
* Converts a point into a {@link MeteringRectangle} with the supplied coordinates as the center
* point.
*
* <p>Since the Camera API (due to cross-platform constraints) only accepts a point when
* configuring a specific focus or exposure area and Android requires a rectangle to configure
* these settings there is a need to convert the point into a rectangle. This method will create
* the required rectangle with an arbitrarily size that is a 10th of the current viewport and the
* coordinates as the center point.
*
* @param boundaries - The camera boundaries to calculate the metering rectangle for.
* @param x x - 1 >= coordinate >= 0.
* @param y y - 1 >= coordinate >= 0.
* @return The dimensions of the metering rectangle based on the supplied coordinates and
* boundaries.
*/
@NonNull
public static MeteringRectangle convertPointToMeteringRectangle(
@NonNull Size boundaries,
double x,
double y,
@NonNull PlatformChannel.DeviceOrientation orientation) {
assert (boundaries.getWidth() > 0 && boundaries.getHeight() > 0);
assert (x >= 0 && x <= 1);
assert (y >= 0 && y <= 1);
// Rotate the coordinates to match the device orientation.
double oldX = x, oldY = y;
switch (orientation) {
case PORTRAIT_UP: // 90 ccw.
y = 1 - oldX;
x = oldY;
break;
case PORTRAIT_DOWN: // 90 cw.
x = 1 - oldY;
y = oldX;
break;
case LANDSCAPE_LEFT:
// No rotation required.
break;
case LANDSCAPE_RIGHT: // 180.
x = 1 - x;
y = 1 - y;
break;
}
// Interpolate the target coordinate.
int targetX = (int) Math.round(x * ((double) (boundaries.getWidth() - 1)));
int targetY = (int) Math.round(y * ((double) (boundaries.getHeight() - 1)));
// Determine the dimensions of the metering rectangle (10th of the viewport).
int targetWidth = (int) Math.round(((double) boundaries.getWidth()) / 10d);
int targetHeight = (int) Math.round(((double) boundaries.getHeight()) / 10d);
// Adjust target coordinate to represent top-left corner of metering rectangle.
targetX -= targetWidth / 2;
targetY -= targetHeight / 2;
// Adjust target coordinate as to not fall out of bounds.
if (targetX < 0) {
targetX = 0;
}
if (targetY < 0) {
targetY = 0;
}
int maxTargetX = boundaries.getWidth() - 1 - targetWidth;
int maxTargetY = boundaries.getHeight() - 1 - targetHeight;
if (targetX > maxTargetX) {
targetX = maxTargetX;
}
if (targetY > maxTargetY) {
targetY = maxTargetY;
}
// Build the metering rectangle.
return MeteringRectangleFactory.create(targetX, targetY, targetWidth, targetHeight, 1);
}
@TargetApi(Build.VERSION_CODES.P)
private static boolean supportsDistortionCorrection(CameraProperties cameraProperties) {
int[] availableDistortionCorrectionModes =
cameraProperties.getDistortionCorrectionAvailableModes();
if (availableDistortionCorrectionModes == null) {
availableDistortionCorrectionModes = new int[0];
}
long nonOffModesSupported =
Arrays.stream(availableDistortionCorrectionModes)
.filter((value) -> value != CaptureRequest.DISTORTION_CORRECTION_MODE_OFF)
.count();
return nonOffModesSupported > 0;
}
/** Factory class that assists in creating a {@link MeteringRectangle} instance. */
static class MeteringRectangleFactory {
/**
* Creates a new instance of the {@link MeteringRectangle} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param x coordinate >= 0.
* @param y coordinate >= 0.
* @param width width >= 0.
* @param height height >= 0.
* @param meteringWeight weight between {@value MeteringRectangle#METERING_WEIGHT_MIN} and
* {@value MeteringRectangle#METERING_WEIGHT_MAX} inclusively.
* @return new instance of the {@link MeteringRectangle} class.
* @throws IllegalArgumentException if any of the parameters were negative.
*/
@VisibleForTesting
public static MeteringRectangle create(
int x, int y, int width, int height, int meteringWeight) {
return new MeteringRectangle(x, y, width, height, meteringWeight);
}
}
/** Factory class that assists in creating a {@link Size} instance. */
static class SizeFactory {
/**
* Creates a new instance of the {@link Size} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param width width >= 0.
* @param height height >= 0.
* @return new instance of the {@link Size} class.
*/
@VisibleForTesting
public static Size create(int width, int height) {
return new Size(width, height);
}
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraRegionUtils.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraRegionUtils.java",
"repo_id": "packages",
"token_count": 2396
} | 917 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.exposurelock;
import android.annotation.SuppressLint;
import android.hardware.camera2.CaptureRequest;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls whether or not the exposure mode is currently locked or automatically metering. */
public class ExposureLockFeature extends CameraFeature<ExposureMode> {
@NonNull private ExposureMode currentSetting = ExposureMode.auto;
/**
* Creates a new instance of the {@see ExposureLockFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
*/
public ExposureLockFeature(@NonNull CameraProperties cameraProperties) {
super(cameraProperties);
}
@NonNull
@Override
public String getDebugName() {
return "ExposureLockFeature";
}
@SuppressLint("KotlinPropertyAccess")
@NonNull
@Override
public ExposureMode getValue() {
return currentSetting;
}
@Override
public void setValue(@NonNull ExposureMode value) {
this.currentSetting = value;
}
// Available on all devices.
@Override
public boolean checkIsSupported() {
return true;
}
@Override
public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
requestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, currentSetting == ExposureMode.locked);
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeature.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeature.java",
"repo_id": "packages",
"token_count": 474
} | 918 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.media;
import android.graphics.ImageFormat;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.Looper;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Wraps an ImageReader to allow for testing of the image handler.
public class ImageStreamReader {
/**
* The image format we are going to send back to dart. Usually it's the same as streamImageFormat
* but in the case of NV21 we will actually request YUV frames but convert it to NV21 before
* sending to dart.
*/
private final int dartImageFormat;
private final ImageReader imageReader;
private final ImageStreamReaderUtils imageStreamReaderUtils;
/**
* Creates a new instance of the {@link ImageStreamReader}.
*
* @param imageReader is the image reader that will receive frames
* @param imageStreamReaderUtils is an instance of {@link ImageStreamReaderUtils}
*/
@VisibleForTesting
public ImageStreamReader(
@NonNull ImageReader imageReader,
int dartImageFormat,
@NonNull ImageStreamReaderUtils imageStreamReaderUtils) {
this.imageReader = imageReader;
this.dartImageFormat = dartImageFormat;
this.imageStreamReaderUtils = imageStreamReaderUtils;
}
/**
* Creates a new instance of the {@link ImageStreamReader}.
*
* @param width is the image width
* @param height is the image height
* @param imageFormat is the {@link ImageFormat} that should be returned to dart.
* @param maxImages is how many images can be acquired at one time, usually 1.
*/
public ImageStreamReader(int width, int height, int imageFormat, int maxImages) {
this.dartImageFormat = imageFormat;
this.imageReader =
ImageReader.newInstance(width, height, computeStreamImageFormat(imageFormat), maxImages);
this.imageStreamReaderUtils = new ImageStreamReaderUtils();
}
/**
* Returns the image format to stream based on a requested input format. Usually it's the same
* except when dart is requesting NV21. In that case we stream YUV420 and process it into NV21
* before sending the frames over.
*
* @param dartImageFormat is the image format dart is requesting.
* @return the image format that should be streamed from the camera.
*/
@VisibleForTesting
public static int computeStreamImageFormat(int dartImageFormat) {
if (dartImageFormat == ImageFormat.NV21) {
return ImageFormat.YUV_420_888;
} else {
return dartImageFormat;
}
}
/**
* Processes a new frame (image) from the image reader and send the frame to Dart.
*
* @param image is the image which needs processed as an {@link Image}
* @param captureProps is the capture props from the camera class as {@link
* CameraCaptureProperties}
* @param imageStreamSink is the image stream sink from dart as a dart {@link
* EventChannel.EventSink}
*/
@VisibleForTesting
public void onImageAvailable(
@NonNull Image image,
@NonNull CameraCaptureProperties captureProps,
@NonNull EventChannel.EventSink imageStreamSink) {
try {
Map<String, Object> imageBuffer = new HashMap<>();
// Get plane data ready
if (dartImageFormat == ImageFormat.NV21) {
imageBuffer.put("planes", parsePlanesForNv21(image));
} else {
imageBuffer.put("planes", parsePlanesForYuvOrJpeg(image));
}
imageBuffer.put("width", image.getWidth());
imageBuffer.put("height", image.getHeight());
imageBuffer.put("format", dartImageFormat);
imageBuffer.put("lensAperture", captureProps.getLastLensAperture());
imageBuffer.put("sensorExposureTime", captureProps.getLastSensorExposureTime());
Integer sensorSensitivity = captureProps.getLastSensorSensitivity();
imageBuffer.put(
"sensorSensitivity", sensorSensitivity == null ? null : (double) sensorSensitivity);
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> imageStreamSink.success(imageBuffer));
image.close();
} catch (IllegalStateException e) {
// Handle "buffer is inaccessible" errors that can happen on some devices from ImageStreamReaderUtils.yuv420ThreePlanesToNV21()
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(
() ->
imageStreamSink.error(
"IllegalStateException",
"Caught IllegalStateException: " + e.getMessage(),
null));
image.close();
}
}
/**
* Given an input image, will return a list of maps suitable to send back to dart where each map
* describes the image plane.
*
* <p>For Yuv / Jpeg, we do no further processing on the frame so we simply send it as-is.
*
* @param image - the image to process.
* @return parsed map describing the image planes to be sent to dart.
*/
@NonNull
public List<Map<String, Object>> parsePlanesForYuvOrJpeg(@NonNull Image image) {
List<Map<String, Object>> planes = new ArrayList<>();
// For YUV420 and JPEG, just send the data as-is for each plane.
for (Image.Plane plane : image.getPlanes()) {
ByteBuffer buffer = plane.getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);
Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", plane.getRowStride());
planeBuffer.put("bytesPerPixel", plane.getPixelStride());
planeBuffer.put("bytes", bytes);
planes.add(planeBuffer);
}
return planes;
}
/**
* Given an input image, will return a single-plane NV21 image. Assumes YUV420 as an input type.
*
* @param image - the image to process.
* @return parsed map describing the image planes to be sent to dart.
*/
@NonNull
public List<Map<String, Object>> parsePlanesForNv21(@NonNull Image image) {
List<Map<String, Object>> planes = new ArrayList<>();
// We will convert the YUV data to NV21 which is a single-plane image
ByteBuffer bytes =
imageStreamReaderUtils.yuv420ThreePlanesToNV21(
image.getPlanes(), image.getWidth(), image.getHeight());
Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", image.getWidth());
planeBuffer.put("bytesPerPixel", 1);
planeBuffer.put("bytes", bytes.array());
planes.add(planeBuffer);
return planes;
}
/** Returns the image reader surface. */
@NonNull
public Surface getSurface() {
return imageReader.getSurface();
}
/**
* Subscribes the image stream reader to handle incoming images using onImageAvailable().
*
* @param captureProps is the capture props from the camera class as {@link
* CameraCaptureProperties}
* @param imageStreamSink is the image stream sink from dart as {@link EventChannel.EventSink}
* @param handler is generally the background handler of the camera as {@link Handler}
*/
public void subscribeListener(
@NonNull CameraCaptureProperties captureProps,
@NonNull EventChannel.EventSink imageStreamSink,
@NonNull Handler handler) {
imageReader.setOnImageAvailableListener(
reader -> {
Image image = reader.acquireNextImage();
if (image == null) return;
onImageAvailable(image, captureProps, imageStreamSink);
},
handler);
}
/**
* Removes the listener from the image reader.
*
* @param handler is generally the background handler of the camera
*/
public void removeListener(@NonNull Handler handler) {
imageReader.setOnImageAvailableListener(null, handler);
}
/** Closes the image reader. */
public void close() {
imageReader.close();
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/media/ImageStreamReader.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/media/ImageStreamReader.java",
"repo_id": "packages",
"token_count": 2716
} | 919 |
## 0.6.0+1
* Updates `README.md` to encourage developers to opt into this implementation of the camera plugin.
## 0.6.0
* Implements `setFocusMode`, which makes this plugin reach feature parity with camera_android.
* Fixes `setExposureCompensationIndex` return value to use index returned by CameraX.
## 0.5.0+36
* Implements `setExposureMode`.
## 0.5.0+35
* Modifies `CameraInitializedEvent` that is sent when the camera is initialized to indicate that the initial focus
and exposure modes are auto and that developers may set focus and exposure points.
## 0.5.0+34
* Implements `setFocusPoint`, `setExposurePoint`, and `setExposureOffset`.
## 0.5.0+33
* Fixes typo in `README.md`.
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 0.5.0+32
* Removes all remaining `unawaited` calls to fix potential race conditions and updates the
camera state when video capture starts.
## 0.5.0+31
* Wraps CameraX classes needed to set capture request options, which is needed to implement setting the exposure mode.
## 0.5.0+30
* Adds documentation to clarify how the plugin uses resolution presets as target resolutions for CameraX.
## 0.5.0+29
* Modifies `buildPreview` to return `Texture` that maps to camera preview, building in the assumption
that `createCamera` should have been called before building the preview. Fixes
https://github.com/flutter/flutter/issues/140567.
## 0.5.0+28
* Wraps CameraX classes needed to implement setting focus and exposure points and exposure offset.
* Updates compileSdk version to 34.
## 0.5.0+27
* Removes or updates any references to an `ActivityPluginBinding` when the plugin is detached
or attached/re-attached, respectively, to an `Activity.`
## 0.5.0+26
* Fixes new lint warnings.
## 0.5.0+25
* Implements `lockCaptureOrientation` and `unlockCaptureOrientation`.
## 0.5.0+24
* Updates example app to use non-deprecated video_player method.
## 0.5.0+23
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Adds `CameraXProxy` class to test `JavaObject` creation and their method calls in the plugin.
## 0.5.0+22
* Fixes `_getResolutionSelectorFromPreset` null pointer error.
## 0.5.0+21
* Changes fallback resolution strategies for camera use cases to look for a higher resolution if neither the desired
resolution nor any lower resolutions are available.
## 0.5.0+20
* Implements `setZoomLevel`.
## 0.5.0+19
* Implements torch flash mode.
## 0.5.0+18
* Implements `startVideoCapturing`.
## 0.5.0+17
* Implements resolution configuration for all camera use cases.
## 0.5.0+16
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.5.0+15
* Explicitly removes `READ_EXTERNAL_STORAGE` permission that may otherwise be implied from `WRITE_EXTERNAL_STORAGE`.
## 0.5.0+14
* Wraps classes needed to implement resolution configuration for video recording.
## 0.5.0+13
* Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters.
## 0.5.0+12
* Wraps classes needed to implement resolution configuration for image capture, image analysis, and preview.
* Removes usages of deprecated APIs for resolution configuration.
* Bumps CameraX version to 1.3.0-beta01.
## 0.5.0+11
* Fixes issue with image data not being emitted after relistening to stream returned by `onStreamedFrameAvailable`.
## 0.5.0+10
* Implements off, auto, and always flash mode configurations for image capture.
## 0.5.0+9
* Marks all Dart-wrapped Android native classes as `@immutable`.
* Updates `CONTRIBUTING.md` to note requirements of Dart-wrapped Android native classes.
## 0.5.0+8
* Fixes unawaited_futures violations.
## 0.5.0+7
* Updates Guava version to 32.0.1.
## 0.5.0+6
* Updates Guava version to 32.0.0.
## 0.5.0+5
* Updates `README.md` to fully cover unimplemented functionality.
## 0.5.0+4
* Removes obsolete null checks on non-nullable values.
## 0.5.0+3
* Fixes Java lints.
## 0.5.0+2
* Adds a dependency on kotlin-bom to align versions of Kotlin transitive dependencies.
* Removes note in `README.md` regarding duplicate Kotlin classes issue.
## 0.5.0+1
* Update `README.md` to include known duplicate Kotlin classes issue.
## 0.5.0
* Initial release of this `camera` implementation that supports:
* Image capture
* Video recording
* Displaying a live camera preview
* Image streaming
See [`README.md`](README.md) for more details on the limitations of this implementation.
| packages/packages/camera/camera_android_camerax/CHANGELOG.md/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1417
} | 920 |
// 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.camera.core.CameraInfo;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraInfoFlutterApi;
public class CameraInfoFlutterApiImpl extends CameraInfoFlutterApi {
private final @NonNull InstanceManager instanceManager;
public CameraInfoFlutterApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
super(binaryMessenger);
this.instanceManager = instanceManager;
}
/**
* Creates a {@link CameraInfo} instance in Dart. {@code reply} is not used so it can be empty.
*/
void create(CameraInfo cameraInfo, Reply<Void> reply) {
if (!instanceManager.containsInstance(cameraInfo)) {
create(instanceManager.addHostCreatedInstance(cameraInfo), reply);
}
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java",
"repo_id": "packages",
"token_count": 319
} | 921 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.FocusMeteringResult;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultHostApi;
/**
* Host API implementation for {@link FocusMeteringResult}.
*
* <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 FocusMeteringResultHostApiImpl implements FocusMeteringResultHostApi {
private final InstanceManager instanceManager;
private final FocusMeteringResultProxy proxy;
/** Proxy for methods of {@link FocusMeteringResult}. */
@VisibleForTesting
public static class FocusMeteringResultProxy {
/**
* Returns whether or not auto focus was successful.
*
* <p>If the current camera does not support auto focus, it will return true. If auto focus is
* not requested, it will return false.
*/
@NonNull
public Boolean isFocusSuccessful(@NonNull FocusMeteringResult focusMeteringResult) {
return focusMeteringResult.isFocusSuccessful();
}
}
/**
* Constructs a {@link FocusMeteringResultHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public FocusMeteringResultHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new FocusMeteringResultProxy());
}
/**
* Constructs a {@link FocusMeteringResultHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for methods of {@link FocusMeteringResult}
*/
FocusMeteringResultHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull FocusMeteringResultProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
@Override
@NonNull
public Boolean isFocusSuccessful(@NonNull Long identifier) {
return proxy.isFocusSuccessful(instanceManager.getInstance(identifier));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java",
"repo_id": "packages",
"token_count": 655
} | 922 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.camera.core.ImageProxy;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AnalyzerFlutterApi;
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 AnalyzerTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public AnalyzerHostApiImpl.AnalyzerImpl mockImageAnalysisAnalyzer;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public AnalyzerFlutterApi mockFlutterApi;
@Mock public AnalyzerHostApiImpl.AnalyzerProxy mockProxy;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void hostApiCreate_makesCallToCreateAnalyzerInstanceWithExpectedIdentifier() {
final AnalyzerHostApiImpl hostApi =
new AnalyzerHostApiImpl(mockBinaryMessenger, instanceManager, mockProxy);
final long instanceIdentifier = 90;
when(mockProxy.create(mockBinaryMessenger, instanceManager))
.thenReturn(mockImageAnalysisAnalyzer);
hostApi.create(instanceIdentifier);
assertEquals(instanceManager.getInstance(instanceIdentifier), mockImageAnalysisAnalyzer);
}
@Test
public void flutterApiCreate_makesCallToDartCreate() {
final AnalyzerFlutterApiImpl flutterApi =
new AnalyzerFlutterApiImpl(mockBinaryMessenger, instanceManager);
flutterApi.setApi(mockFlutterApi);
flutterApi.create(mockImageAnalysisAnalyzer, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(
instanceManager.getIdentifierForStrongReference(mockImageAnalysisAnalyzer));
verify(mockFlutterApi).create(eq(instanceIdentifier), any());
}
@Test
public void analyze_makesCallToDartAnalyze() {
final AnalyzerFlutterApiImpl flutterApi =
new AnalyzerFlutterApiImpl(mockBinaryMessenger, instanceManager);
final ImageProxy mockImageProxy = mock(ImageProxy.class);
final long mockImageProxyIdentifier = 97;
final AnalyzerHostApiImpl.AnalyzerImpl instance =
new AnalyzerHostApiImpl.AnalyzerImpl(mockBinaryMessenger, instanceManager);
final ImageProxyFlutterApiImpl mockImageProxyApi =
spy(new ImageProxyFlutterApiImpl(mockBinaryMessenger, instanceManager));
final long instanceIdentifier = 20;
final long format = 3;
final long height = 2;
final long width = 1;
flutterApi.setApi(mockFlutterApi);
instance.setApi(flutterApi);
instance.imageProxyApi = mockImageProxyApi;
instanceManager.addDartCreatedInstance(instance, instanceIdentifier);
instanceManager.addDartCreatedInstance(mockImageProxy, mockImageProxyIdentifier);
when(mockImageProxy.getFormat()).thenReturn(3);
when(mockImageProxy.getHeight()).thenReturn(2);
when(mockImageProxy.getWidth()).thenReturn(1);
instance.analyze(mockImageProxy);
verify(mockFlutterApi).analyze(eq(instanceIdentifier), eq(mockImageProxyIdentifier), any());
verify(mockImageProxyApi).create(eq(mockImageProxy), eq(format), eq(height), eq(width), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java",
"repo_id": "packages",
"token_count": 1305
} | 923 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.camera.core.FocusMeteringAction;
import androidx.camera.core.MeteringPoint;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointInfo;
import java.util.Arrays;
import java.util.List;
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 FocusMeteringActionTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public FocusMeteringAction focusMeteringAction;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void hostApiCreate_createsExpectedFocusMeteringActionWithInitialPointThatHasMode() {
FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy =
spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy());
FocusMeteringActionHostApiImpl hostApi =
new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy);
final Long focusMeteringActionIdentifier = 43L;
FocusMeteringAction.Builder mockFocusMeteringActionBuilder =
mock(FocusMeteringAction.Builder.class);
final MeteringPoint mockMeteringPoint1 = mock(MeteringPoint.class);
final MeteringPoint mockMeteringPoint2 = mock(MeteringPoint.class);
final MeteringPoint mockMeteringPoint3 = mock(MeteringPoint.class);
final Long mockMeteringPoint1Id = 47L;
final Long mockMeteringPoint2Id = 56L;
final Long mockMeteringPoint3Id = 99L;
final Integer mockMeteringPoint1Mode = FocusMeteringAction.FLAG_AE;
final Integer mockMeteringPoint2Mode = FocusMeteringAction.FLAG_AF;
MeteringPointInfo fakeMeteringPointInfo1 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint1Id)
.setMeteringMode(mockMeteringPoint1Mode.longValue())
.build();
MeteringPointInfo fakeMeteringPointInfo2 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint2Id)
.setMeteringMode(mockMeteringPoint2Mode.longValue())
.build();
MeteringPointInfo fakeMeteringPointInfo3 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint3Id)
.setMeteringMode(null)
.build();
testInstanceManager.addDartCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id);
testInstanceManager.addDartCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id);
testInstanceManager.addDartCreatedInstance(mockMeteringPoint3, mockMeteringPoint3Id);
when(proxySpy.getFocusMeteringActionBuilder(
mockMeteringPoint1, mockMeteringPoint1Mode.intValue()))
.thenReturn(mockFocusMeteringActionBuilder);
when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction);
List<MeteringPointInfo> mockMeteringPointInfos =
Arrays.asList(fakeMeteringPointInfo1, fakeMeteringPointInfo2, fakeMeteringPointInfo3);
hostApi.create(focusMeteringActionIdentifier, mockMeteringPointInfos, null);
verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint2, mockMeteringPoint2Mode);
verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint3);
assertEquals(
testInstanceManager.getInstance(focusMeteringActionIdentifier), focusMeteringAction);
}
@Test
public void
hostApiCreate_createsExpectedFocusMeteringActionWithInitialPointThatDoesNotHaveMode() {
FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy =
spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy());
FocusMeteringActionHostApiImpl hostApi =
new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy);
final Long focusMeteringActionIdentifier = 43L;
FocusMeteringAction.Builder mockFocusMeteringActionBuilder =
mock(FocusMeteringAction.Builder.class);
final MeteringPoint mockMeteringPoint1 = mock(MeteringPoint.class);
final MeteringPoint mockMeteringPoint2 = mock(MeteringPoint.class);
final MeteringPoint mockMeteringPoint3 = mock(MeteringPoint.class);
final Long mockMeteringPoint1Id = 47L;
final Long mockMeteringPoint2Id = 56L;
final Long mockMeteringPoint3Id = 99L;
final Integer mockMeteringPoint2Mode = FocusMeteringAction.FLAG_AF;
MeteringPointInfo fakeMeteringPointInfo1 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint1Id)
.setMeteringMode(null)
.build();
MeteringPointInfo fakeMeteringPointInfo2 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint2Id)
.setMeteringMode(mockMeteringPoint2Mode.longValue())
.build();
MeteringPointInfo fakeMeteringPointInfo3 =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPoint3Id)
.setMeteringMode(null)
.build();
testInstanceManager.addDartCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id);
testInstanceManager.addDartCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id);
testInstanceManager.addDartCreatedInstance(mockMeteringPoint3, mockMeteringPoint3Id);
when(proxySpy.getFocusMeteringActionBuilder(mockMeteringPoint1))
.thenReturn(mockFocusMeteringActionBuilder);
when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction);
List<MeteringPointInfo> mockMeteringPointInfos =
Arrays.asList(fakeMeteringPointInfo1, fakeMeteringPointInfo2, fakeMeteringPointInfo3);
hostApi.create(focusMeteringActionIdentifier, mockMeteringPointInfos, null);
verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint2, mockMeteringPoint2Mode);
verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint3);
assertEquals(
testInstanceManager.getInstance(focusMeteringActionIdentifier), focusMeteringAction);
}
@Test
public void hostApiCreate_disablesAutoCancelAsExpected() {
FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy =
spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy());
FocusMeteringActionHostApiImpl hostApi =
new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy);
FocusMeteringAction.Builder mockFocusMeteringActionBuilder =
mock(FocusMeteringAction.Builder.class);
final MeteringPoint mockMeteringPoint = mock(MeteringPoint.class);
final Long mockMeteringPointId = 47L;
MeteringPointInfo fakeMeteringPointInfo =
new MeteringPointInfo.Builder()
.setMeteringPointId(mockMeteringPointId)
.setMeteringMode(null)
.build();
testInstanceManager.addDartCreatedInstance(mockMeteringPoint, mockMeteringPointId);
when(proxySpy.getFocusMeteringActionBuilder(mockMeteringPoint))
.thenReturn(mockFocusMeteringActionBuilder);
when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction);
List<MeteringPointInfo> mockMeteringPointInfos = Arrays.asList(fakeMeteringPointInfo);
// Test not disabling auto cancel.
hostApi.create(73L, mockMeteringPointInfos, /* disableAutoCancel */ null);
verify(mockFocusMeteringActionBuilder, never()).disableAutoCancel();
hostApi.create(74L, mockMeteringPointInfos, /* disableAutoCancel */ false);
verify(mockFocusMeteringActionBuilder, never()).disableAutoCancel();
// Test disabling auto cancel.
hostApi.create(75L, mockMeteringPointInfos, /* disableAutoCancel */ true);
verify(mockFocusMeteringActionBuilder).disableAutoCancel();
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java",
"repo_id": "packages",
"token_count": 2918
} | 924 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.PendingRecording;
import androidx.camera.video.QualitySelector;
import androidx.camera.video.Recorder;
import androidx.test.core.app.ApplicationProvider;
import io.flutter.plugin.common.BinaryMessenger;
import java.io.File;
import java.util.Objects;
import java.util.concurrent.Executor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class RecorderTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public Recorder mockRecorder;
private Context context;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = spy(InstanceManager.create(identifier -> {}));
context = ApplicationProvider.getApplicationContext();
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void create_createsExpectedRecorderInstance() {
final int recorderId = 0;
final int aspectRatio = 1;
final int bitRate = 2;
final int qualitySelectorId = 3;
final RecorderHostApiImpl recorderHostApi =
new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context);
final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class);
final Recorder.Builder mockRecorderBuilder = mock(Recorder.Builder.class);
final QualitySelector mockQualitySelector = mock(QualitySelector.class);
recorderHostApi.cameraXProxy = mockCameraXProxy;
when(mockCameraXProxy.createRecorderBuilder()).thenReturn(mockRecorderBuilder);
when(mockRecorderBuilder.setAspectRatio(aspectRatio)).thenReturn(mockRecorderBuilder);
when(mockRecorderBuilder.setTargetVideoEncodingBitRate(bitRate))
.thenReturn(mockRecorderBuilder);
when(mockRecorderBuilder.setExecutor(any(Executor.class))).thenReturn(mockRecorderBuilder);
when(mockRecorderBuilder.build()).thenReturn(mockRecorder);
testInstanceManager.addDartCreatedInstance(
mockQualitySelector, Long.valueOf(qualitySelectorId));
recorderHostApi.create(
Long.valueOf(recorderId),
Long.valueOf(aspectRatio),
Long.valueOf(bitRate),
Long.valueOf(qualitySelectorId));
verify(mockCameraXProxy).createRecorderBuilder();
verify(mockRecorderBuilder).setAspectRatio(aspectRatio);
verify(mockRecorderBuilder).setTargetVideoEncodingBitRate(bitRate);
verify(mockRecorderBuilder).setQualitySelector(mockQualitySelector);
verify(mockRecorderBuilder).build();
assertEquals(testInstanceManager.getInstance(Long.valueOf(recorderId)), mockRecorder);
testInstanceManager.remove(Long.valueOf(recorderId));
}
@Test
public void getAspectRatioTest() {
final int recorderId = 3;
final int aspectRatio = 6;
when(mockRecorder.getAspectRatio()).thenReturn(aspectRatio);
testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId));
final RecorderHostApiImpl recorderHostApi =
new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context);
assertEquals(
recorderHostApi.getAspectRatio(Long.valueOf(recorderId)), Long.valueOf(aspectRatio));
verify(mockRecorder).getAspectRatio();
testInstanceManager.remove(Long.valueOf(recorderId));
}
@Test
public void getTargetVideoEncodingBitRateTest() {
final int bitRate = 7;
final int recorderId = 3;
when(mockRecorder.getTargetVideoEncodingBitRate()).thenReturn(bitRate);
testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId));
final RecorderHostApiImpl recorderHostApi =
new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context);
assertEquals(
recorderHostApi.getTargetVideoEncodingBitRate(Long.valueOf(recorderId)),
Long.valueOf(bitRate));
verify(mockRecorder).getTargetVideoEncodingBitRate();
testInstanceManager.remove(Long.valueOf(recorderId));
}
@Test
@SuppressWarnings("unchecked")
public void prepareRecording_returnsExpectedPendingRecording() {
final int recorderId = 3;
PendingRecordingFlutterApiImpl mockPendingRecordingFlutterApi =
mock(PendingRecordingFlutterApiImpl.class);
PendingRecording mockPendingRecording = mock(PendingRecording.class);
testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId));
when(mockRecorder.prepareRecording(any(Context.class), any(FileOutputOptions.class)))
.thenReturn(mockPendingRecording);
doNothing().when(mockPendingRecordingFlutterApi).create(any(PendingRecording.class), any());
Long mockPendingRecordingId = testInstanceManager.addHostCreatedInstance(mockPendingRecording);
RecorderHostApiImpl spy =
spy(new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context));
spy.pendingRecordingFlutterApi = mockPendingRecordingFlutterApi;
doReturn(mock(File.class)).when(spy).openTempFile(any());
spy.prepareRecording(Long.valueOf(recorderId), "");
testInstanceManager.remove(Long.valueOf(recorderId));
testInstanceManager.remove(mockPendingRecordingId);
}
@Test
@SuppressWarnings("unchecked")
public void prepareRecording_errorsWhenPassedNullPath() {
final int recorderId = 3;
testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId));
RecorderHostApiImpl recorderHostApi =
new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context);
assertThrows(
RuntimeException.class,
() -> {
recorderHostApi.prepareRecording(Long.valueOf(recorderId), null);
});
testInstanceManager.remove(Long.valueOf(recorderId));
}
@Test
public void flutterApiCreateTest() {
final RecorderFlutterApiImpl spyRecorderFlutterApi =
spy(new RecorderFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
spyRecorderFlutterApi.create(mockRecorder, null, null, reply -> {});
final long identifier =
Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockRecorder));
verify(spyRecorderFlutterApi).create(eq(identifier), eq(null), eq(null), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java",
"repo_id": "packages",
"token_count": 2457
} | 925 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';
import 'camera_state_error.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// A snapshot of the camera state.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState.
@immutable
class CameraState extends JavaObject {
/// Constructs a [CameraState] that is not automatically attached to a native object.
CameraState.detached(
{super.binaryMessenger,
super.instanceManager,
required this.type,
this.error})
: super.detached();
/// The type of state that the camera is in.
final CameraStateType type;
/// The error that the camera has encountered, if any.
final CameraStateError? error;
/// Error code indicating that the camera device is already in use.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_IN_USE()
static const int errorCameraInUse = 1;
/// Error code indicating that the limit number of open cameras has been
/// reached.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_MAX_CAMERAS_IN_USE()
static const int errorMaxCamerasInUse = 2;
/// Error code indicating that the camera device has encountered a recoverable
/// error.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_OTHER_RECOVERABLE_ERROR()
static const int errorOtherRecoverableError = 3;
/// Error code inidcating that configuring the camera has failed.
///
/// https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_STREAM_CONFIG()
static const int errorStreamConfig = 4;
/// Error code indicating that the camera device could not be opened due to a
/// device policy.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_DISABLED()
static const int errorCameraDisabled = 5;
/// Error code indicating that the camera device was closed due to a fatal
/// error.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_FATAL_ERROR()
static const int errorCameraFatalError = 6;
/// Error code indicating that the camera could not be opened because
/// "Do Not Disturb" mode is enabled on devices affected by a bug in Android 9
/// (API level 28).
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_DO_NOT_DISTURB_MODE_ENABLED()
static const int errorDoNotDisturbModeEnabled = 7;
}
/// Flutter API implementation for [CameraState].
///
/// This class may handle instantiating and adding Dart instances that are
/// attached to a native instance or receiving callback methods from an
/// overridden native class.
@protected
class CameraStateFlutterApiImpl implements CameraStateFlutterApi {
/// Constructs a [CameraStateFlutterApiImpl].
///
/// 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].
CameraStateFlutterApiImpl({
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,
CameraStateTypeData type,
int? errorIdentifier,
) {
_instanceManager.addHostCreatedInstance(
CameraState.detached(
type: type.value,
error: errorIdentifier == null
? null
: _instanceManager.getInstanceWithWeakReference(
errorIdentifier,
),
binaryMessenger: _binaryMessenger,
instanceManager: _instanceManager,
),
identifier,
onCopy: (CameraState original) => CameraState.detached(
type: original.type,
error: original.error,
binaryMessenger: _binaryMessenger,
instanceManager: _instanceManager,
),
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/camera_state.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/camera_state.dart",
"repo_id": "packages",
"token_count": 1426
} | 926 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camera_info.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Representation for a region which can be converted to sensor coordinate
/// system for focus and metering purpose.
///
/// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint.
@immutable
class MeteringPoint extends JavaObject {
/// Creates a [MeteringPoint].
MeteringPoint({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required this.x,
required this.y,
this.size,
required this.cameraInfo,
}) : super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
) {
_api = _MeteringPointHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstance(this, x, y, size, cameraInfo);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
/// Creates a [MeteringPoint] that is not automatically attached to a
/// native object.
MeteringPoint.detached({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required this.x,
required this.y,
this.size,
required this.cameraInfo,
}) : super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
) {
_api = _MeteringPointHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final _MeteringPointHostApiImpl _api;
/// X coordinate.
final double x;
/// Y coordinate.
final double y;
/// The size of the [MeteringPoint] width and height (ranging from 0 to 1),
/// which is a normalized percentage of the sensor width/height (or crop
/// region width/height if crop region is set).
final double? size;
/// The [CameraInfo] used to construct the metering point with a display-
/// oriented metering point factory.
final CameraInfo cameraInfo;
/// The default size of the [MeteringPoint] width and height (ranging from 0
/// to 1) which is a (normalized) percentage of the sensor width/height (or
/// crop region width/height if crop region is set).
static Future<double> getDefaultPointSize(
{BinaryMessenger? binaryMessenger}) {
final MeteringPointHostApi hostApi =
MeteringPointHostApi(binaryMessenger: binaryMessenger);
return hostApi.getDefaultPointSize();
}
}
/// Host API implementation of [MeteringPoint].
class _MeteringPointHostApiImpl extends MeteringPointHostApi {
/// Constructs a [_MeteringPointHostApiImpl].
///
/// 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].
_MeteringPointHostApiImpl(
{this.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default [BinaryMessenger] will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Creates a [MeteringPoint] instance with the specified [x] and [y]
/// coordinates as well as [size] if non-null.
Future<void> createFromInstance(MeteringPoint instance, double x, double y,
double? size, CameraInfo cameraInfo) {
int? identifier = instanceManager.getIdentifier(instance);
identifier ??= instanceManager.addDartCreatedInstance(instance,
onCopy: (MeteringPoint original) {
return MeteringPoint.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
x: original.x,
y: original.y,
cameraInfo: original.cameraInfo,
size: original.size);
});
final int? camInfoId = instanceManager.getIdentifier(cameraInfo);
return create(identifier, x, y, size, camInfoId!);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/metering_point.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/metering_point.dart",
"repo_id": "packages",
"token_count": 1467
} | 927 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/camerax_library.g.dart',
dartTestOut: 'test/test_camerax_library.g.dart',
dartOptions: DartOptions(copyrightHeader: <String>[
'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.',
]),
javaOut:
'android/src/main/java/io/flutter/plugins/camerax/GeneratedCameraXLibrary.java',
javaOptions: JavaOptions(
package: 'io.flutter.plugins.camerax',
className: 'GeneratedCameraXLibrary',
copyrightHeader: <String>[
'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.',
],
),
),
)
class ResolutionInfo {
ResolutionInfo({
required this.width,
required this.height,
});
int width;
int height;
}
class CameraPermissionsErrorData {
CameraPermissionsErrorData({
required this.errorCode,
required this.description,
});
String errorCode;
String description;
}
/// The states the camera can be in.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraState.Type.
enum CameraStateType {
closed,
closing,
open,
opening,
pendingOpen,
}
class CameraStateTypeData {
late CameraStateType value;
}
/// The types (T) properly wrapped to be used as a LiveData<T>.
///
/// If you need to add another type to support a type S to use a LiveData<S> in
/// this plugin, ensure the following is done on the Dart side:
///
/// * In `camera_android_camerax/lib/src/live_data.dart`, add new cases for S in
/// `_LiveDataHostApiImpl#getValueFromInstances` to get the current value of
/// type S from a LiveData<S> instance and in `LiveDataFlutterApiImpl#create`
/// to create the expected type of LiveData<S> when requested.
///
/// On the native side, ensure the following is done:
///
/// * Make sure `LiveDataHostApiImpl#getValue` is updated to properly return
/// identifiers for instances of type S.
/// * Update `ObserverFlutterApiWrapper#onChanged` to properly handle receiving
/// calls with instances of type S if a LiveData<S> instance is observed.
enum LiveDataSupportedType {
cameraState,
zoomState,
}
class LiveDataSupportedTypeData {
late LiveDataSupportedType value;
}
class ExposureCompensationRange {
ExposureCompensationRange({
required this.minCompensation,
required this.maxCompensation,
});
int minCompensation;
int maxCompensation;
}
/// Video quality constraints that will be used by a QualitySelector to choose
/// an appropriate video resolution.
///
/// These are pre-defined quality constants that are universally used for video.
///
/// See https://developer.android.com/reference/androidx/camera/video/Quality.
enum VideoQuality {
SD, // 480p
HD, // 720p
FHD, // 1080p
UHD, // 2160p
lowest,
highest,
}
/// Convenience class for sending lists of [Quality]s.
class VideoQualityData {
late VideoQuality quality;
}
/// Fallback rules for selecting video resolution.
///
/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy.
enum VideoResolutionFallbackRule {
higherQualityOrLowerThan,
higherQualityThan,
lowerQualityOrHigherThan,
lowerQualityThan,
}
/// Convenience class for building [FocusMeteringAction]s with multiple metering
/// points.
class MeteringPointInfo {
MeteringPointInfo({
required this.meteringPointId,
required this.meteringMode,
});
/// InstanceManager ID for a [MeteringPoint].
int meteringPointId;
/// The metering mode of the [MeteringPoint] whose ID is [meteringPointId].
///
/// Metering mode should be one of the [FocusMeteringAction] constants.
int? meteringMode;
}
/// The types of capture request options this plugin currently supports.
///
/// If you need to add another option to support, ensure the following is done
/// on the Dart side:
///
/// * In `camera_android_camerax/lib/src/capture_request_options.dart`, add new cases for this
/// option in `_CaptureRequestOptionsHostApiImpl#createFromInstances`
/// to create the expected Map entry of option key index and value to send to
/// the native side.
///
/// On the native side, ensure the following is done:
///
/// * Update `CaptureRequestOptionsHostApiImpl#create` to set the correct
/// `CaptureRequest` key with a valid value type for this option.
///
/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest
/// for the sorts of capture request options that can be supported via CameraX's
/// interoperability with Camera2.
enum CaptureRequestKeySupportedType {
controlAeLock,
}
@HostApi(dartHostTestHandler: 'TestInstanceManagerHostApi')
abstract class InstanceManagerHostApi {
/// Clear the native `InstanceManager`.
///
/// This is typically only used after a hot restart.
void clear();
}
@HostApi(dartHostTestHandler: 'TestJavaObjectHostApi')
abstract class JavaObjectHostApi {
void dispose(int identifier);
}
@FlutterApi()
abstract class JavaObjectFlutterApi {
void dispose(int identifier);
}
@HostApi(dartHostTestHandler: 'TestCameraInfoHostApi')
abstract class CameraInfoHostApi {
int getSensorRotationDegrees(int identifier);
int getCameraState(int identifier);
int getExposureState(int identifier);
int getZoomState(int identifier);
}
@FlutterApi()
abstract class CameraInfoFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestCameraSelectorHostApi')
abstract class CameraSelectorHostApi {
void create(int identifier, int? lensFacing);
List<int> filter(int identifier, List<int> cameraInfoIds);
}
@FlutterApi()
abstract class CameraSelectorFlutterApi {
void create(int identifier, int? lensFacing);
}
@HostApi(dartHostTestHandler: 'TestProcessCameraProviderHostApi')
abstract class ProcessCameraProviderHostApi {
@async
int getInstance();
List<int> getAvailableCameraInfos(int identifier);
int bindToLifecycle(
int identifier, int cameraSelectorIdentifier, List<int> useCaseIds);
bool isBound(int identifier, int useCaseIdentifier);
void unbind(int identifier, List<int> useCaseIds);
void unbindAll(int identifier);
}
@FlutterApi()
abstract class ProcessCameraProviderFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestCameraHostApi')
abstract class CameraHostApi {
int getCameraInfo(int identifier);
int getCameraControl(int identifier);
}
@FlutterApi()
abstract class CameraFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestSystemServicesHostApi')
abstract class SystemServicesHostApi {
@async
CameraPermissionsErrorData? requestCameraPermissions(bool enableAudio);
String getTempFilePath(String prefix, String suffix);
}
@FlutterApi()
abstract class SystemServicesFlutterApi {
void onCameraError(String errorDescription);
}
@HostApi(dartHostTestHandler: 'TestDeviceOrientationManagerHostApi')
abstract class DeviceOrientationManagerHostApi {
void startListeningForDeviceOrientationChange(
bool isFrontFacing, int sensorOrientation);
void stopListeningForDeviceOrientationChange();
int getDefaultDisplayRotation();
}
@FlutterApi()
abstract class DeviceOrientationManagerFlutterApi {
void onDeviceOrientationChanged(String orientation);
}
@HostApi(dartHostTestHandler: 'TestPreviewHostApi')
abstract class PreviewHostApi {
void create(int identifier, int? rotation, int? resolutionSelectorId);
int setSurfaceProvider(int identifier);
void releaseFlutterSurfaceTexture();
ResolutionInfo getResolutionInfo(int identifier);
void setTargetRotation(int identifier, int rotation);
}
@HostApi(dartHostTestHandler: 'TestVideoCaptureHostApi')
abstract class VideoCaptureHostApi {
int withOutput(int videoOutputId);
int getOutput(int identifier);
void setTargetRotation(int identifier, int rotation);
}
@FlutterApi()
abstract class VideoCaptureFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestRecorderHostApi')
abstract class RecorderHostApi {
void create(
int identifier, int? aspectRatio, int? bitRate, int? qualitySelectorId);
int getAspectRatio(int identifier);
int getTargetVideoEncodingBitRate(int identifier);
int prepareRecording(int identifier, String path);
}
@FlutterApi()
abstract class RecorderFlutterApi {
void create(int identifier, int? aspectRatio, int? bitRate);
}
@HostApi(dartHostTestHandler: 'TestPendingRecordingHostApi')
abstract class PendingRecordingHostApi {
int start(int identifier);
}
@FlutterApi()
abstract class PendingRecordingFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestRecordingHostApi')
abstract class RecordingHostApi {
void close(int identifier);
void pause(int identifier);
void resume(int identifier);
void stop(int identifier);
}
@FlutterApi()
abstract class RecordingFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestImageCaptureHostApi')
abstract class ImageCaptureHostApi {
void create(int identifier, int? targetRotation, int? flashMode,
int? resolutionSelectorId);
void setFlashMode(int identifier, int flashMode);
@async
String takePicture(int identifier);
void setTargetRotation(int identifier, int rotation);
}
@HostApi(dartHostTestHandler: 'TestResolutionStrategyHostApi')
abstract class ResolutionStrategyHostApi {
void create(int identifier, ResolutionInfo? boundSize, int? fallbackRule);
}
@HostApi(dartHostTestHandler: 'TestResolutionSelectorHostApi')
abstract class ResolutionSelectorHostApi {
void create(
int identifier,
int? resolutionStrategyIdentifier,
int? aspectRatioStrategyIdentifier,
);
}
@HostApi(dartHostTestHandler: 'TestAspectRatioStrategyHostApi')
abstract class AspectRatioStrategyHostApi {
void create(int identifier, int preferredAspectRatio, int fallbackRule);
}
@FlutterApi()
abstract class CameraStateFlutterApi {
void create(int identifier, CameraStateTypeData type, int? errorIdentifier);
}
@FlutterApi()
abstract class ExposureStateFlutterApi {
void create(
int identifier,
ExposureCompensationRange exposureCompensationRange,
double exposureCompensationStep);
}
@FlutterApi()
abstract class ZoomStateFlutterApi {
void create(int identifier, double minZoomRatio, double maxZoomRatio);
}
@HostApi(dartHostTestHandler: 'TestImageAnalysisHostApi')
abstract class ImageAnalysisHostApi {
void create(int identifier, int? targetRotation, int? resolutionSelectorId);
void setAnalyzer(int identifier, int analyzerIdentifier);
void clearAnalyzer(int identifier);
void setTargetRotation(int identifier, int rotation);
}
@HostApi(dartHostTestHandler: 'TestAnalyzerHostApi')
abstract class AnalyzerHostApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestObserverHostApi')
abstract class ObserverHostApi {
void create(int identifier);
}
@FlutterApi()
abstract class ObserverFlutterApi {
void onChanged(int identifier, int valueIdentifier);
}
@FlutterApi()
abstract class CameraStateErrorFlutterApi {
void create(int identifier, int code);
}
@HostApi(dartHostTestHandler: 'TestLiveDataHostApi')
abstract class LiveDataHostApi {
void observe(int identifier, int observerIdentifier);
void removeObservers(int identifier);
int? getValue(int identifier, LiveDataSupportedTypeData type);
}
@FlutterApi()
abstract class LiveDataFlutterApi {
void create(int identifier, LiveDataSupportedTypeData type);
}
@FlutterApi()
abstract class AnalyzerFlutterApi {
void create(int identifier);
void analyze(int identifier, int imageProxyIdentifier);
}
@HostApi(dartHostTestHandler: 'TestImageProxyHostApi')
abstract class ImageProxyHostApi {
List<int> getPlanes(int identifier);
void close(int identifier);
}
@FlutterApi()
abstract class ImageProxyFlutterApi {
void create(int identifier, int format, int height, int width);
}
@FlutterApi()
abstract class PlaneProxyFlutterApi {
void create(int identifier, Uint8List buffer, int pixelStride, int rowStride);
}
@HostApi(dartHostTestHandler: 'TestQualitySelectorHostApi')
abstract class QualitySelectorHostApi {
void create(int identifier, List<VideoQualityData> videoQualityDataList,
int? fallbackStrategyId);
ResolutionInfo getResolution(int cameraInfoId, VideoQuality quality);
}
@HostApi(dartHostTestHandler: 'TestFallbackStrategyHostApi')
abstract class FallbackStrategyHostApi {
void create(int identifier, VideoQuality quality,
VideoResolutionFallbackRule fallbackRule);
}
@HostApi(dartHostTestHandler: 'TestCameraControlHostApi')
abstract class CameraControlHostApi {
@async
void enableTorch(int identifier, bool torch);
@async
void setZoomRatio(int identifier, double ratio);
@async
int? startFocusAndMetering(int identifier, int focusMeteringActionId);
@async
void cancelFocusAndMetering(int identifier);
@async
int? setExposureCompensationIndex(int identifier, int index);
}
@FlutterApi()
abstract class CameraControlFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestFocusMeteringActionHostApi')
abstract class FocusMeteringActionHostApi {
void create(int identifier, List<MeteringPointInfo> meteringPointInfos,
bool? disableAutoCancel);
}
@HostApi(dartHostTestHandler: 'TestFocusMeteringResultHostApi')
abstract class FocusMeteringResultHostApi {
bool isFocusSuccessful(int identifier);
}
@FlutterApi()
abstract class FocusMeteringResultFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestMeteringPointHostApi')
abstract class MeteringPointHostApi {
void create(
int identifier, double x, double y, double? size, int cameraInfoId);
double getDefaultPointSize();
}
@HostApi(dartHostTestHandler: 'TestCaptureRequestOptionsHostApi')
abstract class CaptureRequestOptionsHostApi {
void create(int identifier, Map<int, Object?> options);
}
@HostApi(dartHostTestHandler: 'TestCamera2CameraControlHostApi')
abstract class Camera2CameraControlHostApi {
void create(int identifier, int cameraControlIdentifier);
@async
void addCaptureRequestOptions(
int identifier, int captureRequestOptionsIdentifier);
}
| packages/packages/camera/camera_android_camerax/pigeons/camerax_library.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/pigeons/camerax_library.dart",
"repo_id": "packages",
"token_count": 4516
} | 928 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camera_state_error.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'camera_state_error_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('CameraStateError', () {
test(
'FlutterAPI create makes call to create CameraStateError instance with expected identifier',
() {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraStateErrorFlutterApiImpl api = CameraStateErrorFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
const int code = 23;
api.create(
instanceIdentifier,
code,
);
// Test instance type.
final Object? instance =
instanceManager.getInstanceWithWeakReference(instanceIdentifier);
expect(
instance,
isA<CameraStateError>(),
);
// Test instance properties.
final CameraStateError cameraStateError = instance! as CameraStateError;
expect(cameraStateError.code, equals(code));
});
});
}
| packages/packages/camera/camera_android_camerax/test/camera_state_error_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/camera_state_error_test.dart",
"repo_id": "packages",
"token_count": 578
} | 929 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/focus_metering_result.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/metering_point.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'focus_metering_result_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
MeteringPoint,
TestFocusMeteringResultHostApi,
TestInstanceManagerHostApi
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('FocusMeteringResult', () {
tearDown(() => TestCameraHostApi.setup(null));
test('isFocusSuccessful returns expected result', () async {
final MockTestFocusMeteringResultHostApi mockApi =
MockTestFocusMeteringResultHostApi();
TestFocusMeteringResultHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final FocusMeteringResult focusMeteringResult =
FocusMeteringResult.detached(
instanceManager: instanceManager,
);
const int focusMeteringResultIdentifier = 5;
instanceManager.addHostCreatedInstance(
focusMeteringResult,
focusMeteringResultIdentifier,
onCopy: (_) =>
FocusMeteringResult.detached(instanceManager: instanceManager),
);
when(mockApi.isFocusSuccessful(focusMeteringResultIdentifier))
.thenAnswer((_) => false);
expect(await focusMeteringResult.isFocusSuccessful(), isFalse);
verify(mockApi.isFocusSuccessful(focusMeteringResultIdentifier));
});
test('flutterApiCreate makes call to add instance to instance manager', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final FocusMeteringResultFlutterApiImpl flutterApi =
FocusMeteringResultFlutterApiImpl(
instanceManager: instanceManager,
);
const int focusMeteringResultIdentifier = 37;
flutterApi.create(focusMeteringResultIdentifier);
expect(
instanceManager
.getInstanceWithWeakReference(focusMeteringResultIdentifier),
isA<FocusMeteringResult>());
});
});
}
| packages/packages/camera/camera_android_camerax/test/focus_metering_result_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/focus_metering_result_test.dart",
"repo_id": "packages",
"token_count": 936
} | 930 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/pending_recording_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:camera_android_camerax/src/recording.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestPendingRecordingHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestPendingRecordingHostApi extends _i1.Mock
implements _i2.TestPendingRecordingHostApi {
MockTestPendingRecordingHostApi() {
_i1.throwOnMissingStub(this);
}
@override
int start(int? identifier) => (super.noSuchMethod(
Invocation.method(
#start,
[identifier],
),
returnValue: 0,
) as int);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i2.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [Recording].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockRecording extends _i1.Mock implements _i3.Recording {
MockRecording() {
_i1.throwOnMissingStub(this);
}
@override
_i4.Future<void> close() => (super.noSuchMethod(
Invocation.method(
#close,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> pause() => (super.noSuchMethod(
Invocation.method(
#pause,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> resume() => (super.noSuchMethod(
Invocation.method(
#resume,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> stop() => (super.noSuchMethod(
Invocation.method(
#stop,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
| packages/packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart",
"repo_id": "packages",
"token_count": 1347
} | 931 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/resolution_strategy_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestResolutionStrategyHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestResolutionStrategyHostApi extends _i1.Mock
implements _i2.TestResolutionStrategyHostApi {
MockTestResolutionStrategyHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
_i3.ResolutionInfo? boundSize,
int? fallbackRule,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
boundSize,
fallbackRule,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i2.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart",
"repo_id": "packages",
"token_count": 799
} | 932 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('chrome') // Uses web-only Flutter SDK
library;
import 'dart:convert';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:cross_file/cross_file.dart';
import 'package:test/test.dart';
import 'package:web/web.dart' as html;
const String expectedStringContents = 'Hello, world! I ❤ ñ! 空手';
final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents));
final html.File textFile =
html.File(<JSUint8Array>[bytes.toJS].toJS, 'hello.txt');
final String textFileUrl =
// TODO(kevmoo): drop ignore when pkg:web constraint excludes v0.3
// ignore: unnecessary_cast
html.URL.createObjectURL(textFile as JSObject);
void main() {
group('Create with an objectUrl', () {
final XFile file = XFile(textFileUrl);
test('Can be read as a string', () async {
expect(await file.readAsString(), equals(expectedStringContents));
});
test('Can be read as bytes', () async {
expect(await file.readAsBytes(), equals(bytes));
});
test('Can be read as a stream', () async {
expect(await file.openRead().first, equals(bytes));
});
test('Stream can be sliced', () async {
expect(await file.openRead(2, 5).first, equals(bytes.sublist(2, 5)));
});
});
group('Create from data', () {
final XFile file = XFile.fromData(bytes);
test('Can be read as a string', () async {
expect(await file.readAsString(), equals(expectedStringContents));
});
test('Can be read as bytes', () async {
expect(await file.readAsBytes(), equals(bytes));
});
test('Can be read as a stream', () async {
expect(await file.openRead().first, equals(bytes));
});
test('Stream can be sliced', () async {
expect(await file.openRead(2, 5).first, equals(bytes.sublist(2, 5)));
});
});
group('Blob backend', () {
final XFile file = XFile(textFileUrl);
test('Stores data as a Blob', () async {
// Read the blob from its path 'natively'
final html.Response response =
await html.window.fetch(file.path.toJS).toDart;
final JSAny arrayBuffer = await response.arrayBuffer().toDart;
final ByteBuffer data = (arrayBuffer as JSArrayBuffer).toDart;
expect(data.asUint8List(), equals(bytes));
});
test('Data may be purged from the blob!', () async {
html.URL.revokeObjectURL(file.path);
expect(() async {
await file.readAsBytes();
}, throwsException);
});
});
group('saveTo(..)', () {
const String crossFileDomElementId = '__x_file_dom_element';
group('CrossFile saveTo(..)', () {
test('creates a DOM container', () async {
final XFile file = XFile.fromData(bytes);
await file.saveTo('');
final html.Element? container =
html.document.querySelector('#$crossFileDomElementId');
expect(container, isNotNull);
});
test('create anchor element', () async {
final XFile file = XFile.fromData(bytes, name: textFile.name);
await file.saveTo('path');
final html.Element container =
html.document.querySelector('#$crossFileDomElementId')!;
late html.HTMLAnchorElement element;
for (int i = 0; i < container.childNodes.length; i++) {
final html.Element test = container.children.item(i)!;
if (test.tagName == 'A') {
element = test as html.HTMLAnchorElement;
break;
}
}
// if element is not found, the `firstWhere` call will throw StateError.
expect(element.href, file.path);
expect(element.download, file.name);
});
test('anchor element is clicked', () async {
final html.HTMLAnchorElement mockAnchor =
html.document.createElement('a') as html.HTMLAnchorElement;
final CrossFileTestOverrides overrides = CrossFileTestOverrides(
createAnchorElement: (_, __) => mockAnchor,
);
final XFile file =
XFile.fromData(bytes, name: textFile.name, overrides: overrides);
bool clicked = false;
mockAnchor.onClick.listen((html.MouseEvent event) => clicked = true);
await file.saveTo('path');
expect(clicked, true);
});
});
});
}
| packages/packages/cross_file/test/x_file_html_test.dart/0 | {
"file_path": "packages/packages/cross_file/test/x_file_html_test.dart",
"repo_id": "packages",
"token_count": 1712
} | 933 |
# 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.
version:
revision: cd41fdd495f6944ecd3506c21e94c6567b073278
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: android
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: ios
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: linux
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: macos
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: web
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
- platform: windows
create_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
base_revision: cd41fdd495f6944ecd3506c21e94c6567b073278
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| packages/packages/dynamic_layouts/example/.metadata/0 | {
"file_path": "packages/packages/dynamic_layouts/example/.metadata",
"repo_id": "packages",
"token_count": 713
} | 934 |
name: example
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.1.0
dependencies:
cupertino_icons: ^1.0.5
dynamic_layouts:
path: ../
flutter:
sdk: flutter
dev_dependencies:
flutter_lints: ^2.0.0
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/dynamic_layouts/example/pubspec.yaml/0 | {
"file_path": "packages/packages/dynamic_layouts/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 148
} | 935 |
name: dynamic_layouts
description: Widgets for building dynamic grid layouts.
version: 0.0.1+1
issue_tracker: https://github.com/flutter/flutter/labels/p%3A%20dynamic_layouts
repository: https://github.com/flutter/packages/tree/main/packages/dynamic_layouts
# Temporarily unpublished while in process of releasing full package in multiple stages.
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
| packages/packages/dynamic_layouts/pubspec.yaml/0 | {
"file_path": "packages/packages/dynamic_layouts/pubspec.yaml",
"repo_id": "packages",
"token_count": 182
} | 936 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.espresso">
</manifest>
| packages/packages/espresso/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/espresso/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 42
} | 937 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.flutter.packages.file_selector_android">
</manifest>
| packages/packages/file_selector/file_selector_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 49
} | 938 |
// 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_android/file_selector_android.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'home_page.dart';
import 'open_image_page.dart';
import 'open_multiple_images_page.dart';
import 'open_text_page.dart';
/// Entry point for integration tests that require espresso.
@pragma('vm:entry-point')
void integrationTestMain() {
enableFlutterDriverExtension();
main();
}
void main() {
FileSelectorPlatform.instance = FileSelectorAndroid();
runApp(const MyApp());
}
/// MyApp is the Main Application.
class MyApp extends StatelessWidget {
/// Default Constructor
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'File Selector Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const HomePage(),
routes: <String, WidgetBuilder>{
'/open/image': (BuildContext context) => const OpenImagePage(),
'/open/images': (BuildContext context) =>
const OpenMultipleImagesPage(),
'/open/text': (BuildContext context) => const OpenTextPage(),
},
);
}
}
| packages/packages/file_selector/file_selector_android/example/lib/main.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/example/lib/main.dart",
"repo_id": "packages",
"token_count": 506
} | 939 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v10.0.1), 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_windows/src/messages.g.dart';
class _TestFileSelectorApiCodec extends StandardMessageCodec {
const _TestFileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileDialogResult) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is SelectionOptions) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is TypeGroup) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileDialogResult.decode(readValue(buffer)!);
case 129:
return SelectionOptions.decode(readValue(buffer)!);
case 130:
return TypeGroup.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestFileSelectorApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = _TestFileSelectorApiCodec();
FileDialogResult showOpenDialog(SelectionOptions options,
String? initialDirectory, String? confirmButtonText);
FileDialogResult showSaveDialog(
SelectionOptions options,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText);
static void setup(TestFileSelectorApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showOpenDialog', 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.FileSelectorApi.showOpenDialog was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SelectionOptions? arg_options = (args[0] as SelectionOptions?);
assert(arg_options != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showOpenDialog was null, expected non-null SelectionOptions.');
final String? arg_initialDirectory = (args[1] as String?);
final String? arg_confirmButtonText = (args[2] as String?);
final FileDialogResult output = api.showOpenDialog(
arg_options!, arg_initialDirectory, arg_confirmButtonText);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showSaveDialog', 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.FileSelectorApi.showSaveDialog was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SelectionOptions? arg_options = (args[0] as SelectionOptions?);
assert(arg_options != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showSaveDialog was null, expected non-null SelectionOptions.');
final String? arg_initialDirectory = (args[1] as String?);
final String? arg_suggestedName = (args[2] as String?);
final String? arg_confirmButtonText = (args[3] as String?);
final FileDialogResult output = api.showSaveDialog(arg_options!,
arg_initialDirectory, arg_suggestedName, arg_confirmButtonText);
return <Object?>[output];
});
}
}
}
}
| packages/packages/file_selector/file_selector_windows/test/test_api.g.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/test/test_api.g.dart",
"repo_id": "packages",
"token_count": 1944
} | 940 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart';
/// A more functional demo of the usage of the adaptive layout helper widgets.
/// Specifically, it is built using an [AdaptiveLayout] and uses static helpers
/// from [AdaptiveScaffold].
///
/// Modeled off of the example on the Material 3 page regarding adaptive layouts.
/// For a more clear cut example usage, please look at adaptive_layout_demo.dart
/// or adaptive_scaffold_demo.dart
void main() {
runApp(const MyApp());
}
/// The main application widget for this example.
class MyApp extends StatelessWidget {
/// Creates a const main application widget.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Adaptive Layout Demo',
routes: <String, Widget Function(BuildContext)>{
_ExtractRouteArguments.routeName: (_) => const _ExtractRouteArguments()
},
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
home: const MyHomePage(),
);
}
}
/// Creates an example mail page using [AdaptiveLayout].
class MyHomePage extends StatefulWidget {
/// Creates a const [MyHomePage].
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with TickerProviderStateMixin, ChangeNotifier {
// A listener used for the controllers to reanimate the staggered animation of
// the navigation elements.
ValueNotifier<bool?> showGridView = ValueNotifier<bool?>(false);
// Override the application's directionality.
TextDirection directionalityOverride = TextDirection.ltr;
// The index of the selected mail card.
int? selected;
void selectCard(int? index) {
setState(() {
selected = index;
});
}
// The index of the navigation screen. Only impacts body/secondaryBody
int _navigationIndex = 0;
// The controllers used for the staggered animation of the navigation elements.
late AnimationController _inboxIconSlideController;
late AnimationController _articleIconSlideController;
late AnimationController _chatIconSlideController;
late AnimationController _videoIconSlideController;
@override
void initState() {
showGridView.addListener(() {
Navigator.popUntil(
context, (Route<dynamic> route) => route.settings.name == '/');
_inboxIconSlideController
..reset()
..forward();
_articleIconSlideController
..reset()
..forward();
_chatIconSlideController
..reset()
..forward();
_videoIconSlideController
..reset()
..forward();
});
_inboxIconSlideController = AnimationController(
duration: const Duration(milliseconds: 100),
vsync: this,
)..forward();
_articleIconSlideController = AnimationController(
duration: const Duration(milliseconds: 120),
vsync: this,
)..forward();
_chatIconSlideController = AnimationController(
duration: const Duration(milliseconds: 140),
vsync: this,
)..forward();
_videoIconSlideController = AnimationController(
duration: const Duration(milliseconds: 160),
vsync: this,
)..forward();
super.initState();
}
@override
void dispose() {
_inboxIconSlideController.dispose();
_articleIconSlideController.dispose();
_chatIconSlideController.dispose();
_videoIconSlideController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Widget trailingNavRail = Expanded(
child: Column(
children: <Widget>[
const Divider(color: Colors.white, thickness: 1.5),
const SizedBox(height: 10),
Row(children: <Widget>[
const SizedBox(width: 22),
Text('Folders',
style: TextStyle(fontSize: 13, color: Colors.grey[700]))
]),
const SizedBox(height: 22),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Text('Freelance', overflow: TextOverflow.ellipsis),
],
),
const SizedBox(height: 16),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Text('Mortgage', overflow: TextOverflow.ellipsis),
],
),
const SizedBox(height: 16),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text('Taxes', overflow: TextOverflow.ellipsis))
],
),
const SizedBox(height: 16),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text('Receipts', overflow: TextOverflow.ellipsis))
],
),
Expanded(
child: Align(
alignment: Alignment.bottomCenter,
child: SwitchListTile.adaptive(
title: const Text(
'Directionality',
style: TextStyle(fontSize: 12),
),
subtitle: Text(
directionalityOverride == TextDirection.ltr ? 'LTR' : 'RTL',
),
value: directionalityOverride == TextDirection.ltr,
onChanged: (bool value) {
setState(() {
if (value) {
directionalityOverride = TextDirection.ltr;
} else {
directionalityOverride = TextDirection.rtl;
}
});
},
),
),
),
],
),
);
// These are the destinations used within the AdaptiveScaffold navigation
// builders.
const List<NavigationDestination> destinations = <NavigationDestination>[
NavigationDestination(
label: 'Inbox',
icon: Icon(Icons.inbox),
),
NavigationDestination(
label: 'Articles',
icon: Icon(Icons.article_outlined),
),
NavigationDestination(
label: 'Chat',
icon: Icon(Icons.chat_bubble_outline),
),
NavigationDestination(
label: 'Video',
icon: Icon(Icons.video_call_outlined),
)
];
// Updating the listener value.
showGridView.value = Breakpoints.mediumAndUp.isActive(context);
return Directionality(
textDirection: directionalityOverride,
child: Scaffold(
backgroundColor: const Color.fromARGB(255, 234, 227, 241),
// Usage of AdaptiveLayout suite begins here. AdaptiveLayout takes
// LayoutSlots for its variety of screen slots.
body: AdaptiveLayout(
// Each SlotLayout has a config which maps Breakpoints to
// SlotLayoutConfigs.
primaryNavigation: SlotLayout(
config: <Breakpoint, SlotLayoutConfig?>{
// The breakpoint used here is from the Breakpoints class but custom
// Breakpoints can be defined by extending the Breakpoint class
Breakpoints.medium: SlotLayout.from(
// Every SlotLayoutConfig takes a key and a builder. The builder
// is to save memory that would be spent on initialization.
key: const Key('primaryNavigation'),
builder: (_) {
return AdaptiveScaffold.standardNavigationRail(
// Usually it would be easier to use a builder from
// AdaptiveScaffold for these types of navigation but this
// navigation has custom staggered item animations.
onDestinationSelected: (int index) {
setState(() {
_navigationIndex = index;
});
},
selectedIndex: _navigationIndex,
leading: ScaleTransition(
scale: _articleIconSlideController,
child: const _MediumComposeIcon(),
),
backgroundColor: const Color.fromARGB(0, 255, 255, 255),
destinations: <NavigationRailDestination>[
slideInNavigationItem(
begin: -1,
controller: _inboxIconSlideController,
icon: Icons.inbox,
label: 'Inbox',
),
slideInNavigationItem(
begin: -2,
controller: _articleIconSlideController,
icon: Icons.article_outlined,
label: 'Articles',
),
slideInNavigationItem(
begin: -3,
controller: _chatIconSlideController,
icon: Icons.chat_bubble_outline,
label: 'Chat',
),
slideInNavigationItem(
begin: -4,
controller: _videoIconSlideController,
icon: Icons.video_call_outlined,
label: 'Video',
)
],
);
},
),
Breakpoints.large: SlotLayout.from(
key: const Key('Large primaryNavigation'),
// The AdaptiveScaffold builder here greatly simplifies
// navigational elements.
builder: (_) => AdaptiveScaffold.standardNavigationRail(
leading: const _LargeComposeIcon(),
onDestinationSelected: (int index) {
setState(() {
_navigationIndex = index;
});
},
selectedIndex: _navigationIndex,
trailing: trailingNavRail,
extended: true,
destinations:
destinations.map((NavigationDestination destination) {
return AdaptiveScaffold.toRailDestination(destination);
}).toList(),
),
),
},
),
body: SlotLayout(
config: <Breakpoint, SlotLayoutConfig?>{
Breakpoints.standard: SlotLayout.from(
key: const Key('body'),
// The conditional here is for navigation screens. The first
// screen shows the main screen and every other screen shows
// ExamplePage.
builder: (_) => (_navigationIndex == 0)
? Padding(
padding: const EdgeInsets.fromLTRB(0, 32, 0, 0),
child: _ItemList(
selected: selected,
items: _allItems,
selectCard: selectCard,
),
)
: const _ExamplePage(),
),
},
),
secondaryBody: _navigationIndex == 0
? SlotLayout(
config: <Breakpoint, SlotLayoutConfig?>{
Breakpoints.mediumAndUp: SlotLayout.from(
// This overrides the default behavior of the secondaryBody
// disappearing as it is animating out.
outAnimation: AdaptiveScaffold.stayOnScreen,
key: const Key('Secondary Body'),
builder: (_) => SafeArea(
child: _DetailTile(item: _allItems[selected ?? 0]),
),
)
},
)
: null,
bottomNavigation: SlotLayout(
config: <Breakpoint, SlotLayoutConfig?>{
Breakpoints.small: SlotLayout.from(
key: const Key('bottomNavigation'),
// You can define inAnimations or outAnimations to override the
// default offset transition.
outAnimation: AdaptiveScaffold.topToBottom,
builder: (_) => AdaptiveScaffold.standardBottomNavigationBar(
destinations: destinations,
),
)
},
),
),
),
);
}
NavigationRailDestination slideInNavigationItem({
required double begin,
required AnimationController controller,
required IconData icon,
required String label,
}) {
return NavigationRailDestination(
icon: SlideTransition(
position: Tween<Offset>(
begin: Offset(begin, 0),
end: Offset.zero,
).animate(
CurvedAnimation(parent: controller, curve: Curves.easeInOutCubic),
),
child: Icon(icon),
),
label: Text(label),
);
}
}
class _SmallComposeIcon extends StatelessWidget {
const _SmallComposeIcon();
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: const Color.fromARGB(255, 254, 215, 227),
borderRadius: const BorderRadius.all(Radius.circular(15)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 2,
offset: const Offset(0, 2),
),
],
),
width: 50,
height: 50,
child: const Icon(Icons.edit_outlined),
);
}
}
class _MediumComposeIcon extends StatelessWidget {
const _MediumComposeIcon();
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 18),
child: const Icon(Icons.menu),
),
const _SmallComposeIcon(),
]);
}
}
class _LargeComposeIcon extends StatelessWidget {
const _LargeComposeIcon();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(8.0, 5, 0, 12),
child: Column(children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(6, 0, 0, 0),
child: const Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'REPLY',
style: TextStyle(color: Colors.deepPurple, fontSize: 15),
),
Icon(Icons.menu_open, size: 22)
],
),
),
const SizedBox(height: 10),
Container(
alignment: Alignment.centerLeft,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 255, 225, 231),
borderRadius: const BorderRadius.all(Radius.circular(15)),
boxShadow: Breakpoints.mediumAndUp.isActive(context)
? null
: <BoxShadow>[
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 2,
offset: const Offset(0, 2),
),
],
),
width: 200,
height: 50,
child: const Padding(
padding: EdgeInsets.fromLTRB(16.0, 0, 0, 0),
child: Row(
children: <Widget>[
Icon(Icons.edit_outlined),
SizedBox(width: 20),
Center(child: Text('Compose')),
],
),
),
)
]),
);
}
}
typedef _CardSelectedCallback = void Function(int?);
// ItemList creates the list of cards and the search bar.
class _ItemList extends StatelessWidget {
const _ItemList({
required this.items,
required this.selectCard,
required this.selected,
});
final List<_Item> items;
final int? selected;
final _CardSelectedCallback selectCard;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(0, 0, 0, 0),
floatingActionButton: Breakpoints.mediumAndUp.isActive(context)
? null
: const _SmallComposeIcon(),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
prefixIcon: const Padding(
padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Icon(Icons.search),
),
suffixIcon: Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: CircleAvatar(
radius: 18,
child: Image.asset(
'images/plum.png',
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: BorderSide.none,
),
filled: true,
contentPadding: const EdgeInsets.all(25),
hintStyle:
const TextStyle(color: Color.fromARGB(255, 135, 129, 138)),
hintText: 'Search replies',
fillColor: Colors.white,
),
),
),
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) => _ItemListTile(
item: items[index],
email: items[index].emails![0],
selectCard: selectCard,
selected: selected,
),
),
),
],
),
);
}
}
class _ItemListTile extends StatelessWidget {
const _ItemListTile({
required this.item,
required this.email,
required this.selectCard,
required this.selected,
});
final _Item item;
final _Email email;
final int? selected;
final _CardSelectedCallback selectCard;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// The behavior of opening a detail view is different on small screens
// than large screens.
// Small screens open a modal with the detail view while large screens
// simply show the details on the secondaryBody.
selectCard(_allItems.indexOf(item));
if (!Breakpoints.mediumAndUp.isActive(context)) {
Navigator.of(context).pushNamed(_ExtractRouteArguments.routeName,
arguments: _ScreenArguments(item: item, selectCard: selectCard));
} else {
selectCard(_allItems.indexOf(item));
}
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: selected == _allItems.indexOf(item)
? const Color.fromARGB(255, 234, 222, 255)
: const Color.fromARGB(255, 243, 237, 247),
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.zero,
leading: CircleAvatar(
radius: 18,
child: Image.asset(
email.image,
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
email.sender,
style: Theme.of(context).textTheme.bodyLarge,
softWrap: false,
overflow: TextOverflow.clip,
),
const SizedBox(height: 3),
Text(
'${email.time} ago',
style: Theme.of(context).textTheme.bodySmall,
softWrap: false,
overflow: TextOverflow.clip,
),
],
),
trailing: Container(
padding: const EdgeInsets.all(8.0),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(50)),
),
child: Icon(Icons.star_outline, color: Colors.grey[500]),
),
),
const SizedBox(height: 13),
Text(item.title,
style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 9),
Text(email.body.replaceRange(116, email.body.length, '...'),
style: Theme.of(context).textTheme.bodyLarge),
const SizedBox(height: 9),
SizedBox(
width: MediaQuery.of(context).size.width,
child: (email.bodyImage != '')
? Image.asset(email.bodyImage)
: Container(),
),
],
),
),
),
),
);
}
}
class _DetailTile extends StatelessWidget {
const _DetailTile({required this.item});
final _Item item;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: Container(
decoration: const BoxDecoration(
color: Color.fromARGB(255, 245, 241, 248),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
item.title,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 7),
Text(
'${item.emails!.length} Messages',
style: Theme.of(context).textTheme.labelSmall,
)
],
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.all(Radius.circular(15)),
),
child: Icon(
Icons.restore_from_trash,
color: Colors.grey[600],
),
),
const SizedBox(width: 15),
Container(
padding: const EdgeInsets.all(8.0),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.all(Radius.circular(15)),
),
child: Icon(Icons.more_vert,
color: Colors.grey[600]),
)
],
),
),
],
),
const SizedBox(height: 20),
],
),
),
Expanded(
child: ListView.builder(
itemCount: item.emails!.length,
itemBuilder: (BuildContext context, int index) {
final _Email thisEmail = item.emails![index];
return _EmailTile(
sender: thisEmail.sender,
time: thisEmail.time,
senderIcon: thisEmail.image,
recipients: thisEmail.recipients,
body: thisEmail.body,
bodyImage: thisEmail.bodyImage,
);
},
),
),
],
),
),
),
);
}
}
class _EmailTile extends StatelessWidget {
const _EmailTile({
required this.sender,
required this.time,
required this.senderIcon,
required this.recipients,
required this.body,
required this.bodyImage,
});
final String sender;
final String time;
final String senderIcon;
final String recipients;
final String body;
final String bodyImage;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 4),
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
CircleAvatar(
radius: 18,
child: Image.asset(
senderIcon,
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(sender,
style:
TextStyle(color: Colors.grey[850], fontSize: 13)),
const SizedBox(height: 3),
Text('$time ago',
style: Theme.of(context).textTheme.bodySmall),
],
),
const Spacer(),
Container(
padding: const EdgeInsets.all(8.0),
decoration: const BoxDecoration(
color: Color.fromARGB(255, 245, 241, 248),
borderRadius: BorderRadius.all(Radius.circular(50)),
),
child: Icon(Icons.star_outline, color: Colors.grey[500]),
),
],
),
if (recipients != '')
Column(children: <Widget>[
const SizedBox(height: 15),
Text('To $recipients',
style: TextStyle(color: Colors.grey[500], fontSize: 12)),
])
else
Container(),
const SizedBox(height: 15),
Text(body,
style: TextStyle(
color: Colors.grey[700], height: 1.35, fontSize: 14.5)),
const SizedBox(height: 9),
SizedBox(
width: MediaQuery.of(context).size.width,
child:
(bodyImage != '') ? Image.asset(bodyImage) : Container()),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
SizedBox(
width: 126,
child: OutlinedButton(
onPressed: () {},
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromARGB(255, 245, 241, 248),
),
side: MaterialStateProperty.all(
const BorderSide(
width: 0.0, color: Colors.transparent),
),
),
child: Text('Reply',
style:
TextStyle(color: Colors.grey[700], fontSize: 12)),
),
),
SizedBox(
width: 126,
child: OutlinedButton(
onPressed: () {},
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromARGB(255, 245, 241, 248),
),
side: MaterialStateProperty.all(
const BorderSide(
width: 0.0, color: Colors.transparent),
),
),
child: Text(
'Reply all',
style: TextStyle(color: Colors.grey[700], fontSize: 12),
),
),
),
],
),
],
),
),
),
);
}
}
// The ScreenArguments used to pass arguments to the RouteDetailView as a named
// route.
class _ScreenArguments {
_ScreenArguments({
required this.item,
required this.selectCard,
});
final _Item item;
final _CardSelectedCallback selectCard;
}
class _ExtractRouteArguments extends StatelessWidget {
const _ExtractRouteArguments();
static const String routeName = '/detailView';
@override
Widget build(BuildContext context) {
final _ScreenArguments args =
ModalRoute.of(context)!.settings.arguments! as _ScreenArguments;
return _RouteDetailView(item: args.item, selectCard: args.selectCard);
}
}
class _RouteDetailView extends StatelessWidget {
const _RouteDetailView({
required this.item,
required this.selectCard,
});
final _Item item;
final _CardSelectedCallback selectCard;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: TextButton(
onPressed: () {
Navigator.popUntil(context,
(Route<dynamic> route) => route.settings.name == '/');
selectCard(null);
},
child: const Icon(Icons.arrow_back),
),
),
Expanded(child: _DetailTile(item: item)),
],
),
);
}
}
class _ExamplePage extends StatelessWidget {
const _ExamplePage();
@override
Widget build(BuildContext context) {
return Container(color: Colors.grey);
}
}
class _Item {
const _Item({
required this.title,
required this.emails,
});
final String title;
final List<_Email>? emails;
}
class _Email {
const _Email({
required this.sender,
required this.recipients,
required this.image,
required this.time,
required this.body,
required this.bodyImage,
});
final String sender;
final String recipients;
final String image;
final String time;
final String body;
final String bodyImage;
}
/// List of items, each representing a thread of emails which will populate
/// the different layouts.
const List<_Item> _allItems = <_Item>[
_Item(
title: 'Dinner Club',
emails: <_Email>[
_Email(
sender: 'So Duri',
recipients: 'me, Ziad and Lily',
image: 'images/strawberry.png',
time: '20 min',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec gravida tellus, vel scelerisque nisi. Mauris egestas, augue nec dictum tempus, diam sapien luctus odio, a posuere sem neque at nulla. Vivamus pulvinar nisi et dapibus dapibus. Donec euismod pellentesque ultrices. Vivamus quis condimentum metus, in venenatis lorem. Proin suscipit tincidunt eleifend. Praesent a nisi ac ipsum sodales gravida.',
bodyImage: '',
),
_Email(
sender: 'Me',
recipients: 'me, Ziad, and Lily',
image: 'images/plum.png',
time: '4 min',
body:
'Donec non mollis nulla, in varius mi. Ut id lorem eget felis lobortis tincidunt. Curabitur facilisis ex vitae tristique efficitur. Aenean eget augue finibus, tempor eros vitae, tempor neque. In sed pellentesque elit. Donec lacus lacus, malesuada in tincidunt sit amet, condimentum vel enim. Cras dapibus erat quis nisl hendrerit, vel pretium turpis condimentum. ',
bodyImage: ''),
_Email(
sender: 'Ziad Aouad',
recipients: 'me, Ziad and Lily',
image: 'images/mushroom.png',
time: '2 min',
body:
'Duis sit amet nibh a diam placerat aliquam nec ac mi. Aenean hendrerit efficitur tellus, non pharetra eros posuere sit amet. Maecenas interdum lacinia eleifend. Nam efficitur tellus et dolor vestibulum, non dictum quam iaculis. Aenean id nulla ut erat placerat feugiat. Mauris in quam metus. Aliquam erat volutpat.',
bodyImage: ''),
],
),
_Item(
title: '7 Best Yoga Poses',
emails: <_Email>[
_Email(
sender: 'Elaine Howley',
time: '2 hours',
body:
'Curabitur tincidunt purus at vulputate mattis. Nam lectus urna, varius eget quam in, ultricies ultrices libero. Curabitur rutrum ultricies varius. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vulputate auctor est, non semper velit eleifend sit amet.',
image: 'images/potato.png',
bodyImage: 'images/avocado.png',
recipients: '',
),
],
),
_Item(
title: 'A Programming Language',
emails: <_Email>[
_Email(
sender: 'Laney Mansell',
time: '10 min',
body:
'Cras egestas ultricies elit, vitae interdum lorem aliquam et. Donec quis arcu a quam tempor rutrum vitae in lectus. Nullam elit nunc, lacinia sed luctus non, mollis id nulla. Morbi luctus turpis sapien, id molestie ante maximus vel. Vivamus sagittis consequat nisl nec placerat.',
image: 'images/habanero.png',
bodyImage: '',
recipients: '',
),
],
),
];
| packages/packages/flutter_adaptive_scaffold/example/lib/main.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/lib/main.dart",
"repo_id": "packages",
"token_count": 19734
} | 941 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
const Set<TargetPlatform> _desktop = <TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows
};
const Set<TargetPlatform> _mobile = <TargetPlatform>{
TargetPlatform.android,
TargetPlatform.fuchsia,
TargetPlatform.iOS,
};
/// A group of standard breakpoints built according to the material
/// specifications for screen width size.
///
/// See also:
///
/// * [AdaptiveScaffold], which uses some of these Breakpoints as defaults.
class Breakpoints {
/// This is a standard breakpoint that can be used as a fallthrough in the
/// case that no other breakpoint is active.
///
/// It is active from a width of -1 dp to infinity.
static const Breakpoint standard = WidthPlatformBreakpoint(begin: -1);
/// A window whose width is less than 600 dp and greater than 0 dp.
static const Breakpoint small = WidthPlatformBreakpoint(begin: 0, end: 600);
/// A window whose width is greater than 0 dp.
static const Breakpoint smallAndUp = WidthPlatformBreakpoint(begin: 0);
/// A desktop screen whose width is less than 600 dp and greater than 0 dp.
static const Breakpoint smallDesktop =
WidthPlatformBreakpoint(begin: 0, end: 600, platform: _desktop);
/// A mobile screen whose width is less than 600 dp and greater than 0 dp.
static const Breakpoint smallMobile =
WidthPlatformBreakpoint(begin: 0, end: 600, platform: _mobile);
/// A window whose width is between 600 dp and 840 dp.
static const Breakpoint medium =
WidthPlatformBreakpoint(begin: 600, end: 840);
/// A window whose width is greater than 600 dp.
static const Breakpoint mediumAndUp = WidthPlatformBreakpoint(begin: 600);
/// A desktop window whose width is between 600 dp and 840 dp.
static const Breakpoint mediumDesktop =
WidthPlatformBreakpoint(begin: 600, end: 840, platform: _desktop);
/// A mobile window whose width is between 600 dp and 840 dp.
static const Breakpoint mediumMobile =
WidthPlatformBreakpoint(begin: 600, end: 840, platform: _mobile);
/// A window whose width is greater than 840 dp.
static const Breakpoint large = WidthPlatformBreakpoint(begin: 840);
/// A desktop window whose width is greater than 840 dp.
static const Breakpoint largeDesktop =
WidthPlatformBreakpoint(begin: 840, platform: _desktop);
/// A mobile window whose width is greater than 840 dp.
static const Breakpoint largeMobile =
WidthPlatformBreakpoint(begin: 840, platform: _mobile);
}
/// A class that can be used to quickly generate [Breakpoint]s that depend on
/// the screen width and the platform.
class WidthPlatformBreakpoint extends Breakpoint {
/// Returns a const [Breakpoint] with the given constraints.
const WidthPlatformBreakpoint({this.begin, this.end, this.platform});
/// The beginning width dp value. If left null then the [Breakpoint] will have
/// no lower bound.
final double? begin;
/// The end width dp value. If left null then the [Breakpoint] will have no
/// upper bound.
final double? end;
/// A Set of [TargetPlatform]s that the [Breakpoint] will be active on. If
/// left null then it will be active on all platforms.
final Set<TargetPlatform>? platform;
@override
bool isActive(BuildContext context) {
final TargetPlatform host = Theme.of(context).platform;
final bool isRightPlatform = platform?.contains(host) ?? true;
// Null boundaries are unbounded, assign the max/min of their associated
// direction on a number line.
final double width = MediaQuery.of(context).size.width;
final double lowerBound = begin ?? double.negativeInfinity;
final double upperBound = end ?? double.infinity;
return width >= lowerBound && width < upperBound && isRightPlatform;
}
}
/// An interface to define the conditions that distinguish between types of
/// screens.
///
/// Adaptive apps usually display differently depending on the screen type: a
/// compact layout for smaller screens, or a relaxed layout for larger screens.
/// Override this class by defining `isActive` to fetch the screen property
/// (usually `MediaQuery.of`) and return true if the condition is met.
///
/// Breakpoints do not need to be exclusive because they are tested in order
/// with the last Breakpoint active taking priority.
///
/// If the condition is only based on the screen width and/or the device type,
/// use [WidthPlatformBreakpoint] to define the [Breakpoint].
///
/// See also:
///
/// * [SlotLayout.config], which uses breakpoints to dictate the layout of the
/// screen.
abstract class Breakpoint {
/// Returns a const [Breakpoint].
const Breakpoint();
/// A method that returns true based on conditions related to the context of
/// the screen such as MediaQuery.of(context).size.width.
bool isActive(BuildContext context);
}
| packages/packages/flutter_adaptive_scaffold/lib/src/breakpoints.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/lib/src/breakpoints.dart",
"repo_id": "packages",
"token_count": 1354
} | 942 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/flutter_image/example/android/gradle.properties/0 | {
"file_path": "packages/packages/flutter_image/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 31
} | 943 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 3.0.1
* Replaces `flutter pub add --dev` with `dev:` in README.md.
## 3.0.0
* Updated `package:lints` dependency to version 3.0.0, with the following changes:
* added `collection_methods_unrelated_type`
* added `dangling_library_doc_comments`
* added `implicit_call_tearoffs`
* added `secure_pubspec_urls`
* added `type_literal_in_constant_pattern`
* added `unnecessary_to_list_in_spreads`
* added `use_string_in_part_of_directives`
* added `use_super_parameters`
* removed `iterable_contains_unrelated_type`
* removed `list_remove_unrelated_type`
* removed `no_wildcard_variable_uses`
* removed `prefer_equal_for_default_values`
* removed `prefer_void_to_null`
* Updates minimum supported SDK version to Flutter 3.10 / Dart 3.0.
## 2.0.3
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.0.2
* Update links to the old linter site in the README and example to point to dart.dev.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 2.0.1
* Updated readme to document suggestion process for new lints
## 2.0.0
* Added the following lints:
* `sort_child_properties_last`
* `use_build_context_synchronously`
* Updated `package:lints` dependency to version 2.0.0, which added the following lints:
* `depend_on_referenced_packages`
* `library_private_types_in_public_api`
* `no_leading_underscores_for_library_prefixes`
* `no_leading_underscores_for_local_identifiers`
* `null_check_on_nullable_type_parameter`
* `prefer_interpolation_to_compose_strings`
* `unnecessary_constructor_name`
* `unnecessary_late`
* `unnecessary_null_aware_assignments`
* `unnecessary_nullable_for_final_variable_declarations`
* Bumped the minimum required Dart SDK version to 2.17
## 1.0.4
* Small update to readme
## 1.0.3
* More small updates to readme
## 1.0.2
* Small updates to readme
## 1.0.1
* Added an example project
## 1.0.0
* Initial release
| packages/packages/flutter_lints/CHANGELOG.md/0 | {
"file_path": "packages/packages/flutter_lints/CHANGELOG.md",
"repo_id": "packages",
"token_count": 781
} | 944 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;
import '../shared/markdown_demo_widget.dart';
// ignore_for_file: public_member_api_docs
const String _data = '''
## Centered Title
###### ※ ※ ※
''';
const String _notes = '''
# Centered Title Demo
---
## Overview
This example demonstrates how to implement a centered headline using a custom builder.
''';
// TODO(goderbauer): Restructure the examples to avoid this ignore, https://github.com/flutter/flutter/issues/110208.
// ignore: avoid_implementing_value_types
class CenteredHeaderDemo extends StatelessWidget implements MarkdownDemoWidget {
const CenteredHeaderDemo({super.key});
static const String _title = 'Centered Header Demo';
@override
String get title => CenteredHeaderDemo._title;
@override
String get description =>
'An example of using a user defined builder to implement a centered headline';
@override
Future<String> get data => Future<String>.value(_data);
@override
Future<String> get notes => Future<String>.value(_notes);
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: data,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Markdown(
data: snapshot.data!,
builders: <String, MarkdownElementBuilder>{
'h2': CenteredHeaderBuilder(),
'h6': CenteredHeaderBuilder(),
},
);
} else {
return const CircularProgressIndicator();
}
},
);
}
}
class CenteredHeaderBuilder extends MarkdownElementBuilder {
@override
Widget visitText(md.Text text, TextStyle? preferredStyle) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(text.text, style: preferredStyle),
],
);
}
}
| packages/packages/flutter_markdown/example/lib/demos/centered_header_demo.dart/0 | {
"file_path": "packages/packages/flutter_markdown/example/lib/demos/centered_header_demo.dart",
"repo_id": "packages",
"token_count": 755
} | 945 |
name: flutter_markdown_example
description: Demonstrates how to use the flutter_markdown package.
publish_to: none
environment:
sdk: ^3.2.0
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
flutter_markdown:
path: ../
markdown: ^7.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- assets/
fonts:
- family: 'Roboto Mono'
fonts:
- asset: fonts/RobotoMono-Regular.ttf
uses-material-design: true
| packages/packages/flutter_markdown/example/pubspec.yaml/0 | {
"file_path": "packages/packages/flutter_markdown/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 203
} | 946 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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('MarkdownBody shrinkWrap test', () {
testWidgets(
'Given a MarkdownBody with shrinkWrap=true '
'Then it wraps its content',
(WidgetTester tester) async {
await tester.pumpWidget(boilerplate(
const Stack(
children: <Widget>[
Text('shrinkWrap=true'),
Align(
alignment: Alignment.bottomCenter,
child: MarkdownBody(
data: 'This is a [link](https://flutter.dev/)',
),
),
],
),
));
final Rect stackRect = tester.getRect(find.byType(Stack));
final Rect textRect = tester.getRect(find.text('shrinkWrap=true'));
final Rect markdownBodyRect = tester.getRect(find.byType(MarkdownBody));
// The Text should be on the top of the Stack
expect(textRect.top, equals(stackRect.top));
expect(textRect.bottom, lessThan(stackRect.bottom));
// The MarkdownBody should be on the bottom of the Stack
expect(markdownBodyRect.top, greaterThan(stackRect.top));
expect(markdownBodyRect.bottom, equals(stackRect.bottom));
},
);
testWidgets(
'Given a MarkdownBody with shrinkWrap=false '
'Then it expands to the maximum allowed height',
(WidgetTester tester) async {
await tester.pumpWidget(boilerplate(
const Stack(
children: <Widget>[
Text('shrinkWrap=false test'),
Align(
alignment: Alignment.bottomCenter,
child: MarkdownBody(
data: 'This is a [link](https://flutter.dev/)',
shrinkWrap: false,
),
),
],
),
));
final Rect stackRect = tester.getRect(find.byType(Stack));
final Rect textRect =
tester.getRect(find.text('shrinkWrap=false test'));
final Rect markdownBodyRect = tester.getRect(find.byType(MarkdownBody));
// The Text should be on the top of the Stack
expect(textRect.top, equals(stackRect.top));
expect(textRect.bottom, lessThan(stackRect.bottom));
// The MarkdownBody should take all Stack's height
expect(markdownBodyRect.top, equals(stackRect.top));
expect(markdownBodyRect.bottom, equals(stackRect.bottom));
},
);
});
}
| packages/packages/flutter_markdown/test/markdown_body_shrink_wrap_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/markdown_body_shrink_wrap_test.dart",
"repo_id": "packages",
"token_count": 1230
} | 947 |
# Specify analysis options.
include: ../../analysis_options.yaml
linter:
rules:
public_member_api_docs: false # Standalone executable, no public API
| packages/packages/flutter_migrate/analysis_options.yaml/0 | {
"file_path": "packages/packages/flutter_migrate/analysis_options.yaml",
"repo_id": "packages",
"token_count": 50
} | 948 |
// 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:process/process.dart';
import '../base/command.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/project.dart';
import '../compute.dart';
import '../environment.dart';
import '../manifest.dart';
import '../result.dart';
import '../utils.dart';
class MigrateStartCommand extends MigrateCommand {
MigrateStartCommand({
bool verbose = false,
required this.logger,
required this.fileSystem,
required this.processManager,
this.standalone = false,
}) : _verbose = verbose,
migrateUtils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: processManager,
) {
argParser.addOption(
'staging-directory',
help:
'Specifies the custom migration staging directory used to stage and edit proposed changes. '
'This path can be absolute or relative to the flutter project root.',
valueHelp: 'path',
);
argParser.addOption(
'project-directory',
help: 'The root directory of the flutter project.',
valueHelp: 'path',
);
argParser.addOption(
'platforms',
help:
'Restrict the tool to only migrate the listed platforms. By default all platforms generated by '
'flutter create will be migrated. To indicate the project root, use the `root` platform',
valueHelp: 'root,android,ios,windows...',
);
argParser.addFlag(
'delete-temp-directories',
help:
'Indicates if the temporary directories created by the migrate tool will be deleted.',
);
argParser.addOption(
'base-app-directory',
help:
'The directory containing the base reference app. This is used as the common ancestor in a 3 way merge. '
'Providing this directory will prevent the tool from generating its own. This is primarily used '
'in testing and CI.',
valueHelp: 'path',
hide: !verbose,
);
argParser.addOption(
'target-app-directory',
help:
'The directory containing the target reference app. This is used as the target app in 3 way merge. '
'Providing this directory will prevent the tool from generating its own. This is primarily used '
'in testing and CI.',
valueHelp: 'path',
hide: !verbose,
);
argParser.addFlag(
'allow-fallback-base-revision',
help:
'If a base revision cannot be determined, this flag enables using flutter 1.0.0 as a fallback base revision. '
'Using this fallback will typically produce worse quality migrations and possibly more conflicts.',
);
argParser.addOption(
'base-revision',
help:
'Manually sets the base revision to generate the base ancestor reference app with. This may be used '
'if the tool is unable to determine an appropriate base revision.',
valueHelp: 'git revision hash',
);
argParser.addOption(
'target-revision',
help:
'Manually sets the target revision to generate the target reference app with. Passing this indicates '
'that the current flutter sdk version is not the version that should be migrated to.',
valueHelp: 'git revision hash',
);
argParser.addFlag(
'prefer-two-way-merge',
negatable: false,
help:
'Avoid three way merges when possible. Enabling this effectively ignores the base ancestor reference '
'files when a merge is required, opting for a simpler two way merge instead. In some edge cases typically '
'involving using a fallback or incorrect base revision, the default three way merge algorithm may produce '
'incorrect merges. Two way merges are more conflict prone, but less likely to produce incorrect results '
'silently.',
);
argParser.addFlag(
'flutter-subcommand',
help:
'Enable when using the flutter tool as a subcommand. This changes the '
'wording of log messages to indicate the correct suggested commands to use.',
);
}
final bool _verbose;
final Logger logger;
final FileSystem fileSystem;
final MigrateUtils migrateUtils;
final ProcessManager processManager;
final bool standalone;
@override
final String name = 'start';
@override
final String description =
r'Begins a new migration. Computes the changes needed to migrate the project from the base revision of Flutter to the current revision of Flutter and outputs the results in a working directory. Use `$ flutter migrate apply` accept and apply the changes.';
@override
Future<CommandResult> runCommand() async {
final FlutterToolsEnvironment environment =
await FlutterToolsEnvironment.initializeFlutterToolsEnvironment(
processManager, logger);
if (!_validateEnvironment(environment)) {
return const CommandResult(ExitStatus.fail);
}
final String? projectRootDirPath = stringArg('project-directory') ??
environment.getString('FlutterProject.directory');
final Directory projectRootDir = fileSystem.directory(projectRootDirPath);
final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory();
final FlutterProject project = projectRootDirPath == null
? FlutterProject.current(fileSystem)
: flutterProjectFactory
.fromDirectory(fileSystem.directory(projectRootDirPath));
if (!validateWorkingDirectory(project, logger)) {
return CommandResult.fail();
}
final bool isModule =
environment.getBool('FlutterProject.isModule') ?? false;
final bool isPlugin =
environment.getBool('FlutterProject.isPlugin') ?? false;
if (isModule || isPlugin) {
logger.printError(
'Migrate tool only supports app projects. This project is a ${isModule ? 'module' : 'plugin'}');
return const CommandResult(ExitStatus.fail);
}
final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone;
if (!await gitRepoExists(project.directory.path, logger, migrateUtils)) {
return const CommandResult(ExitStatus.fail);
}
Directory stagingDirectory =
project.directory.childDirectory(kDefaultMigrateStagingDirectoryName);
final String? customStagingDirectoryPath = stringArg('staging-directory');
if (customStagingDirectoryPath != null) {
if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) {
stagingDirectory = fileSystem.directory(customStagingDirectoryPath);
} else {
stagingDirectory =
project.directory.childDirectory(customStagingDirectoryPath);
}
}
if (stagingDirectory.existsSync()) {
logger.printStatus('Old migration already in progress.', emphasis: true);
logger.printStatus(
'Pending migration files exist in `${stagingDirectory.path}/$kDefaultMigrateStagingDirectoryName`');
logger.printStatus(
'Resolve merge conflicts and accept changes with by running:');
printCommandText('apply', logger, standalone: !isSubcommand);
logger.printStatus(
'You may also abandon the existing migration and start a new one with:');
printCommandText('abandon', logger, standalone: !isSubcommand);
return const CommandResult(ExitStatus.fail);
}
if (await hasUncommittedChanges(
project.directory.path, logger, migrateUtils)) {
return const CommandResult(ExitStatus.fail);
}
List<SupportedPlatform>? platforms;
if (stringArg('platforms') != null) {
platforms = <SupportedPlatform>[];
for (String platformString in stringArg('platforms')!.split(',')) {
platformString = platformString.trim();
platforms.add(SupportedPlatform.values.firstWhere(
(SupportedPlatform val) =>
val.toString() == 'SupportedPlatform.$platformString'));
}
}
final MigrateCommandParameters commandParameters = MigrateCommandParameters(
verbose: _verbose,
baseAppPath: stringArg('base-app-directory'),
targetAppPath: stringArg('target-app-directory'),
baseRevision: stringArg('base-revision'),
targetRevision: stringArg('target-revision'),
deleteTempDirectories: boolArg('delete-temp-directories') ?? true,
platforms: platforms,
preferTwoWayMerge: boolArg('prefer-two-way-merge') ?? false,
allowFallbackBaseRevision:
boolArg('allow-fallback-base-revision') ?? false,
);
final MigrateResult? migrateResult = await computeMigration(
flutterProject: project,
commandParameters: commandParameters,
fileSystem: fileSystem,
logger: logger,
migrateUtils: migrateUtils,
environment: environment,
);
if (migrateResult == null) {
return const CommandResult(ExitStatus.fail);
}
await writeStagingDir(migrateResult, logger,
verbose: _verbose, projectRootDir: projectRootDir);
_deleteTempDirectories(
paths: <String>[],
directories: migrateResult.tempDirectories,
);
logger.printStatus(
'The migrate tool has staged proposed changes in the migrate staging directory.\n');
logger.printStatus('Guided conflict resolution wizard:');
printCommandText('resolve-conflicts', logger, standalone: !isSubcommand);
logger.printStatus('Check the status and diffs of the migration with:');
printCommandText('status', logger, standalone: !isSubcommand);
logger.printStatus('Abandon the proposed migration with:');
printCommandText('abandon', logger, standalone: !isSubcommand);
logger.printStatus(
'Accept staged changes after resolving any merge conflicts with:');
printCommandText('apply', logger, standalone: !isSubcommand);
return const CommandResult(ExitStatus.success);
}
/// Deletes the files or directories at the provided paths.
void _deleteTempDirectories(
{List<String> paths = const <String>[],
List<Directory> directories = const <Directory>[]}) {
for (final Directory d in directories) {
try {
d.deleteSync(recursive: true);
} on FileSystemException catch (e) {
logger.printError(
'Unabled to delete ${d.path} due to ${e.message}, please clean up manually.');
}
}
for (final String p in paths) {
try {
fileSystem.directory(p).deleteSync(recursive: true);
} on FileSystemException catch (e) {
logger.printError(
'Unabled to delete $p due to ${e.message}, please clean up manually.');
}
}
}
bool _validateEnvironment(FlutterToolsEnvironment environment) {
if (environment.getString('FlutterProject.directory') == null) {
logger.printError(
'No valid flutter project found. This command must be run from a flutter project directory');
return false;
}
if (environment.getString('FlutterProject.manifest.appname') == null) {
logger.printError('No app name found in project pubspec.yaml');
return false;
}
if (!(environment.getBool('FlutterProject.android.exists') ?? false) &&
environment['FlutterProject.android.isKotlin'] == null) {
logger.printError(
'Could not detect if android project uses kotlin or java');
return false;
}
if (!(environment.getBool('FlutterProject.ios.exists') ?? false) &&
environment['FlutterProject.ios.isSwift'] == null) {
logger.printError(
'Could not detect if iosProject uses swift or objective-c');
return false;
}
return true;
}
/// Writes the files into the working directory for the developer to review and resolve any conflicts.
Future<void> writeStagingDir(MigrateResult migrateResult, Logger logger,
{bool verbose = false, required Directory projectRootDir}) async {
final Directory stagingDir =
projectRootDir.childDirectory(kDefaultMigrateStagingDirectoryName);
if (verbose) {
logger.printStatus(
'Writing migrate staging directory at `${stagingDir.path}`');
}
// Write files in working dir
for (final MergeResult result in migrateResult.mergeResults) {
final File file = stagingDir.childFile(result.localPath);
file.createSync(recursive: true);
if (result is StringMergeResult) {
file.writeAsStringSync(result.mergedString, flush: true);
} else {
file.writeAsBytesSync((result as BinaryMergeResult).mergedBytes,
flush: true);
}
}
// Write all files that are newly added in target
for (final FilePendingMigration addedFile in migrateResult.addedFiles) {
final File file = stagingDir.childFile(addedFile.localPath);
file.createSync(recursive: true);
try {
file.writeAsStringSync(addedFile.file.readAsStringSync(), flush: true);
} on FileSystemException {
file.writeAsBytesSync(addedFile.file.readAsBytesSync(), flush: true);
}
}
// Write the MigrateManifest.
final MigrateManifest manifest = MigrateManifest(
migrateRootDir: stagingDir,
migrateResult: migrateResult,
);
manifest.writeFile();
// output the manifest contents.
checkAndPrintMigrateStatus(manifest, stagingDir, logger: logger);
logger.printBox('Staging directory created at `${stagingDir.path}`');
}
}
| packages/packages/flutter_migrate/lib/src/commands/start.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/commands/start.dart",
"repo_id": "packages",
"token_count": 4664
} | 949 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_migrate/src/base/context.dart';
import 'package:flutter_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/base/signals.dart';
import 'package:flutter_migrate/src/commands/status.dart';
import 'package:flutter_migrate/src/utils.dart';
import 'package:process/process.dart';
import 'src/common.dart';
import 'src/context.dart';
import 'src/test_flutter_command_runner.dart';
void main() {
late FileSystem fileSystem;
late BufferLogger logger;
late ProcessManager processManager;
late Directory appDir;
setUp(() {
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
appDir = fileSystem.systemTempDirectory.createTempSync('apptestdir');
logger = BufferLogger.test();
processManager = const LocalProcessManager();
});
tearDown(() async {
tryToDelete(appDir);
});
testUsingContext('Status produces all outputs', () async {
final MigrateStatusCommand command = MigrateStatusCommand(
verbose: true,
logger: logger,
fileSystem: fileSystem,
processManager: processManager,
);
final Directory stagingDir =
appDir.childDirectory(kDefaultMigrateStagingDirectoryName);
final File pubspecOriginal = appDir.childFile('pubspec.yaml');
pubspecOriginal.createSync();
pubspecOriginal.writeAsStringSync('''
name: originalname
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: '>=2.18.0-58.0.dev <3.0.0'
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true''', flush: true);
final File pubspecModified = stagingDir.childFile('pubspec.yaml');
pubspecModified.createSync(recursive: true);
pubspecModified.writeAsStringSync('''
name: newname
description: new description of the test project
version: 1.0.0+1
environment:
sdk: '>=2.18.0-58.0.dev <3.0.0'
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: false
EXTRALINE''', flush: true);
final File addedFile = stagingDir.childFile('added.file');
addedFile.createSync(recursive: true);
addedFile.writeAsStringSync('new file contents');
final File manifestFile = stagingDir.childFile('.migrate_manifest');
manifestFile.createSync(recursive: true);
manifestFile.writeAsStringSync('''
merged_files:
- pubspec.yaml
conflict_files:
added_files:
- added.file
deleted_files:
''');
await createTestCommandRunner(command).run(<String>[
'status',
'--staging-directory=${stagingDir.path}',
'--project-directory=${appDir.path}',
'--flutter-subcommand',
]);
expect(logger.statusText, contains('''
Newly added file at added.file:
new file contents'''));
expect(logger.statusText, contains(r'''
Added files:
- added.file
Modified files:
- pubspec.yaml
All conflicts resolved. Review changes above and apply the migration with:
$ flutter migrate apply
'''));
expect(logger.statusText, contains(r'''
@@ -1,5 +1,5 @@
-name: originalname
-description: A new Flutter project.
+name: newname
+description: new description of the test project
version: 1.0.0+1
environment:
sdk: '>=2.18.0-58.0.dev <3.0.0'
@@ -10,4 +10,5 @@ dev_dependencies:
flutter_test:
sdk: flutter
flutter:
- uses-material-design: true
\ No newline at end of file
+ uses-material-design: false
+ EXTRALINE'''));
// Add conflict file
final File conflictFile =
stagingDir.childDirectory('conflict').childFile('conflict.file');
conflictFile.createSync(recursive: true);
conflictFile.writeAsStringSync('''
line1
<<<<<<< /conflcit/conflict.file
line2
=======
linetwo
>>>>>>> /var/folders/md/gm0zgfcj07vcsj6jkh_mp_wh00ff02/T/flutter_tools.4Xdep8/generatedTargetTemplatetlN44S/conflict/conflict.file
line3
''', flush: true);
final File conflictFileOriginal =
appDir.childDirectory('conflict').childFile('conflict.file');
conflictFileOriginal.createSync(recursive: true);
conflictFileOriginal.writeAsStringSync('''
line1
line2
line3
''', flush: true);
manifestFile.writeAsStringSync('''
merged_files:
- pubspec.yaml
conflict_files:
- conflict/conflict.file
added_files:
- added.file
deleted_files:
''');
logger.clear();
await createTestCommandRunner(command).run(<String>[
'status',
'--staging-directory=${stagingDir.path}',
'--project-directory=${appDir.path}',
'--flutter-subcommand',
]);
expect(logger.statusText, contains('''
@@ -1,3 +1,7 @@
line1
+<<<<<<< /conflcit/conflict.file
line2
+=======
+linetwo
+>>>>>>>'''));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
}
| packages/packages/flutter_migrate/test/status_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/status_test.dart",
"repo_id": "packages",
"token_count": 1818
} | 950 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.flutter_plugin_android_lifecycle">
</manifest>
| packages/packages/flutter_plugin_android_lifecycle/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/flutter_plugin_android_lifecycle/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 52
} | 951 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 4.2.1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Updates minimum SDK version to Flutter 3.0.
## 4.2.0
* Adds iOS template app icons, updated to square icons with no transparency.
## 4.1.1
* Removes empty Dart file.
* Opts in to NNBD (which is a no-op) so it's not flagged by pub.dev.
## 4.1.0
* Updates package description.
* Adds macOS template app icons, updated to Big Sur style.
## 4.0.0
* Move assets common to all app templates to a new `app_shared` directory
(relands changes reverted in 3.0.0).
* Create `skeleton` directory and assets to support new app template
(formerly known as `list_detail_app`).
## 3.0.1
* Fix maskable icon file names
* Fix maskable icon image dimensions
## 3.0.0
* Reverts to the 1.0 layout, since the new app template never landed.
* Added additional icons for winuwp template.
## 2.0.0
* Move assets common to all app templates to a new `app_shared` directory.
* Create `list_detail_app` directory and assets to support new app template.
## 1.0.1
* Moved Windows app template icon for new folder structure.
## 1.0.0
* Windows app template icon.
| packages/packages/flutter_template_images/CHANGELOG.md/0 | {
"file_path": "packages/packages/flutter_template_images/CHANGELOG.md",
"repo_id": "packages",
"token_count": 392
} | 952 |
To get started, follow the [package installation
instructions](https://pub.dev/packages/go_router/install) and add a GoRouter
configuration to your app:
```dart
import 'package:go_router/go_router.dart';
// GoRouter configuration
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
],
);
```
To use this configuration in your app, use either the `MaterialApp.router` or
`CupertinoApp.router` constructor and set the `routerConfig` parameter to your
GoRouter configuration object:
```
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}
```
For a complete sample, see the [Getting started sample][] in the example directory.
For more on how to configure GoRouter, see [Configuration].
[Getting started sample]: https://github.com/flutter/packages/tree/main/packages/go_router/example/lib/main.dart
[Configuration]: https://pub.dev/documentation/go_router/latest/topics/Configuration-topic.html
| packages/packages/go_router/doc/get-started.md/0 | {
"file_path": "packages/packages/go_router/doc/get-started.md",
"repo_id": "packages",
"token_count": 353
} | 953 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../data.dart';
import '../widgets/book_list.dart';
/// A screen that displays a list of books.
class BooksScreen extends StatefulWidget {
/// Creates a [BooksScreen].
const BooksScreen(this.kind, {super.key});
/// Which tab to display.
final String kind;
@override
State<BooksScreen> createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
void didUpdateWidget(BooksScreen oldWidget) {
super.didUpdateWidget(oldWidget);
switch (widget.kind) {
case 'popular':
_tabController.index = 0;
case 'new':
_tabController.index = 1;
case 'all':
_tabController.index = 2;
}
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Books'),
bottom: TabBar(
controller: _tabController,
onTap: _handleTabTapped,
tabs: const <Tab>[
Tab(
text: 'Popular',
icon: Icon(Icons.people),
),
Tab(
text: 'New',
icon: Icon(Icons.new_releases),
),
Tab(
text: 'All',
icon: Icon(Icons.list),
),
],
),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
BookList(
books: libraryInstance.popularBooks,
onTap: _handleBookTapped,
),
BookList(
books: libraryInstance.newBooks,
onTap: _handleBookTapped,
),
BookList(
books: libraryInstance.allBooks,
onTap: _handleBookTapped,
),
],
),
);
void _handleBookTapped(Book book) {
context.go('/book/${book.id}');
}
void _handleTabTapped(int index) {
switch (index) {
case 1:
context.go('/books/new');
case 2:
context.go('/books/all');
case 0:
default:
context.go('/books/popular');
break;
}
}
}
| packages/packages/go_router/example/lib/books/src/screens/books.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/books/src/screens/books.dart",
"repo_id": "packages",
"token_count": 1264
} | 954 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
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: Push';
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
);
late final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const Page1ScreenWithPush(),
),
GoRoute(
path: '/page2',
builder: (BuildContext context, GoRouterState state) =>
Page2ScreenWithPush(
int.parse(state.uri.queryParameters['push-count']!),
),
),
],
);
}
/// The screen of the first page.
class Page1ScreenWithPush extends StatelessWidget {
/// Creates a [Page1ScreenWithPush].
const Page1ScreenWithPush({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('${App.title}: page 1')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => context.push('/page2?push-count=1'),
child: const Text('Push page 2'),
),
],
),
),
);
}
/// The screen of the second page.
class Page2ScreenWithPush extends StatelessWidget {
/// Creates a [Page2ScreenWithPush].
const Page2ScreenWithPush(this.pushCount, {super.key});
/// The push count.
final int pushCount;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('${App.title}: page 2 w/ push count $pushCount'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () => context.go('/'),
child: const Text('Go to home page'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () => context.push(
'/page2?push-count=${pushCount + 1}',
),
child: const Text('Push page 2 (again)'),
),
),
],
),
),
);
}
| packages/packages/go_router/example/lib/others/push.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/others/push.dart",
"repo_id": "packages",
"token_count": 1323
} | 955 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router_examples/routing_config.dart' as example;
void main() {
testWidgets('example works', (WidgetTester tester) async {
await tester.pumpWidget(const example.MyApp());
expect(find.text('Add a new route'), findsOneWidget);
await tester.tap(find.text('Try going to /new-route'));
await tester.pumpAndSettle();
expect(find.text('Page not found'), findsOneWidget);
await tester.tap(find.text('Go to home'));
await tester.pumpAndSettle();
await tester.tap(find.text('Add a new route'));
await tester.pumpAndSettle();
expect(find.text('A route has been added'), findsOneWidget);
await tester.tap(find.text('Try going to /new-route'));
await tester.pumpAndSettle();
expect(find.text('A new Route'), findsOneWidget);
});
}
| packages/packages/go_router/example/test/routing_config_test.dart/0 | {
"file_path": "packages/packages/go_router/example/test/routing_config_test.dart",
"repo_id": "packages",
"token_count": 348
} | 956 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'extensions.dart';
/// Default error page implementation for WidgetsApp.
class ErrorScreen extends StatelessWidget {
/// Provide an exception to this page for it to be displayed.
const ErrorScreen(this.error, {super.key});
/// The exception to be displayed.
final Exception? error;
static const Color _kWhite = Color(0xFFFFFFFF);
@override
Widget build(BuildContext context) => SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Page Not Found',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
Text(error?.toString() ?? 'page not found'),
const SizedBox(height: 16),
_Button(
onPressed: () => context.go('/'),
child: const Text(
'Go to home page',
style: TextStyle(color: _kWhite),
),
),
],
),
),
);
}
class _Button extends StatefulWidget {
const _Button({
required this.onPressed,
required this.child,
});
final VoidCallback onPressed;
/// The child subtree.
final Widget child;
@override
State<_Button> createState() => _ButtonState();
}
class _ButtonState extends State<_Button> {
late final Color _color;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_color = (context as Element)
.findAncestorWidgetOfExactType<WidgetsApp>()
?.color ??
const Color(0xFF2196F3); // blue
}
@override
Widget build(BuildContext context) => GestureDetector(
onTap: widget.onPressed,
child: Container(
padding: const EdgeInsets.all(8),
color: _color,
child: widget.child,
),
);
}
| packages/packages/go_router/lib/src/misc/error_screen.dart/0 | {
"file_path": "packages/packages/go_router/lib/src/misc/error_screen.dart",
"repo_id": "packages",
"token_count": 920
} | 957 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
void main() {
group('RouteConfiguration', () {
test('throws when parentNavigatorKey is not an ancestor', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> a =
GlobalKey<NavigatorState>(debugLabel: 'a');
final GlobalKey<NavigatorState> b =
GlobalKey<NavigatorState>(debugLabel: 'b');
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
ShellRoute(
navigatorKey: a,
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
)
],
),
ShellRoute(
navigatorKey: b,
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'c',
parentNavigatorKey: a,
builder: _mockScreenBuilder,
)
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test('throws when ShellRoute has no children', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final List<RouteBase> shellRouteChildren = <RouteBase>[];
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(routes: shellRouteChildren),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test(
'throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> keyA =
GlobalKey<NavigatorState>(debugLabel: 'A');
final GlobalKey<NavigatorState> keyB =
GlobalKey<NavigatorState>(debugLabel: 'B');
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
navigatorKey: keyA,
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'details',
builder: _mockScreenBuilder,
parentNavigatorKey: keyB),
]),
],
),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsA(isA<AssertionError>()),
);
});
test(
'does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> keyA =
GlobalKey<NavigatorState>(debugLabel: 'A');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
navigatorKey: keyA,
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'details',
builder: _mockScreenBuilder,
parentNavigatorKey: keyA),
]),
],
),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
});
test(
'throws when a sub-route of StatefulShellRoute has a parentNavigatorKey',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> someNavigatorKey =
GlobalKey<NavigatorState>();
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'details',
builder: _mockScreenBuilder,
parentNavigatorKey: someNavigatorKey),
]),
],
),
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
parentNavigatorKey: someNavigatorKey),
],
),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test('throws when StatefulShellRoute has duplicate navigator keys', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> keyA =
GlobalKey<NavigatorState>(debugLabel: 'A');
final List<GoRoute> shellRouteChildren = <GoRoute>[
GoRoute(
path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: keyA),
GoRoute(
path: '/b', builder: _mockScreenBuilder, parentNavigatorKey: keyA),
];
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(routes: shellRouteChildren)
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test(
'throws when a child of StatefulShellRoute has an incorrect '
'parentNavigatorKey', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> sectionANavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sectionBNavigatorKey =
GlobalKey<NavigatorState>();
final GoRoute routeA = GoRoute(
path: '/a',
builder: _mockScreenBuilder,
parentNavigatorKey: sectionBNavigatorKey);
final GoRoute routeB = GoRoute(
path: '/b',
builder: _mockScreenBuilder,
parentNavigatorKey: sectionANavigatorKey);
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[routeA],
navigatorKey: sectionANavigatorKey),
StatefulShellBranch(
routes: <RouteBase>[routeB],
navigatorKey: sectionBNavigatorKey),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test(
'throws when a branch of a StatefulShellRoute has an incorrect '
'initialLocation', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> sectionANavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sectionBNavigatorKey =
GlobalKey<NavigatorState>();
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
initialLocation: '/x',
navigatorKey: sectionANavigatorKey,
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
),
],
),
StatefulShellBranch(
navigatorKey: sectionBNavigatorKey,
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
),
],
),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsA(isA<AssertionError>()),
);
});
test(
'throws when a branch of a StatefulShellRoute has a initialLocation '
'that is not a descendant of the same branch', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> sectionANavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sectionBNavigatorKey =
GlobalKey<NavigatorState>();
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
initialLocation: '/b',
navigatorKey: sectionANavigatorKey,
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
),
],
),
StatefulShellBranch(
initialLocation: '/b',
navigatorKey: sectionBNavigatorKey,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
),
],
),
],
builder: mockStackedShellBuilder),
],
),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsA(isA<AssertionError>()),
);
});
test(
'does not throw when a branch of a StatefulShellRoute has correctly '
'configured initialLocations', () {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'detail',
builder: _mockScreenBuilder,
),
]),
],
),
StatefulShellBranch(
initialLocation: '/b/detail',
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'detail',
builder: _mockScreenBuilder,
),
]),
],
),
StatefulShellBranch(
initialLocation: '/c/detail',
routes: <RouteBase>[
StatefulShellRoute.indexedStack(branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/c',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'detail',
builder: _mockScreenBuilder,
),
]),
],
),
StatefulShellBranch(
initialLocation: '/d/detail',
routes: <RouteBase>[
GoRoute(
path: '/d',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'detail',
builder: _mockScreenBuilder,
),
]),
],
),
], builder: mockStackedShellBuilder),
],
),
StatefulShellBranch(routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: '/e',
builder: _mockScreenBuilder,
),
],
)
],
),
]),
], builder: mockStackedShellBuilder),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
});
test(
'derives the correct initialLocation for a StatefulShellBranch',
() {
final StatefulShellBranch branchA;
final StatefulShellBranch branchY;
final StatefulShellBranch branchB;
final RouteConfiguration config = createRouteConfiguration(
navigatorKey: GlobalKey<NavigatorState>(debugLabel: 'root'),
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
builder: mockStackedShellBuilder,
branches: <StatefulShellBranch>[
branchA = StatefulShellBranch(routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'x',
builder: _mockScreenBuilder,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
builder: mockStackedShellBuilder,
branches: <StatefulShellBranch>[
branchY =
StatefulShellBranch(routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'y1',
builder: _mockScreenBuilder,
),
GoRoute(
path: 'y2',
builder: _mockScreenBuilder,
),
])
])
]),
],
),
],
),
]),
branchB = StatefulShellBranch(routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: '/b1',
builder: _mockScreenBuilder,
),
GoRoute(
path: '/b2',
builder: _mockScreenBuilder,
),
],
)
],
),
]),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
String? initialLocation(StatefulShellBranch branch) {
final GoRoute? route = branch.defaultRoute;
return route != null ? config.locationForRoute(route) : null;
}
expect('/a', initialLocation(branchA));
expect('/a/x/y1', initialLocation(branchY));
expect('/b1', initialLocation(branchB));
},
);
test(
'throws when there is a GoRoute ancestor with a different parentNavigatorKey',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: shell,
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test(
'Does not throw with valid parentNavigatorKey configuration',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GlobalKey<NavigatorState> shell2 =
GlobalKey<NavigatorState>(debugLabel: 'shell2');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell2,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
parentNavigatorKey: shell2,
),
],
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
);
test(
'Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: 'c',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
);
test(
'Throws when parentNavigatorKeys are overlapping',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
expect(
() => createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
parentNavigatorKey: shell,
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
),
throwsA(isA<AssertionError>()),
);
},
);
test(
'Does not throw when parentNavigatorKeys are overlapping correctly',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
);
test(
'throws when a GoRoute with a different parentNavigatorKey '
'exists between a GoRoute with a parentNavigatorKey and '
'its ShellRoute ancestor',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GlobalKey<NavigatorState> shell2 =
GlobalKey<NavigatorState>(debugLabel: 'shell2');
expect(
() => createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
parentNavigatorKey: root,
builder: _mockScreenBuilder,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell2,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'c',
builder: _mockScreenBuilder,
parentNavigatorKey: shell,
),
],
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
),
throwsA(isA<AssertionError>()),
);
},
);
test('does not throw when ShellRoute is the child of another ShellRoute',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
createRouteConfiguration(
routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <RouteBase>[
ShellRoute(
builder: _mockShellBuilder,
routes: <GoRoute>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
),
],
),
GoRoute(
path: '/b',
builder: _mockScreenBuilder,
),
],
),
GoRoute(
path: '/c',
builder: _mockScreenBuilder,
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
navigatorKey: root,
);
});
test(
'Does not throw with valid parentNavigatorKey configuration',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GlobalKey<NavigatorState> shell2 =
GlobalKey<NavigatorState>(debugLabel: 'shell2');
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell2,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
builder: _mockScreenBuilder,
parentNavigatorKey: shell2,
),
],
),
],
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
);
test('throws when ShellRoute contains a GoRoute with a parentNavigatorKey',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
expect(
() {
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
ShellRoute(
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: _mockScreenBuilder,
parentNavigatorKey: root,
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
);
},
throwsAssertionError,
);
});
test(
'All known route strings returned by debugKnownRoutes are correct',
() {
final GlobalKey<NavigatorState> root =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shell =
GlobalKey<NavigatorState>(debugLabel: 'shell');
expect(
createRouteConfiguration(
navigatorKey: root,
routes: <RouteBase>[
GoRoute(
path: '/a',
parentNavigatorKey: root,
builder: _mockScreenBuilder,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell,
builder: _mockShellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'b',
parentNavigatorKey: shell,
builder: _mockScreenBuilder,
),
GoRoute(
path: 'c',
parentNavigatorKey: shell,
builder: _mockScreenBuilder,
),
],
),
],
),
GoRoute(
path: '/d',
parentNavigatorKey: root,
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'e',
parentNavigatorKey: root,
builder: _mockScreenBuilder,
routes: <RouteBase>[
GoRoute(
path: 'f',
parentNavigatorKey: root,
builder: _mockScreenBuilder,
),
],
),
],
),
GoRoute(
path: '/g',
builder: _mockScreenBuilder,
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
builder: _mockIndexedStackShellBuilder,
branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: 'h',
builder: _mockScreenBuilder,
),
],
),
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: 'i',
builder: _mockScreenBuilder,
),
],
),
],
),
],
),
],
redirectLimit: 10,
topRedirect: (BuildContext context, GoRouterState state) {
return null;
},
).debugKnownRoutes(),
'Full paths for routes:\n'
' => /a\n'
' => /a/b\n'
' => /a/c\n'
' => /d\n'
' => /d/e\n'
' => /d/e/f\n'
' => /g\n'
' => /g/h\n'
' => /g/i\n',
);
},
);
});
}
class _MockScreen extends StatelessWidget {
const _MockScreen({super.key});
@override
Widget build(BuildContext context) => const Placeholder();
}
Widget _mockScreenBuilder(BuildContext context, GoRouterState state) =>
_MockScreen(key: state.pageKey);
Widget _mockShellBuilder(
BuildContext context, GoRouterState state, Widget child) =>
child;
Widget _mockIndexedStackShellBuilder(BuildContext context, GoRouterState state,
StatefulNavigationShell shell) =>
shell;
| packages/packages/go_router/test/configuration_test.dart/0 | {
"file_path": "packages/packages/go_router/test/configuration_test.dart",
"repo_id": "packages",
"token_count": 22568
} | 958 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
void main() {
group('RouteMatch', () {
test('simple', () {
final GoRoute route = GoRoute(
path: '/users/:userId',
builder: _builder,
);
final Map<String, String> pathParameters = <String, String>{};
final List<RouteMatchBase> matches = RouteMatchBase.match(
route: route,
pathParameters: pathParameters,
uri: Uri.parse('/users/123'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
);
expect(matches.length, 1);
final RouteMatchBase match = matches.first;
expect(match.route, route);
expect(match.matchedLocation, '/users/123');
expect(pathParameters['userId'], '123');
expect(match.pageKey, isNotNull);
});
test('ShellRoute has a unique pageKey', () {
final ShellRoute route = ShellRoute(
builder: _shellBuilder,
routes: <GoRoute>[
GoRoute(
path: '/users/:userId',
builder: _builder,
),
],
);
final Map<String, String> pathParameters = <String, String>{};
final List<RouteMatchBase> matches = RouteMatchBase.match(
route: route,
uri: Uri.parse('/users/123'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
pathParameters: pathParameters,
);
expect(matches.length, 1);
expect(matches.first.pageKey, isNotNull);
});
test('ShellRoute Match has stable unique key', () {
final ShellRoute route = ShellRoute(
builder: _shellBuilder,
routes: <GoRoute>[
GoRoute(
path: '/users/:userId',
builder: _builder,
),
],
);
final Map<String, String> pathParameters = <String, String>{};
final List<RouteMatchBase> matches1 = RouteMatchBase.match(
route: route,
pathParameters: pathParameters,
uri: Uri.parse('/users/123'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
);
final List<RouteMatchBase> matches2 = RouteMatchBase.match(
route: route,
pathParameters: pathParameters,
uri: Uri.parse('/users/1234'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
);
expect(matches1.length, 1);
expect(matches2.length, 1);
expect(matches1.first.pageKey, matches2.first.pageKey);
});
test('GoRoute Match has stable unique key', () {
final GoRoute route = GoRoute(
path: '/users/:userId',
builder: _builder,
);
final Map<String, String> pathParameters = <String, String>{};
final List<RouteMatchBase> matches1 = RouteMatchBase.match(
route: route,
uri: Uri.parse('/users/123'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
pathParameters: pathParameters,
);
final List<RouteMatchBase> matches2 = RouteMatchBase.match(
route: route,
uri: Uri.parse('/users/1234'),
rootNavigatorKey: GlobalKey<NavigatorState>(),
pathParameters: pathParameters,
);
expect(matches1.length, 1);
expect(matches2.length, 1);
expect(matches1.first.pageKey, matches2.first.pageKey);
});
});
test('complex parentNavigatorKey works', () {
final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shell1 = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shell2 = GlobalKey<NavigatorState>();
final GoRoute route = GoRoute(
path: '/',
builder: _builder,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell1,
builder: _shellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'a',
builder: _builder,
routes: <RouteBase>[
GoRoute(
parentNavigatorKey: root,
path: 'b',
builder: _builder,
routes: <RouteBase>[
ShellRoute(
navigatorKey: shell2,
builder: _shellBuilder,
routes: <RouteBase>[
GoRoute(
path: 'c',
builder: _builder,
routes: <RouteBase>[
GoRoute(
parentNavigatorKey: root,
path: 'd',
builder: _builder,
),
],
),
],
),
],
),
],
),
],
),
],
);
final Map<String, String> pathParameters = <String, String>{};
final List<RouteMatchBase> matches = RouteMatchBase.match(
route: route,
pathParameters: pathParameters,
uri: Uri.parse('/a/b/c/d'),
rootNavigatorKey: root,
);
expect(matches.length, 4);
expect(
matches[0].route,
isA<GoRoute>().having(
(GoRoute route) => route.path,
'path',
'/',
),
);
expect(
matches[1].route,
isA<ShellRoute>().having(
(ShellRoute route) => route.navigatorKey,
'navigator key',
shell1,
),
);
expect(
matches[2].route,
isA<GoRoute>().having(
(GoRoute route) => route.path,
'path',
'b',
),
);
expect(
matches[3].route,
isA<GoRoute>().having(
(GoRoute route) => route.path,
'path',
'd',
),
);
});
group('ImperativeRouteMatch', () {
final RouteMatchList matchList1 = RouteMatchList(
matches: <RouteMatch>[
RouteMatch(
route: GoRoute(path: '/', builder: (_, __) => const Text('hi')),
matchedLocation: '/',
pageKey: const ValueKey<String>('dummy'),
),
],
uri: Uri.parse('/'),
pathParameters: const <String, String>{});
final RouteMatchList matchList2 = RouteMatchList(
matches: <RouteMatch>[
RouteMatch(
route: GoRoute(path: '/a', builder: (_, __) => const Text('a')),
matchedLocation: '/a',
pageKey: const ValueKey<String>('dummy'),
),
],
uri: Uri.parse('/a'),
pathParameters: const <String, String>{});
const ValueKey<String> key1 = ValueKey<String>('key1');
const ValueKey<String> key2 = ValueKey<String>('key2');
final Completer<void> completer1 = Completer<void>();
final Completer<void> completer2 = Completer<void>();
test('can equal and has', () async {
ImperativeRouteMatch match1 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer1);
ImperativeRouteMatch match2 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer1);
expect(match1 == match2, isTrue);
expect(match1.hashCode == match2.hashCode, isTrue);
match1 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer1);
match2 = ImperativeRouteMatch(
pageKey: key2, matches: matchList1, completer: completer1);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
match1 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer1);
match2 = ImperativeRouteMatch(
pageKey: key1, matches: matchList2, completer: completer1);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
match1 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer1);
match2 = ImperativeRouteMatch(
pageKey: key1, matches: matchList1, completer: completer2);
expect(match1 == match2, isFalse);
expect(match1.hashCode == match2.hashCode, isFalse);
});
});
}
Widget _builder(BuildContext context, GoRouterState state) =>
const Placeholder();
Widget _shellBuilder(BuildContext context, GoRouterState state, Widget child) =>
const Placeholder();
| packages/packages/go_router/test/match_test.dart/0 | {
"file_path": "packages/packages/go_router/test/match_test.dart",
"repo_id": "packages",
"token_count": 3920
} | 959 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:go_router/go_router.dart';
void main() {
const GoRouterState state = GoRouterState();
final GoRouter router = GoRouter(routes: <RouteBase>[]);
state.fullPath;
state.pathParameters;
state.matchedLocation;
state.uri.queryParameters;
state.namedLocation(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
router.namedLocation(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
router.goNamed(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
router.pushNamed(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
router.pushReplacementNamed(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
router.replaceNamed(
'name',
pathParameters: <String, String>{},
queryParameters: <String, String>{},
);
state.uri.queryParametersAll;
state.uri.toString();
}
| packages/packages/go_router/test_fixes/go_router.dart.expect/0 | {
"file_path": "packages/packages/go_router/test_fixes/go_router.dart.expect",
"repo_id": "packages",
"token_count": 429
} | 960 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, unreachable_from_main
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'shared/data.dart';
part 'main.g.dart';
void main() => runApp(App());
class App extends StatelessWidget {
App({super.key});
final LoginInfo loginInfo = LoginInfo();
static const String title = 'GoRouter Example: Named Routes';
@override
Widget build(BuildContext context) => ChangeNotifierProvider<LoginInfo>.value(
value: loginInfo,
child: MaterialApp.router(
routerConfig: _router,
title: title,
debugShowCheckedModeBanner: false,
),
);
late final GoRouter _router = GoRouter(
debugLogDiagnostics: true,
routes: $appRoutes,
// redirect to the login page if the user is not logged in
redirect: (BuildContext context, GoRouterState state) {
final bool loggedIn = loginInfo.loggedIn;
// check just the matchedLocation in case there are query parameters
final String loginLoc = const LoginRoute().location;
final bool goingToLogin = state.matchedLocation == loginLoc;
// the user is not logged in and not headed to /login, they need to login
if (!loggedIn && !goingToLogin) {
return LoginRoute(fromPage: state.matchedLocation).location;
}
// the user is logged in and headed to /login, no need to login again
if (loggedIn && goingToLogin) {
return const HomeRoute().location;
}
// no need to redirect at all
return null;
},
// changes on the listenable will cause the router to refresh it's route
refreshListenable: loginInfo,
);
}
@TypedGoRoute<HomeRoute>(
path: '/',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<FamilyRoute>(
path: 'family/:fid',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<PersonRoute>(
path: 'person/:pid',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<PersonDetailsRoute>(path: 'details/:details'),
],
),
],
),
TypedGoRoute<FamilyCountRoute>(path: 'family-count/:count'),
],
)
class HomeRoute extends GoRouteData {
const HomeRoute();
@override
Widget build(BuildContext context, GoRouterState state) => const HomeScreen();
}
@TypedGoRoute<LoginRoute>(
path: '/login',
)
class LoginRoute extends GoRouteData {
const LoginRoute({this.fromPage});
final String? fromPage;
@override
Widget build(BuildContext context, GoRouterState state) =>
LoginScreen(from: fromPage);
}
class FamilyRoute extends GoRouteData {
const FamilyRoute(this.fid);
final String fid;
@override
Widget build(BuildContext context, GoRouterState state) =>
FamilyScreen(family: familyById(fid));
}
class PersonRoute extends GoRouteData {
const PersonRoute(this.fid, this.pid);
final String fid;
final int pid;
@override
Widget build(BuildContext context, GoRouterState state) {
final Family family = familyById(fid);
final Person person = family.person(pid);
return PersonScreen(family: family, person: person);
}
}
class PersonDetailsRoute extends GoRouteData {
const PersonDetailsRoute(this.fid, this.pid, this.details, {this.$extra});
final String fid;
final int pid;
final PersonDetails details;
final int? $extra;
@override
Page<void> buildPage(BuildContext context, GoRouterState state) {
final Family family = familyById(fid);
final Person person = family.person(pid);
return MaterialPage<Object>(
fullscreenDialog: true,
key: state.pageKey,
child: PersonDetailsPage(
family: family,
person: person,
detailsKey: details,
extra: $extra,
),
);
}
}
class FamilyCountRoute extends GoRouteData {
const FamilyCountRoute(this.count);
final int count;
@override
Widget build(BuildContext context, GoRouterState state) => FamilyCountScreen(
count: count,
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final LoginInfo info = context.read<LoginInfo>();
return Scaffold(
appBar: AppBar(
title: const Text(App.title),
centerTitle: true,
actions: <Widget>[
PopupMenuButton<String>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: '1',
child: const Text('Push w/o return value'),
onTap: () => const PersonRoute('f1', 1).push<void>(context),
),
PopupMenuItem<String>(
value: '2',
child: const Text('Push w/ return value'),
onTap: () async {
unawaited(FamilyCountRoute(familyData.length)
.push<int>(context)
.then((int? value) {
if (value != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Age was: $value'),
),
);
}
}));
},
),
PopupMenuItem<String>(
value: '3',
child: Text('Logout: ${info.userName}'),
onTap: () => info.logout(),
),
];
},
),
],
),
body: ListView(
children: <Widget>[
for (final Family f in familyData)
ListTile(
title: Text(f.name),
onTap: () => FamilyRoute(f.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),
onTap: () => PersonRoute(family.id, p.id).go(context),
),
],
),
);
}
class PersonScreen extends StatelessWidget {
const PersonScreen({required this.family, required this.person, super.key});
final Family family;
final Person person;
static int _extraClickCount = 0;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(person.name)),
body: ListView(
children: <Widget>[
ListTile(
title: Text(
'${person.name} ${family.name} is ${person.age} years old'),
),
for (final MapEntry<PersonDetails, String> entry
in person.details.entries)
ListTile(
title: Text(
'${entry.key.name} - ${entry.value}',
),
trailing: OutlinedButton(
onPressed: () => PersonDetailsRoute(
family.id,
person.id,
entry.key,
$extra: ++_extraClickCount,
).go(context),
child: const Text('With extra...'),
),
onTap: () => PersonDetailsRoute(family.id, person.id, entry.key)
.go(context),
)
],
),
);
}
class PersonDetailsPage extends StatelessWidget {
const PersonDetailsPage({
required this.family,
required this.person,
required this.detailsKey,
this.extra,
super.key,
});
final Family family;
final Person person;
final PersonDetails detailsKey;
final int? extra;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(person.name)),
body: ListView(
children: <Widget>[
ListTile(
title: Text(
'${person.name} ${family.name}: '
'$detailsKey - ${person.details[detailsKey]}',
),
),
if (extra == null) const ListTile(title: Text('No extra click!')),
if (extra != null)
ListTile(title: Text('Extra click count: $extra')),
],
),
);
}
class FamilyCountScreen extends StatelessWidget {
const FamilyCountScreen({super.key, required this.count});
final int count;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Family Count')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
'There are $count families',
style: Theme.of(context).textTheme.headlineSmall,
),
),
ElevatedButton(
onPressed: () => context.pop(count),
child: Text('Pop with return value $count'),
),
],
),
),
);
}
class LoginScreen extends StatelessWidget {
const LoginScreen({this.from, super.key});
final String? from;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(App.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
// log a user in, letting all the listeners know
context.read<LoginInfo>().login('test-user');
// if there's a deep link, go there
if (from != null) {
context.go(from!);
}
},
child: const Text('Login'),
),
],
),
),
);
}
| packages/packages/go_router_builder/example/lib/main.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/lib/main.dart",
"repo_id": "packages",
"token_count": 4761
} | 961 |
// 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_builder_example/all_types.dart';
import 'package:go_router_builder_example/shared/data.dart';
void main() {
testWidgets('Test typed route navigation', (WidgetTester tester) async {
await tester.pumpWidget(AllTypesApp());
final ScaffoldState scaffoldState =
tester.firstState(find.byType(Scaffold));
BigIntRoute(
requiredBigIntField: BigInt.from(4),
bigIntField: BigInt.from(8),
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('BigIntRoute'), findsOneWidget);
expect(find.text('Param: 4'), findsOneWidget);
expect(find.text('Query param: 8'), findsOneWidget);
BoolRoute(
requiredBoolField: false,
boolField: true,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('BoolRoute'), findsOneWidget);
expect(find.text('Param: false'), findsOneWidget);
expect(find.text('Query param: true'), findsOneWidget);
expect(find.text('Query param with default value: true'), findsOneWidget);
final DateTime param = DateTime.now();
final DateTime query = DateTime(2017, 9, 7, 17, 30);
DateTimeRoute(
requiredDateTimeField: param,
dateTimeField: query,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('DateTimeRoute'), findsOneWidget);
expect(find.text('Param: $param'), findsOneWidget);
expect(find.text('Query param: $query'), findsOneWidget);
DoubleRoute(
requiredDoubleField: 3.14,
doubleField: -3.14,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('DoubleRoute'), findsOneWidget);
expect(find.text('Param: 3.14'), findsOneWidget);
expect(find.text('Query param: -3.14'), findsOneWidget);
expect(find.text('Query param: -3.14'), findsOneWidget);
expect(find.text('Query param with default value: 1.0'), findsOneWidget);
IntRoute(
requiredIntField: 65,
intField: -65,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('IntRoute'), findsOneWidget);
expect(find.text('Param: 65'), findsOneWidget);
expect(find.text('Query param: -65'), findsOneWidget);
expect(find.text('Query param with default value: 1'), findsOneWidget);
NumRoute(
requiredNumField: 987.32,
numField: -987.32,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('NumRoute'), findsOneWidget);
expect(find.text('Param: 987.32'), findsOneWidget);
expect(find.text('Query param: -987.32'), findsOneWidget);
expect(find.text('Query param with default value: 1'), findsOneWidget);
StringRoute(
requiredStringField: r'Tytire tu patulae recubans sub tegmine fagi.',
stringField: r'Tytire tu patulae recubans sub tegmine fagi.',
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('StringRoute'), findsOneWidget);
expect(find.text('Param: Tytire tu patulae recubans sub tegmine fagi.'),
findsOneWidget);
expect(
find.text('Query param: Tytire tu patulae recubans sub tegmine fagi.'),
findsOneWidget);
expect(find.text('Query param with default value: defaultValue'),
findsOneWidget);
EnumRoute(
requiredEnumField: PersonDetails.favoriteFood,
enumField: PersonDetails.favoriteSport,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('EnumRoute'), findsOneWidget);
expect(find.text('Param: PersonDetails.favoriteFood'), findsOneWidget);
expect(
find.text('Query param: PersonDetails.favoriteSport'), findsOneWidget);
expect(
find.text('Query param with default value: PersonDetails.favoriteFood'),
findsOneWidget,
);
EnhancedEnumRoute(
requiredEnumField: SportDetails.football,
enumField: SportDetails.hockey,
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('EnhancedEnumRoute'), findsOneWidget);
expect(find.text('Param: SportDetails.football'), findsOneWidget);
expect(find.text('Query param: SportDetails.hockey'), findsOneWidget);
expect(
find.text('Query param with default value: SportDetails.football'),
findsOneWidget,
);
UriRoute(
requiredUriField: Uri.parse('https://dart.dev'),
uriField: Uri.parse('https://dart.dev'),
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('UriRoute'), findsOneWidget);
expect(find.text('Param: https://dart.dev'), findsOneWidget);
expect(find.text('Query param: https://dart.dev'), findsOneWidget);
IterableRoute(
enumIterableField: <SportDetails>[SportDetails.football],
intListField: <int>[1, 2, 3],
enumOnlyInSetField: <CookingRecipe>{
CookingRecipe.burger,
CookingRecipe.pizza,
},
).go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('IterableRoute'), findsOneWidget);
expect(
find.text(
'/iterable-route?enum-iterable-field=football&int-list-field=1&int-list-field=2&int-list-field=3&enum-only-in-set-field=burger&enum-only-in-set-field=pizza'),
findsOneWidget);
});
testWidgets(
'It should navigate to the iterable route with its default values',
(WidgetTester tester) async {
await tester.pumpWidget(AllTypesApp());
final ScaffoldState scaffoldState =
tester.firstState(find.byType(Scaffold));
const IterableRouteWithDefaultValues().go(scaffoldState.context);
await tester.pumpAndSettle();
expect(find.text('IterableRouteWithDefaultValues'), findsOneWidget);
final IterablePage page =
tester.widget<IterablePage>(find.byType(IterablePage));
expect(
page,
isA<IterablePage>().having(
(IterablePage page) => page.intIterableField,
'intIterableField',
const <int>[0],
).having(
(IterablePage page) => page.intListField,
'intListField',
const <int>[0],
).having(
(IterablePage page) => page.intSetField,
'intSetField',
const <int>{0, 1},
).having(
(IterablePage page) => page.doubleIterableField,
'doubleIterableField',
const <double>[0, 1, 2],
).having(
(IterablePage page) => page.doubleListField,
'doubleListField',
const <double>[1, 2, 3],
).having(
(IterablePage page) => page.doubleSetField,
'doubleSetField',
const <double>{},
).having(
(IterablePage page) => page.stringIterableField,
'stringIterableField',
const <String>['defaultValue'],
).having(
(IterablePage page) => page.stringListField,
'stringListField',
const <String>['defaultValue0', 'defaultValue1'],
).having(
(IterablePage page) => page.stringSetField,
'stringSetField',
const <String>{'defaultValue'},
).having(
(IterablePage page) => page.boolIterableField,
'boolIterableField',
const <bool>[false],
).having(
(IterablePage page) => page.boolListField,
'boolListField',
const <bool>[true],
).having(
(IterablePage page) => page.boolSetField,
'boolSetField',
const <bool>{true, false},
).having(
(IterablePage page) => page.enumIterableField,
'enumIterableField',
const <SportDetails>[SportDetails.tennis, SportDetails.hockey],
).having(
(IterablePage page) => page.enumListField,
'enumListField',
const <SportDetails>[SportDetails.football],
).having(
(IterablePage page) => page.enumSetField,
'enumSetField',
const <SportDetails>{SportDetails.hockey},
),
);
expect(find.text('/iterable-route-with-default-values'), findsOneWidget);
});
}
| packages/packages/go_router_builder/example/test/all_types_test.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/test/all_types_test.dart",
"repo_id": "packages",
"token_count": 3216
} | 962 |
Could not find a field for the path parameter "id".
| packages/packages/go_router_builder/test_inputs/bad_path_pattern.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/bad_path_pattern.dart.expect",
"repo_id": "packages",
"token_count": 13
} | 963 |
RouteBase get $namedRoute => GoRouteData.$route(
path: '/named-route',
name: 'namedRoute',
factory: $NamedRouteExtension._fromState,
);
extension $NamedRouteExtension on NamedRoute {
static NamedRoute _fromState(GoRouterState state) => NamedRoute();
String get location => GoRouteData.$location(
'/named-route',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
| packages/packages/go_router_builder/test_inputs/named_route.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/named_route.dart.expect",
"repo_id": "packages",
"token_count": 211
} | 964 |
The ShellRouteData "ShellRouteWithoutUnnamedConstructor" class must have an unnamed constructor.
| packages/packages/go_router_builder/test_inputs/shell_route_data_without_unnamed_constructor.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/shell_route_data_without_unnamed_constructor.dart.expect",
"repo_id": "packages",
"token_count": 21
} | 965 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// the following ignore is needed for downgraded analyzer (casts to JSObject).
// ignore_for_file: unnecessary_cast
import 'dart:async';
import 'dart:js_interop';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_identity_services_web/id.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/web.dart' as web;
import 'utils.dart' as utils;
void main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
// Load web/mock-gis.js in the page
await utils.installGisMock();
});
group('renderButton', () {
testWidgets('supports a js-interop target from any library', (_) async {
final web.HTMLDivElement target =
web.document.createElement('div') as web.HTMLDivElement;
id.renderButton(target);
final web.Element? button = target.querySelector('button');
expect(button, isNotNull);
});
});
group('IdConfig', () {
testWidgets('passes values from Dart to JS', (_) async {
final IdConfiguration config = IdConfiguration(
client_id: 'testing_1-2-3',
auto_select: false,
callback: (_) {},
login_uri: Uri.parse('https://www.example.com/login'),
native_callback: (_) {},
cancel_on_tap_outside: false,
prompt_parent_id: 'some_dom_id',
nonce: 's0m3_r4ndOM_vALu3',
context: OneTapContext.signin,
state_cookie_domain: 'subdomain.example.com',
ux_mode: UxMode.popup,
allowed_parent_origin: <String>['allowed', 'another'],
intermediate_iframe_close_callback: () {},
itp_support: true,
login_hint: '[email protected]',
hd: 'hd_value',
use_fedcm_for_prompt: true,
);
final utils.ExpectConfigValueFn expectConfigValue =
utils.createExpectConfigValue(config as JSObject);
expectConfigValue('client_id', 'testing_1-2-3');
expectConfigValue('auto_select', isFalse);
expectConfigValue('callback', utils.isAJs('function'));
expectConfigValue('login_uri', 'https://www.example.com/login');
expectConfigValue('native_callback', utils.isAJs('function'));
expectConfigValue('cancel_on_tap_outside', isFalse);
expectConfigValue('allowed_parent_origin', isA<JSArray<JSString>>());
expectConfigValue('prompt_parent_id', 'some_dom_id');
expectConfigValue('nonce', 's0m3_r4ndOM_vALu3');
expectConfigValue('context', 'signin');
expectConfigValue('state_cookie_domain', 'subdomain.example.com');
expectConfigValue('ux_mode', 'popup');
expectConfigValue(
'allowed_parent_origin', <String>['allowed', 'another']);
expectConfigValue(
'intermediate_iframe_close_callback', utils.isAJs('function'));
expectConfigValue('itp_support', isTrue);
expectConfigValue('login_hint', '[email protected]');
expectConfigValue('hd', 'hd_value');
expectConfigValue('use_fedcm_for_prompt', isTrue);
});
});
group('prompt', () {
testWidgets('supports a moment notification callback', (_) async {
id.initialize(IdConfiguration(client_id: 'testing_1-2-3'));
final StreamController<PromptMomentNotification> controller =
StreamController<PromptMomentNotification>();
id.prompt(controller.add);
final PromptMomentNotification moment = await controller.stream.first;
// These defaults are set in mock-gis.js
expect(moment.getMomentType(), MomentType.skipped);
expect(moment.getSkippedReason(), MomentSkippedReason.user_cancel);
});
testWidgets('calls config callback with credential response', (_) async {
const String expected = 'should_be_a_proper_jwt_token';
utils.setMockCredentialResponse(expected);
final StreamController<CredentialResponse> controller =
StreamController<CredentialResponse>();
id.initialize(IdConfiguration(
client_id: 'testing_1-2-3',
callback: controller.add,
));
id.prompt();
final CredentialResponse response = await controller.stream.first;
expect(response.credential, expected);
});
});
}
| packages/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart",
"repo_id": "packages",
"token_count": 1657
} | 966 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is used to mock the GIS library for integration tests under:
// example/integration_test
class PromptMomentNotification {
constructor(momentType, reason) {
this.momentType = momentType;
this.reason = reason;
this.getNotDisplayedReason = this._getReason;
this.getSkippedReason = this._getReason;
this.getDismissedReason = this._getReason;
}
getMomentType() { return this.momentType; }
_getReason() { return this.reason; }
isDismissedMoment() { return this.momentType === "dismissed" }
isDisplayMoment() { return this.momentType === "display" }
isSkippedMoment() { return this.momentType === "skipped" }
isDisplayed() { return this.isDisplayMoment() && !this.reason; }
isNotDisplayed() { return this.isDisplayMoment() && this.reason; }
}
const CREDENTIAL_RETURNED = new PromptMomentNotification("dismissed", "credential_returned");
const USER_CANCEL = new PromptMomentNotification("skipped", "user_cancel");
function callAsync(func, timeout = 100) {
window.setTimeout(func, timeout)
}
class Id {
initialize(config) {
this.config = config;
}
renderButton(target, config) {
// Simulate rendering a button.
target.replaceChildren();
target.dataset.buttonConfig = config;
let button = document.createElement('button');
target.append(button);
}
prompt(momentListener) {
callAsync(() => {
if (this.mockCredentialResponse) {
let callback = this.config.callback;
if (callback) {
callback(this.mockCredentialResponse);
}
if (momentListener) {
momentListener(CREDENTIAL_RETURNED);
}
} else if (momentListener) {
momentListener(USER_CANCEL);
}
});
}
setMockCredentialResponse(credential, select_by) {
this.mockCredentialResponse = {
credential: credential,
select_by: select_by,
};
}
disableAutoSelect() {}
storeCredential() {}
cancel() {}
revoke(hint, callback) {
this.mockCredentialResponse = null;
if (!callback) {
return;
}
callAsync(() => {
callback({
successful: true,
error: 'Revoked ' + hint,
});
})
}
}
class CodeClient {
constructor(config) {
this.config = config;
}
requestCode() {
let callback = this.config.callback;
if (!callback) {
return;
}
callAsync(() => {
callback(this.codeResponse);
});
}
setMockCodeResponse(codeResponse) {
this.codeResponse = codeResponse;
}
}
class TokenClient {
constructor(config) {
this.config = config;
}
requestAccessToken(overridableConfig) {
this.config = {...this.config, ...overridableConfig};
let callback = this.config.callback;
if (!callback) {
return;
}
callAsync(() => {
callback({
...this.tokenResponse,
scope: this.config.scope,
});
});
}
setMockTokenResponse(access_token) {
this.tokenResponse = {
access_token: access_token,
token_type: access_token != null ? 'Bearer' : null,
error: access_token == null ? 'unauthorized' : null,
};
}
}
class Oauth2 {
initCodeClient(config) {
return new CodeClient(config);
}
initTokenClient(config) {
return new TokenClient(config);
}
hasGrantedAllScopes(tokenResponse, scope, ...scopes) {
return tokenResponse != null && !scope.startsWith('not-granted-');
}
hasGrantedAnyScopes(tokenResponse, scope, ...scopes) {
return false; // Unused in the lib
}
revoke(accessToken, done) {
if (!done) {
return;
}
callAsync(() => {
done({
success: true,
});
})
}
}
(function() {
let goog = {
accounts: {
id: new Id(),
oauth2: new Oauth2(),
}
};
globalThis['google'] = goog;
}());
| packages/packages/google_identity_services_web/example/web/mock-gis.js/0 | {
"file_path": "packages/packages/google_identity_services_web/example/web/mock-gis.js",
"repo_id": "packages",
"token_count": 1525
} | 967 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
@TestOn('vm')
library;
import 'package:test/test.dart';
void main() {
test('Tell the user where to find the real tests', () {
print('---');
print('This package uses `dart test -p chrome` for its tests.');
print('See `README.md` for more info.');
print('---');
});
}
| packages/packages/google_identity_services_web/test/only_chrome_tests_here_test.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/test/only_chrome_tests_here_test.dart",
"repo_id": "packages",
"token_count": 160
} | 968 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:integration_test/integration_test.dart';
import 'shared.dart';
/// Integration Tests that only need a standard [GoogleMapController].
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
runTests();
}
void runTests() {
testWidgets('testInitialCenterLocationAtCenter', (WidgetTester tester) async {
await tester.binding.setSurfaceSize(const Size(800, 600));
final Completer<GoogleMapController> mapControllerCompleter =
Completer<GoogleMapController>();
final Key key = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
mapControllerCompleter.complete(controller);
},
),
),
);
final GoogleMapController mapController =
await mapControllerCompleter.future;
await tester.pumpAndSettle();
// TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen
// in `mapRendered`.
// https://github.com/flutter/flutter/issues/54758
await Future<void>.delayed(const Duration(seconds: 1));
final ScreenCoordinate coordinate =
await mapController.getScreenCoordinate(kInitialCameraPosition.target);
final Rect rect = tester.getRect(find.byKey(key));
if (isIOS || isWeb) {
// On iOS, the coordinate value from the GoogleMapSdk doesn't include the devicePixelRatio`.
// So we don't need to do the conversion like we did below for other platforms.
expect(coordinate.x, (rect.center.dx - rect.topLeft.dx).round());
expect(coordinate.y, (rect.center.dy - rect.topLeft.dy).round());
} else {
expect(
coordinate.x,
((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio)
.round());
expect(
coordinate.y,
((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio)
.round());
}
await tester.binding.setSurfaceSize(null);
},
// Android doesn't like the layout required for the web, so we skip web in this test.
// The equivalent web test already exists here:
// https://github.com/flutter/packages/blob/c43cc13498a1a1c4f3d1b8af2add9ce7c15bd6d0/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart#L78
skip: isWeb ||
// TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825
isIOS);
testWidgets('testGetVisibleRegion', (WidgetTester tester) async {
final Key key = GlobalKey();
final LatLngBounds zeroLatLngBounds = LatLngBounds(
southwest: const LatLng(0, 0), northeast: const LatLng(0, 0));
final Completer<GoogleMapController> mapControllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
mapControllerCompleter.complete(controller);
},
),
);
await tester.pumpAndSettle();
final GoogleMapController mapController =
await mapControllerCompleter.future;
// Wait for the visible region to be non-zero.
final LatLngBounds firstVisibleRegion =
await waitForValueMatchingPredicate<LatLngBounds>(
tester,
() => mapController.getVisibleRegion(),
(LatLngBounds bounds) => bounds != zeroLatLngBounds) ??
zeroLatLngBounds;
expect(firstVisibleRegion, isNot(zeroLatLngBounds));
expect(firstVisibleRegion.contains(kInitialMapCenter), isTrue);
// Making a new `LatLngBounds` about (10, 10) distance south west to the `firstVisibleRegion`.
// The size of the `LatLngBounds` is 10 by 10.
final LatLng southWest = LatLng(firstVisibleRegion.southwest.latitude - 20,
firstVisibleRegion.southwest.longitude - 20);
final LatLng northEast = LatLng(firstVisibleRegion.southwest.latitude - 10,
firstVisibleRegion.southwest.longitude - 10);
final LatLng newCenter = LatLng(
(northEast.latitude + southWest.latitude) / 2,
(northEast.longitude + southWest.longitude) / 2,
);
expect(firstVisibleRegion.contains(northEast), isFalse);
expect(firstVisibleRegion.contains(southWest), isFalse);
final LatLngBounds latLngBounds =
LatLngBounds(southwest: southWest, northeast: northEast);
// TODO(iskakaushik): non-zero padding is needed for some device configurations
// https://github.com/flutter/flutter/issues/30575
const double padding = 0;
await mapController
.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding));
await tester.pumpAndSettle(const Duration(seconds: 3));
final LatLngBounds secondVisibleRegion =
await mapController.getVisibleRegion();
expect(secondVisibleRegion, isNot(zeroLatLngBounds));
expect(firstVisibleRegion, isNot(secondVisibleRegion));
expect(secondVisibleRegion.contains(newCenter), isTrue);
},
// TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825
skip: isIOS);
testWidgets('testSetMapStyle valid Json String', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
const String mapStyle =
'[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]';
await controller.setMapStyle(mapStyle);
});
testWidgets('testSetMapStyle invalid Json String',
(WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
try {
await controller.setMapStyle('invalid_value');
fail('expected MapStyleException');
} on MapStyleException catch (e) {
expect(e.cause, isNotNull);
}
});
testWidgets('testSetMapStyle null string', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
await controller.setMapStyle(null);
});
testWidgets('testGetLatLng', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
await tester.pumpAndSettle();
// TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen
// in `mapRendered`.
// https://github.com/flutter/flutter/issues/54758
await Future<void>.delayed(const Duration(seconds: 1));
final LatLngBounds visibleRegion = await controller.getVisibleRegion();
final LatLng topLeft =
await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0));
final LatLng northWest = LatLng(
visibleRegion.northeast.latitude,
visibleRegion.southwest.longitude,
);
expect(topLeft, northWest);
});
testWidgets('testGetZoomLevel', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
await tester.pumpAndSettle();
// TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen
// in `mapRendered`.
// https://github.com/flutter/flutter/issues/54758
await Future<void>.delayed(const Duration(seconds: 1));
double zoom = await controller.getZoomLevel();
expect(zoom, kInitialZoomLevel);
await controller.moveCamera(CameraUpdate.zoomTo(7));
await tester.pumpAndSettle();
zoom = await controller.getZoomLevel();
expect(zoom, equals(7));
},
// TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825
skip: isIOS);
testWidgets('testScreenCoordinate', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
await tester.pumpAndSettle();
// TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen
// in `mapRendered`.
// https://github.com/flutter/flutter/issues/54758
await Future<void>.delayed(const Duration(seconds: 1));
final LatLngBounds visibleRegion = await controller.getVisibleRegion();
final LatLng northWest = LatLng(
visibleRegion.northeast.latitude,
visibleRegion.southwest.longitude,
);
final ScreenCoordinate topLeft =
await controller.getScreenCoordinate(northWest);
expect(topLeft, const ScreenCoordinate(x: 0, y: 0));
},
// TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825
skip: isIOS);
testWidgets('testResizeWidget', (WidgetTester tester) async {
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) async {
controllerCompleter.complete(controller);
},
),
const Size(100, 100),
);
final GoogleMapController controller = await controllerCompleter.future;
await pumpMap(
tester,
GoogleMap(
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) async {
// fail!
fail('The map should not get recreated!');
// controllerCompleter.complete(controller);
},
),
const Size(400, 400),
);
await tester.pumpAndSettle();
// TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen
// in `mapRendered`.
// https://github.com/flutter/flutter/issues/54758
await Future<void>.delayed(const Duration(seconds: 1));
// Simple call to make sure that the app hasn't crashed.
final LatLngBounds bounds1 = await controller.getVisibleRegion();
final LatLngBounds bounds2 = await controller.getVisibleRegion();
expect(bounds1, bounds2);
});
testWidgets('testToggleInfoWindow', (WidgetTester tester) async {
const Marker marker = Marker(
markerId: MarkerId('marker'),
infoWindow: InfoWindow(title: 'InfoWindow'));
final Set<Marker> markers = <Marker>{marker};
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
markers: markers,
onMapCreated: (GoogleMapController googleMapController) {
controllerCompleter.complete(googleMapController);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
await tester.pumpAndSettle();
// TODO(mossmana): Adding this delay addresses
// https://github.com/flutter/flutter/issues/131783. It may be related
// to https://github.com/flutter/flutter/issues/54758 and should be
// re-evaluated when that issue is fixed.
await Future<void>.delayed(const Duration(seconds: 1));
bool iwVisibleStatus =
await controller.isMarkerInfoWindowShown(marker.markerId);
expect(iwVisibleStatus, false);
await controller.showMarkerInfoWindow(marker.markerId);
// The Maps SDK doesn't always return true for whether it is shown
// immediately after showing it, so wait for it to report as shown.
iwVisibleStatus = await waitForValueMatchingPredicate<bool>(
tester,
() => controller.isMarkerInfoWindowShown(marker.markerId),
(bool visible) => visible) ??
false;
expect(iwVisibleStatus, true);
await controller.hideMarkerInfoWindow(marker.markerId);
iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId);
expect(iwVisibleStatus, false);
});
testWidgets('testTakeSnapshot', (WidgetTester tester) async {
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
await tester.pumpAndSettle(const Duration(seconds: 3));
final GoogleMapController controller = await controllerCompleter.future;
final Uint8List? bytes = await controller.takeSnapshot();
expect(bytes?.isNotEmpty, true);
},
// TODO(cyanglaz): un-skip the test when we can test this on CI with API key enabled.
// https://github.com/flutter/flutter/issues/57057
// https://github.com/flutter/flutter/issues/139825
skip: isAndroid || isWeb || isIOS);
testWidgets(
'testCloudMapId',
(WidgetTester tester) async {
final Completer<int> mapIdCompleter = Completer<int>();
final Key key = GlobalKey();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
onMapCreated: (GoogleMapController controller) {
mapIdCompleter.complete(controller.mapId);
},
cloudMapId: kCloudMapId,
),
);
await tester.pumpAndSettle();
// Await mapIdCompleter to finish to make sure map can be created with cloudMapId
await mapIdCompleter.future;
},
);
testWidgets('getStyleError reports last error', (WidgetTester tester) async {
final Key key = GlobalKey();
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await pumpMap(
tester,
GoogleMap(
key: key,
initialCameraPosition: kInitialCameraPosition,
style: '[[[this is an invalid style',
onMapCreated: (GoogleMapController controller) {
controllerCompleter.complete(controller);
},
),
);
final GoogleMapController controller = await controllerCompleter.future;
final String? error = await controller.getStyleError();
expect(error, isNotNull);
});
}
/// Repeatedly checks an asynchronous value against a test condition.
///
/// This function waits one frame between each check, returning the value if it
/// passes the predicate before [maxTries] is reached.
///
/// Returns null if the predicate is never satisfied.
///
/// This is useful for cases where the Maps SDK has some internally
/// asynchronous operation that we don't have visibility into (e.g., native UI
/// animations).
Future<T?> waitForValueMatchingPredicate<T>(WidgetTester tester,
Future<T> Function() getValue, bool Function(T) predicate,
{int maxTries = 100}) async {
for (int i = 0; i < maxTries; i++) {
final T value = await getValue();
if (predicate(value)) {
return value;
}
await tester.pump();
}
return null;
}
| packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart",
"repo_id": "packages",
"token_count": 6590
} | 969 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.googlemaps;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
class TileOverlayBuilder implements TileOverlaySink {
private final TileOverlayOptions tileOverlayOptions;
TileOverlayBuilder() {
this.tileOverlayOptions = new TileOverlayOptions();
}
TileOverlayOptions build() {
return tileOverlayOptions;
}
@Override
public void setFadeIn(boolean fadeIn) {
tileOverlayOptions.fadeIn(fadeIn);
}
@Override
public void setTransparency(float transparency) {
tileOverlayOptions.transparency(transparency);
}
@Override
public void setZIndex(float zIndex) {
tileOverlayOptions.zIndex(zIndex);
}
@Override
public void setVisible(boolean visible) {
tileOverlayOptions.visible(visible);
}
@Override
public void setTileProvider(TileProvider tileProvider) {
tileOverlayOptions.tileProvider(tileProvider);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlayBuilder.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlayBuilder.java",
"repo_id": "packages",
"token_count": 349
} | 970 |
# Platform Implementation Test Apps
These are test apps for manual testing and automated integration testing
of this platform implementation. They are not intended to demonstrate actual
use of this package, since the intent is that plugin clients use the
app-facing package.
Unless you are making changes to this implementation package, these examples
are very unlikely to be relevant.
## Structure
This package contains multiple exmaples, which are used to test different
versions of the Google Maps iOS SDK. Because the plugin's dependency
is loosely pinned, CocoaPods will pick the newest version that supports the
minimum targetted OS version of the application using the plugin. In
order to ensure that the plugin continues to compile against all
SDK versions that could resolve, there are multiple largely identical
examples, each with a different minimum target iOS version.
In order to avoid wasting CI resources, tests are mostly not duplicated.
The test structure is:
* The oldest version has all of the usual tests (Dart integration,
XCTest, XCUITest).
* The newest version has only XCTests (the cheapest tests), which
can be used to unit tests any code paths that are specific to
new SDKs (e.g., behind target OS `#if` checks).
This setup is based on the assumption (based on experience so far) that
the changes in the SDK are unlikely to break functionality at runtime,
but that we will want to have unit test coverage of new-SDK-only code.
New test types can be added to any example if needs change.
## Updating Examples
* When a new major of the SDK comes out that raises the minimum
iOS deployment version, a new example with that minimum target
should be added to ensure that the plugin compiles with that
version of the SDK, and the range in the plugin's `podspec` file
should be bumped to the next major version.
* When the minimum supported version of Flutter (on `stable`)
reaches the point where the oldest example is for an SDK
that can no longer be resolved to, that example should be
removed, and all of its testing (Dart integration tests,
native unit tests, native UI tests) should be folded into
the next-oldest version.
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/README.md/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/README.md",
"repo_id": "packages",
"token_count": 503
} | 971 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'google_maps_flutter_ios'
s.version = '0.0.1'
s.summary = 'Google Maps for Flutter'
s.description = <<-DESC
A Flutter plugin that provides a Google Maps widget.
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/google_maps_flutter/google_maps_flutter/ios' }
s.documentation_url = 'https://pub.dev/packages/google_maps_flutter_ios'
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/google_maps_flutter_ios.modulemap'
s.dependency 'Flutter'
# Allow any version up to the next breaking change after the latest version that
# has been confirmed to be compatible via an example in examples/. See discussion
# in https://github.com/flutter/flutter/issues/86820 for why this is so broad.
s.dependency 'GoogleMaps', '< 9.0'
s.static_framework = true
s.platform = :ios, '12.0'
# GoogleMaps 6.x does not support arm64 simulators, but also doesn't declare
# explicitly that it doesn't, so mark that here so that the Flutter tool knows
# to build the Runner for x86_64 instead. See https://github.com/flutter/flutter/issues/94491
# TODO(stuartmorgan): Remove EXCLUDED_ARCHS once this plugin requires iOS 13+,
# at which point Cocoapods will resolve to a version of GoogleMaps that has
# arm64 support.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.resource_bundles = {'google_maps_flutter_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/google_maps_flutter_ios.podspec/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/google_maps_flutter_ios.podspec",
"repo_id": "packages",
"token_count": 742
} | 972 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../maps_object.dart';
/// Converts an [Iterable] of [MapsObject]s in a Map of [MapObjectId] -> [MapObject].
Map<MapsObjectId<T>, T> keyByMapsObjectId<T extends MapsObject<T>>(
Iterable<T> objects) {
return Map<MapsObjectId<T>, T>.fromEntries(objects.map((T object) =>
MapEntry<MapsObjectId<T>, T>(object.mapsId, object.clone())));
}
/// Converts a Set of [MapsObject]s into something serializable in JSON.
Object serializeMapsObjectSet<T>(Set<MapsObject<T>> mapsObjects) {
return mapsObjects.map<Object>((MapsObject<T> p) => p.toJson()).toList();
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart",
"repo_id": "packages",
"token_count": 249
} | 973 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_platform_interface/src/types/utils/maps_object.dart';
import 'test_maps_object.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('keyByMapsObjectId', () async {
const MapsObjectId<TestMapsObject> id1 = MapsObjectId<TestMapsObject>('1');
const MapsObjectId<TestMapsObject> id2 = MapsObjectId<TestMapsObject>('2');
const MapsObjectId<TestMapsObject> id3 = MapsObjectId<TestMapsObject>('3');
const TestMapsObject object1 = TestMapsObject(id1);
const TestMapsObject object2 = TestMapsObject(id2, data: 2);
const TestMapsObject object3 = TestMapsObject(id3);
expect(
keyByMapsObjectId(<TestMapsObject>{object1, object2, object3}),
<MapsObjectId<TestMapsObject>, TestMapsObject>{
id1: object1,
id2: object2,
id3: object3,
});
});
test('serializeMapsObjectSet', () async {
const MapsObjectId<TestMapsObject> id1 = MapsObjectId<TestMapsObject>('1');
const MapsObjectId<TestMapsObject> id2 = MapsObjectId<TestMapsObject>('2');
const MapsObjectId<TestMapsObject> id3 = MapsObjectId<TestMapsObject>('3');
const TestMapsObject object1 = TestMapsObject(id1);
const TestMapsObject object2 = TestMapsObject(id2, data: 2);
const TestMapsObject object3 = TestMapsObject(id3);
expect(
serializeMapsObjectSet(<TestMapsObject>{object1, object2, object3}),
<Map<String, Object>>[
<String, Object>{'id': '1'},
<String, Object>{'id': '2'},
<String, Object>{'id': '3'}
]);
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart",
"repo_id": "packages",
"token_count": 711
} | 974 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
| packages/packages/google_sign_in/google_sign_in/example/android/gradle.properties/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 22
} | 975 |
// Mocks generated by Mockito 5.4.4 from annotations
// in google_sign_in/test/google_sign_in_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'
as _i3;
import 'package:google_sign_in_platform_interface/src/types.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 _FakeGoogleSignInTokenData_0 extends _i1.SmartFake
implements _i2.GoogleSignInTokenData {
_FakeGoogleSignInTokenData_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [GoogleSignInPlatform].
///
/// See the documentation for Mockito's code generation for more information.
class MockGoogleSignInPlatform extends _i1.Mock
implements _i3.GoogleSignInPlatform {
MockGoogleSignInPlatform() {
_i1.throwOnMissingStub(this);
}
@override
bool get isMock => (super.noSuchMethod(
Invocation.getter(#isMock),
returnValue: false,
) as bool);
@override
_i4.Future<void> init({
List<String>? scopes = const [],
_i2.SignInOption? signInOption = _i2.SignInOption.standard,
String? hostedDomain,
String? clientId,
}) =>
(super.noSuchMethod(
Invocation.method(
#init,
[],
{
#scopes: scopes,
#signInOption: signInOption,
#hostedDomain: hostedDomain,
#clientId: clientId,
},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> initWithParams(_i2.SignInInitParameters? params) =>
(super.noSuchMethod(
Invocation.method(
#initWithParams,
[params],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<_i2.GoogleSignInUserData?> signInSilently() => (super.noSuchMethod(
Invocation.method(
#signInSilently,
[],
),
returnValue: _i4.Future<_i2.GoogleSignInUserData?>.value(),
) as _i4.Future<_i2.GoogleSignInUserData?>);
@override
_i4.Future<_i2.GoogleSignInUserData?> signIn() => (super.noSuchMethod(
Invocation.method(
#signIn,
[],
),
returnValue: _i4.Future<_i2.GoogleSignInUserData?>.value(),
) as _i4.Future<_i2.GoogleSignInUserData?>);
@override
_i4.Future<_i2.GoogleSignInTokenData> getTokens({
required String? email,
bool? shouldRecoverAuth,
}) =>
(super.noSuchMethod(
Invocation.method(
#getTokens,
[],
{
#email: email,
#shouldRecoverAuth: shouldRecoverAuth,
},
),
returnValue: _i4.Future<_i2.GoogleSignInTokenData>.value(
_FakeGoogleSignInTokenData_0(
this,
Invocation.method(
#getTokens,
[],
{
#email: email,
#shouldRecoverAuth: shouldRecoverAuth,
},
),
)),
) as _i4.Future<_i2.GoogleSignInTokenData>);
@override
_i4.Future<void> signOut() => (super.noSuchMethod(
Invocation.method(
#signOut,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> disconnect() => (super.noSuchMethod(
Invocation.method(
#disconnect,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<bool> isSignedIn() => (super.noSuchMethod(
Invocation.method(
#isSignedIn,
[],
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<void> clearAuthCache({required String? token}) =>
(super.noSuchMethod(
Invocation.method(
#clearAuthCache,
[],
{#token: token},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<bool> requestScopes(List<String>? scopes) => (super.noSuchMethod(
Invocation.method(
#requestScopes,
[scopes],
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> canAccessScopes(
List<String>? scopes, {
String? accessToken,
}) =>
(super.noSuchMethod(
Invocation.method(
#canAccessScopes,
[scopes],
{#accessToken: accessToken},
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
}
| packages/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart",
"repo_id": "packages",
"token_count": 2599
} | 976 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/google_sign_in/google_sign_in_android/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_android/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 977 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'google_sign_in_ios'
s.version = '0.0.1'
s.summary = 'Google Sign-In plugin for Flutter'
s.description = <<-DESC
Enables Google Sign-In in Flutter apps.
DESC
s.homepage = 'https://github.com/flutter/packages/tree/main/packages/google_sign_in'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in_ios' }
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/FLTGoogleSignInPlugin.modulemap'
s.dependency 'GoogleSignIn', '~> 7.0'
s.static_framework = true
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.15'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.resource_bundles = {'google_sign_in_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
| packages/packages/google_sign_in/google_sign_in_ios/darwin/google_sign_in_ios.podspec/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/google_sign_in_ios.podspec",
"repo_id": "packages",
"token_count": 543
} | 978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.