text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
export 'home_page.dart'; export 'home_view.dart';
news_toolkit/flutter_news_example/lib/home/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/home/view/view.dart", "repo_id": "news_toolkit", "token_count": 20 }
871
export 'view/view.dart';
news_toolkit/flutter_news_example/lib/magic_link_prompt/magic_link_prompt.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/magic_link_prompt/magic_link_prompt.dart", "repo_id": "news_toolkit", "token_count": 10 }
872
export 'view/network_error.dart';
news_toolkit/flutter_news_example/lib/network_error/network_error.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/network_error/network_error.dart", "repo_id": "news_toolkit", "token_count": 12 }
873
part of 'onboarding_bloc.dart'; abstract class OnboardingEvent extends Equatable { const OnboardingEvent(); } class EnableAdTrackingRequested extends OnboardingEvent { const EnableAdTrackingRequested(); @override List<Object?> get props => []; } class EnableNotificationsRequested extends OnboardingEvent { const EnableNotificationsRequested(); @override List<Object?> get props => []; }
news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_event.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_event.dart", "repo_id": "news_toolkit", "token_count": 116 }
874
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; class SearchTextField extends StatelessWidget { const SearchTextField({required this.controller, super.key}); final TextEditingController controller; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: AppTextField( controller: controller, prefix: const Icon(Icons.search), suffix: IconButton( onPressed: controller.clear, icon: const Icon(Icons.clear), ), hintText: context.l10n.searchByKeyword, keyboardType: TextInputType.text, ), ); } }
news_toolkit/flutter_news_example/lib/search/widgets/search_text_field.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/widgets/search_text_field.dart", "repo_id": "news_toolkit", "token_count": 297 }
875
import 'package:app_ui/app_ui.dart' show AppButton, AppColors, AppSpacing, Assets, showAppModal; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.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/article/article.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:visibility_detector/visibility_detector.dart'; @visibleForTesting class SubscribeWithArticleLimitModal extends StatefulWidget { const SubscribeWithArticleLimitModal({super.key}); @override State<SubscribeWithArticleLimitModal> createState() => _SubscribeWithArticleLimitModalState(); } class _SubscribeWithArticleLimitModalState extends State<SubscribeWithArticleLimitModal> { bool _modalShown = false; @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; final isLoggedIn = context.select((AppBloc bloc) => bloc.state.status.isLoggedIn); final articleTitle = context.select((ArticleBloc bloc) => bloc.state.title); final watchVideoButtonTitle = l10n.subscribeWithArticleLimitModalWatchVideoButton; return VisibilityDetector( key: const Key('subscribeWithArticleLimitModal_visibilityDetector'), onVisibilityChanged: _modalShown ? null : (visibility) { if (!visibility.visibleBounds.isEmpty) { context.read<AnalyticsBloc>().add( TrackAnalyticsEvent( PaywallPromptEvent.impression( impression: PaywallPromptImpression.rewarded, articleTitle: articleTitle ?? '', ), ), ); setState(() => _modalShown = true); } }, child: ColoredBox( color: AppColors.darkBackground, child: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: AppSpacing.lg), Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xlg), child: Text( l10n.subscribeWithArticleLimitModalTitle, style: theme.textTheme.displaySmall ?.apply(color: AppColors.white), ), ), const SizedBox(height: AppSpacing.sm + AppSpacing.xxs), Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xlg), child: Text( l10n.subscribeWithArticleLimitModalSubtitle, style: theme.textTheme.titleMedium ?.apply(color: AppColors.mediumEmphasisPrimary), ), ), const SizedBox(height: AppSpacing.lg + AppSpacing.lg), Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg + AppSpacing.xxs, ), child: AppButton.redWine( key: const Key( 'subscribeWithArticleLimitModal_subscribeButton', ), child: Text(l10n.subscribeButtonText), onPressed: () { showPurchaseSubscriptionDialog(context: context); context.read<AnalyticsBloc>().add( TrackAnalyticsEvent( PaywallPromptEvent.click( articleTitle: articleTitle ?? '', ), ), ); }, ), ), const SizedBox(height: AppSpacing.lg), if (!isLoggedIn) ...[ Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg + AppSpacing.xxs, ), child: AppButton.outlinedTransparentWhite( key: const Key('subscribeWithArticleLimitModal_logInButton'), child: Text(l10n.subscribeWithArticleLimitModalLogInButton), onPressed: () => showAppModal<void>( context: context, builder: (context) => const LoginModal(), routeSettings: const RouteSettings(name: LoginModal.name), ), ), ), const SizedBox(height: AppSpacing.lg), ], Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg + AppSpacing.xxs, ), child: AppButton.transparentWhite( key: const Key( 'subscribeWithArticleLimitModal_watchVideoButton', ), onPressed: () => context .read<FullScreenAdsBloc>() .add(const ShowRewardedAdRequested()), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.video.svg(), const SizedBox(width: AppSpacing.sm), Text(watchVideoButtonTitle), ], ), ), ), const SizedBox(height: AppSpacing.sm), ], ), ), ), ); } }
news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscribe_with_article_limit_modal.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscribe_with_article_limit_modal.dart", "repo_id": "news_toolkit", "token_count": 3167 }
876
part of 'user_profile_bloc.dart'; enum UserProfileStatus { initial, fetchingNotificationsEnabled, fetchingNotificationsEnabledFailed, fetchingNotificationsEnabledSucceeded, togglingNotifications, togglingNotificationsFailed, togglingNotificationsSucceeded, userUpdated, } class UserProfileState extends Equatable { const UserProfileState({ required this.status, required this.user, this.notificationsEnabled = false, }); const UserProfileState.initial() : this( status: UserProfileStatus.initial, user: User.anonymous, ); final UserProfileStatus status; final bool notificationsEnabled; final User user; @override List<Object?> get props => [status, user]; UserProfileState copyWith({ UserProfileStatus? status, bool? notificationsEnabled, User? user, }) => UserProfileState( status: status ?? this.status, notificationsEnabled: notificationsEnabled ?? this.notificationsEnabled, user: user ?? this.user, ); }
news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_state.dart", "repo_id": "news_toolkit", "token_count": 355 }
877
import 'package:analytics_repository/analytics_repository.dart'; import 'package:equatable/equatable.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; /// {@template analytics_failure} /// A base failure for the analytics repository failures. /// {@endtemplate} abstract class AnalyticsFailure with EquatableMixin implements Exception { /// {@macro analytics_failure} const AnalyticsFailure(this.error); /// The error which was caught. final Object error; @override List<Object> get props => [error]; } /// {@template track_event_failure} /// Thrown when tracking an event fails. /// {@endtemplate} class TrackEventFailure extends AnalyticsFailure { /// {@macro track_event_failure} const TrackEventFailure(super.error); } /// {@template set_user_id_failure} /// Thrown when setting the user identifier fails. /// {@endtemplate} class SetUserIdFailure extends AnalyticsFailure { /// {@macro set_user_id_failure} const SetUserIdFailure(super.error); } /// {@template analytics_repository} /// Repository which manages tracking analytics. /// {@endtemplate} class AnalyticsRepository { /// {@macro analytics_repository} const AnalyticsRepository(FirebaseAnalytics analytics) : _analytics = analytics; final FirebaseAnalytics _analytics; /// Tracks the provided [AnalyticsEvent]. Future<void> track(AnalyticsEvent event) async { try { await _analytics.logEvent( name: event.name, parameters: event.properties, ); } catch (error, stackTrace) { Error.throwWithStackTrace(TrackEventFailure(error), stackTrace); } } /// Sets the user identifier associated with tracked events. /// /// Setting a null [userId] will clear the user identifier. Future<void> setUserId(String? userId) async { try { await _analytics.setUserId(id: userId); } catch (error, stackTrace) { Error.throwWithStackTrace(SetUserIdFailure(error), stackTrace); } } }
news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/analytics_repository.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/analytics_repository.dart", "repo_id": "news_toolkit", "token_count": 628 }
878
package com.ui.gallery import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
news_toolkit/flutter_news_example/packages/app_ui/gallery/android/app/src/main/kotlin/com/ui/gallery/MainActivity.kt/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/android/app/src/main/kotlin/com/ui/gallery/MainActivity.kt", "repo_id": "news_toolkit", "token_count": 36 }
879
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class AppLogoPage extends StatelessWidget { const AppLogoPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const AppLogoPage()); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Logo'), ), body: ColoredBox( color: AppColors.darkBackground, child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ AppLogo.dark(), const SizedBox(height: AppSpacing.lg), AppLogo.light(), ], ), ), ), ); } }
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_logo_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_logo_page.dart", "repo_id": "news_toolkit", "token_count": 360 }
880
import 'package:intl/intl.dart'; /// Extension to make displaying [DateTime] objects simpler. extension DateTimeEx on DateTime { /// Converts [DateTime] into a MMMM dd, yyyy [String]. String get mDY { return DateFormat('MMMM d, yyyy').format(this); } }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/extensions/date_time_extension.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/extensions/date_time_extension.dart", "repo_id": "news_toolkit", "token_count": 93 }
881
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// {@template app_text_field} /// A text field component based on material [TextFormField] widget with a /// fixed, left-aligned label text displayed above the text field. /// {@endtemplate} class AppTextField extends StatelessWidget { /// {@macro app_text_field} const AppTextField({ super.key, this.initialValue, this.autoFillHints, this.controller, this.inputFormatters, this.autocorrect = true, this.readOnly = false, this.hintText, this.errorText, this.prefix, this.suffix, this.keyboardType, this.onChanged, this.onSubmitted, this.onTap, }); /// A value to initialize the field to. final String? initialValue; /// List of auto fill hints. final Iterable<String>? autoFillHints; /// Controls the text being edited. /// /// If null, this widget will create its own [TextEditingController] and /// initialize its [TextEditingController.text] with [initialValue]. final TextEditingController? controller; /// Optional input validation and formatting overrides. final List<TextInputFormatter>? inputFormatters; /// Whether to enable autocorrect. /// Defaults to true. final bool autocorrect; /// Whether the text field should be read-only. /// Defaults to false. final bool readOnly; /// Text that suggests what sort of input the field accepts. final String? hintText; /// Text that appears below the field. final String? errorText; /// A widget that appears before the editable part of the text field. final Widget? prefix; /// A widget that appears after the editable part of the text field. final Widget? suffix; /// The type of keyboard to use for editing the text. /// Defaults to [TextInputType.text] if maxLines is one and /// [TextInputType.multiline] otherwise. final TextInputType? keyboardType; /// Called when the user inserts or deletes texts in the text field. final ValueChanged<String>? onChanged; /// {@macro flutter.widgets.editableText.onSubmitted} final ValueChanged<String>? onSubmitted; /// Called when the text field has been tapped. final VoidCallback? onTap; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ConstrainedBox( constraints: const BoxConstraints(minHeight: 80), child: TextFormField( key: key, initialValue: initialValue, controller: controller, inputFormatters: inputFormatters, keyboardType: keyboardType, autocorrect: autocorrect, readOnly: readOnly, autofillHints: autoFillHints, cursorColor: AppColors.darkAqua, style: Theme.of(context).textTheme.titleLarge?.copyWith( fontWeight: FontWeight.w500, ), onFieldSubmitted: onSubmitted, decoration: InputDecoration( hintText: hintText, errorText: errorText, prefixIcon: prefix, suffixIcon: suffix, suffixIconConstraints: const BoxConstraints.tightFor( width: 32, height: 32, ), prefixIconConstraints: const BoxConstraints.tightFor( width: 48, ), ), onChanged: onChanged, onTap: onTap, ), ), ], ); } }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_text_field.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_text_field.dart", "repo_id": "news_toolkit", "token_count": 1401 }
882
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../helpers/helpers.dart'; void main() { group('ShowAppModal', () { testWidgets('renders modal', (tester) async { final modalKey = Key('appModal_container'); await tester.pumpApp( Builder( builder: (context) => ElevatedButton( onPressed: () => showAppModal<void>( context: context, builder: (context) => Container( key: modalKey, ), ), style: ElevatedButton.styleFrom( backgroundColor: AppColors.red, padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20), textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), child: const Text('Tap'), ), ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.byKey(modalKey), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/show_app_modal_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/show_app_modal_test.dart", "repo_id": "news_toolkit", "token_count": 549 }
883
import 'package:equatable/equatable.dart'; /// {@template authentication_user} /// User model /// /// [AuthenticationUser.anonymous] represents an unauthenticated user. /// {@endtemplate} class AuthenticationUser extends Equatable { /// {@macro authentication_user} const AuthenticationUser({ required this.id, this.email, this.name, this.photo, this.isNewUser = true, }); /// The current user's email address. final String? email; /// The current user's id. final String id; /// The current user's name (display name). final String? name; /// Url for the current user's photo. final String? photo; /// Whether the current user is a first time user. final bool isNewUser; /// Whether the current user is anonymous. bool get isAnonymous => this == anonymous; /// Anonymous user which represents an unauthenticated user. static const anonymous = AuthenticationUser(id: ''); @override List<Object?> get props => [email, id, name, photo, isNewUser]; }
news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/models/authentication_user.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/models/authentication_user.dart", "repo_id": "news_toolkit", "token_count": 295 }
884
export 'src/token_storage.dart';
news_toolkit/flutter_news_example/packages/authentication_client/token_storage/lib/token_storage.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/token_storage/lib/token_storage.dart", "repo_id": "news_toolkit", "token_count": 12 }
885
// ignore_for_file: prefer_const_constructors import 'package:email_launcher/email_launcher.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import '../helpers/helpers.dart'; void main() { final mock = MockUrlLauncher(); final emailLauncher = EmailLauncher(); setUp(() { UrlLauncherPlatform.instance = mock; }); group('EmailLauncher', () { group('launchEmailApp', () { group('when platform is Android', () { test('completes', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; expect(defaultTargetPlatform, TargetPlatform.android); expect(emailLauncher.launchEmailApp(), completes); debugDefaultTargetPlatformOverride = null; }); }); group('when platform is iOS', () { test('completes', () { final emailLauncher = EmailLauncher( launchUrlProvider: (_) => Future.value(true), canLaunchProvider: (_) => Future.value(true), ); debugDefaultTargetPlatformOverride = TargetPlatform.iOS; expect(defaultTargetPlatform, TargetPlatform.iOS); expect(emailLauncher.launchEmailApp(), completes); WidgetsFlutterBinding.ensureInitialized(); debugDefaultTargetPlatformOverride = null; }); group('calls canLaunch and launchUrl', () { test('when target platform is iOS', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; expect(defaultTargetPlatform, TargetPlatform.iOS); final url = Uri(scheme: 'message'); mock ..canLaunchUrl = url.toString() ..response = true; final result = await canLaunchUrl(url); mock ..setLaunchUrlExpectations( url: url.toString(), ) ..response = true; final launch = await launchUrl(url); await emailLauncher.launchEmailApp(); expect(result, isTrue); expect(launch, isTrue); debugDefaultTargetPlatformOverride = null; }); }); }); test( 'throws LaunchEmailAppFailure ' 'on generic exception', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; final emailLauncher = EmailLauncher( launchUrlProvider: (_) => throw Exception(), ); expect( emailLauncher.launchEmailApp, throwsA(isA<LaunchEmailAppFailure>()), ); debugDefaultTargetPlatformOverride = null; }); }); }); }
news_toolkit/flutter_news_example/packages/email_launcher/test/src/email_launcher_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/email_launcher/test/src/email_launcher_test.dart", "repo_id": "news_toolkit", "token_count": 1169 }
886
# news_blocks_ui [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A Flutter package that contains UI components for news blocks. [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
news_toolkit/flutter_news_example/packages/news_blocks_ui/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/README.md", "repo_id": "news_toolkit", "token_count": 173 }
887
export 'newsletter_container.dart'; export 'newsletter_sign_up.dart'; export 'newsletter_succeeded.dart';
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/index.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/index.dart", "repo_id": "news_toolkit", "token_count": 38 }
888
import 'dart:math' as math; import 'package:app_ui/app_ui.dart'; import 'package:flutter/rendering.dart'; /// Custom GridDelegate that allows to use [HeaderGridTileLayout]. /// This way, the grid can have the first element as a header. class CustomMaxCrossAxisDelegate extends SliverGridDelegateWithMaxCrossAxisExtent { /// Creates a custom delegate that makes grid layouts with tiles /// that have a maximum cross-axis extent. const CustomMaxCrossAxisDelegate({ required super.maxCrossAxisExtent, super.mainAxisSpacing = 0.0, super.crossAxisSpacing = 0.0, super.childAspectRatio = 1.0, super.mainAxisExtent, }); @override SliverGridLayout getLayout(SliverConstraints constraints) { // Code copied from [SliverGridDelegateWithMaxCrossAxisExtent]. var crossAxisCount = (constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing)) .ceil(); // Ensure a minimum count of 1, can be zero and result in an infinite extent // below when the window size is 0. crossAxisCount = math.max(1, crossAxisCount); final double usableCrossAxisExtent = math.max( 0, constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1), ); final childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount; final childMainAxisExtent = mainAxisExtent ?? childCrossAxisExtent / childAspectRatio; return HeaderGridTileLayout( crossAxisCount: crossAxisCount, mainAxisStride: childMainAxisExtent + mainAxisSpacing, crossAxisStride: childCrossAxisExtent + crossAxisSpacing, childMainAxisExtent: childMainAxisExtent, childCrossAxisExtent: childCrossAxisExtent, reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection), ); } } /// Custom [SliverGridRegularTileLayout] that creates a different /// [SliverGridGeometry] for the first element of the grid. class HeaderGridTileLayout extends SliverGridRegularTileLayout { /// Creates a custom layout that makes grid layouts with tiles /// that have a maximum cross-axis extent. const HeaderGridTileLayout({ required super.crossAxisCount, required super.mainAxisStride, required super.crossAxisStride, required super.childMainAxisExtent, required super.childCrossAxisExtent, required super.reverseCrossAxis, }); @override // ignore: hash_and_equals bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is HeaderGridTileLayout && other.childCrossAxisExtent == childCrossAxisExtent && other.mainAxisStride == mainAxisStride && other.crossAxisStride == crossAxisStride && other.childMainAxisExtent == childMainAxisExtent && other.childCrossAxisExtent == childCrossAxisExtent && other.reverseCrossAxis == reverseCrossAxis; } @override int getMinChildIndexForScrollOffset(double scrollOffset) { final result = super.getMinChildIndexForScrollOffset(scrollOffset); return (result > 0) ? result - 1 : result; } @override SliverGridGeometry getGeometryForChildIndex(int index) { final isFirstElement = index == 0; // We want to handle how to show the first element as a header that occupies // the full number of columns. if (isFirstElement) { return SliverGridGeometry( scrollOffset: (index ~/ crossAxisCount) * mainAxisStride, crossAxisOffset: (index % crossAxisCount) * crossAxisStride, mainAxisExtent: (2 * mainAxisStride) - AppSpacing.md, crossAxisExtent: 2 * crossAxisStride - AppSpacing.md, ); } else { return SliverGridGeometry( scrollOffset: (((index + 1) ~/ crossAxisCount) * mainAxisStride) + childMainAxisExtent, crossAxisOffset: ((index + 1) % crossAxisCount) * crossAxisStride, mainAxisExtent: mainAxisStride, crossAxisExtent: childCrossAxisExtent, ); } } @override double computeMaxScrollOffset(int childCount) { // Since the first element is taking up twice the // width and height of the other grid elements, // for computing max scroll offset it can be assumed // as if there was 3 more children on the grid, so // every child after that position must move below, // affecting the max scroll offset. return super.computeMaxScrollOffset(childCount + 3); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/sliver_grid_custom_delegate.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/sliver_grid_custom_delegate.dart", "repo_id": "news_toolkit", "token_count": 1597 }
889
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template post_content} /// A post widget displaying post content. /// {@endtemplate} class PostContent extends StatelessWidget { /// {@macro post_content} const PostContent({ required this.title, this.publishedAt, this.categoryName, this.description, this.author, this.onShare, this.isPremium = false, this.isContentOverlaid = false, this.isVideoContent = false, this.premiumText = '', super.key, }); /// Title of post. final String title; /// The date when this post was published. final DateTime? publishedAt; /// Category of post. final String? categoryName; /// Description of post. final String? description; /// Author of post. final String? author; /// Called when the share button is tapped. final VoidCallback? onShare; /// Whether this post requires a premium subscription to access. /// /// Defaults to false. final bool isPremium; /// Whether content is displayed overlaid. /// /// Defaults to false. final bool isContentOverlaid; /// Text displayed when post is premium content. /// /// Defaults to empty string. final String premiumText; /// Whether content is a part of a video article. /// /// Defaults to false. final bool isVideoContent; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final category = categoryName; final hasCategory = category != null && category.isNotEmpty; return Padding( padding: isContentOverlaid ? const EdgeInsets.symmetric(horizontal: AppSpacing.lg) : EdgeInsets.zero, child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ const SizedBox(height: AppSpacing.lg), Row( children: [ if (hasCategory) PostContentCategory( categoryName: categoryName!, isContentOverlaid: isContentOverlaid, isVideoContent: isVideoContent, ), if (isPremium) ...[ if (hasCategory) const SizedBox(width: AppSpacing.sm), PostContentPremiumCategory( premiumText: premiumText, isVideoContent: isVideoContent, ), ] ], ), Text( title, style: textTheme.displaySmall?.copyWith( color: isContentOverlaid || isVideoContent ? AppColors.highEmphasisPrimary : AppColors.highEmphasisSurface, ), maxLines: 3, overflow: TextOverflow.ellipsis, ), if (publishedAt != null || author != null || onShare != null) ...[ const SizedBox(height: AppSpacing.md), PostFooter( publishedAt: publishedAt, author: author, onShare: onShare, isContentOverlaid: isContentOverlaid, ), ], const SizedBox(height: AppSpacing.xlg + AppSpacing.sm), ], ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_content.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_content.dart", "repo_id": "news_toolkit", "token_count": 1405 }
890
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/src/banner_ad.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../helpers/helpers.dart'; void main() { group('BannerAd', () { testWidgets('renders BannerAdContainer', (tester) async { const block = BannerAdBlock(size: BannerAdSize.normal); await tester.pumpApp( BannerAd( block: block, adFailedToLoadTitle: 'adFailedToLoadTitle', ), ); expect( find.byWidgetPredicate( (widget) => widget is BannerAdContainer && widget.size == block.size, ), findsOneWidget, ); }); testWidgets('renders BannerAdContent', (tester) async { const block = BannerAdBlock(size: BannerAdSize.normal); await tester.pumpApp( BannerAd( block: block, adFailedToLoadTitle: 'adFailedToLoadTitle', ), ); expect( find.byWidgetPredicate( (widget) => widget is BannerAdContent && widget.size == block.size, ), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/banner_ad_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/banner_ad_test.dart", "repo_id": "news_toolkit", "token_count": 539 }
891
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import '../helpers/helpers.dart'; void main() { group('TextParagraph', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly', (tester) async { final widget = Center( child: TextParagraph( block: TextParagraphBlock(text: 'text Paragraph'), ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextParagraph), matchesGoldenFile('text_paragraph.png'), ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_paragraph_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_paragraph_test.dart", "repo_id": "news_toolkit", "token_count": 294 }
892
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('PostFooter', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly', (tester) async { await tester.pumpApp( PostFooter(), ); await expectLater( find.byType(PostFooter), matchesGoldenFile('post_footer.png'), ); }); testWidgets('renders correctly with author', (tester) async { await tester.pumpApp( PostFooter(author: 'Author'), ); await expectLater( find.byType(PostFooter), matchesGoldenFile('post_footer_with_author.png'), ); }); testWidgets('renders correctly with publishedAt date', (tester) async { await tester.pumpApp( PostFooter(publishedAt: DateTime(2022, 5, 9)), ); await expectLater( find.byType(PostFooter), matchesGoldenFile('post_footer_with_published_at.png'), ); }); testWidgets('renders correctly with author and publishedAt date', (tester) async { await tester.pumpApp( PostFooter(author: 'Author', publishedAt: DateTime(2022, 5, 9)), ); await expectLater( find.byType(PostFooter), matchesGoldenFile('post_footer_with_author_and_published_at.png'), ); }); testWidgets('onShare is called when tapped', (tester) async { var onShareTapped = 0; await tester.pumpApp( PostFooter( publishedAt: DateTime(2022, 5, 9), onShare: () => onShareTapped++, ), ); await tester.tap(find.byType(IconButton)); expect(onShareTapped, equals(1)); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_footer_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_footer_test.dart", "repo_id": "news_toolkit", "token_count": 800 }
893
# firebase_notifications_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A Firebase Cloud Messaging notifications client.
news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/README.md", "repo_id": "news_toolkit", "token_count": 67 }
894
export 'src/one_signal_notifications_client.dart';
news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/lib/one_signal_notifications_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/lib/one_signal_notifications_client.dart", "repo_id": "news_toolkit", "token_count": 18 }
895
export 'src/package_info_client.dart';
news_toolkit/flutter_news_example/packages/package_info_client/lib/package_info_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/package_info_client/lib/package_info_client.dart", "repo_id": "news_toolkit", "token_count": 14 }
896
import 'dart:async'; import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'package:purchase_client/src/products.dart'; /// Extension on [PurchaseDetails] enabling copyWith. @visibleForTesting extension PurchaseDetailsCopyWith on PurchaseDetails { /// Returns a copy of the current PurchaseDetails with the given parameters. PurchaseDetails copyWith({ String? purchaseID, String? productID, PurchaseVerificationData? verificationData, String? transactionDate, PurchaseStatus? status, bool? pendingCompletePurchase, }) => PurchaseDetails( purchaseID: purchaseID ?? this.purchaseID, productID: productID ?? this.productID, verificationData: verificationData ?? this.verificationData, transactionDate: transactionDate ?? this.transactionDate, status: status ?? this.status, )..pendingCompletePurchase = pendingCompletePurchase ?? this.pendingCompletePurchase; } /// {@template purchase_client} /// A PurchaseClient stubbing InAppPurchase implementation. /// /// For real implementation, see [InAppPurchase]. /// {@endtemplate} class PurchaseClient implements InAppPurchase { /// {@macro purchase_client} PurchaseClient(); /// The duration after which [isAvailable] completes with `true`. static const _isAvailableDelay = Duration(milliseconds: 100); @override Stream<List<PurchaseDetails>> get purchaseStream => _purchaseStream.stream; final StreamController<List<PurchaseDetails>> _purchaseStream = StreamController<List<PurchaseDetails>>.broadcast(); /// This method is not implemented as the scope of this template /// is limited to purchasing subscriptions which are non-consumables. @override Future<bool> buyConsumable({ required PurchaseParam purchaseParam, bool autoConsume = true, }) => throw UnimplementedError(); @override Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) async { final purchaseDetails = PurchaseDetails( productID: purchaseParam.productDetails.id, verificationData: PurchaseVerificationData( localVerificationData: purchaseParam.applicationUserName!, serverVerificationData: purchaseParam.applicationUserName!, source: 'local', ), status: PurchaseStatus.pending, transactionDate: clock.now().millisecondsSinceEpoch.toString(), ); _purchaseStream ..add([purchaseDetails]) ..add([ purchaseDetails.copyWith( status: PurchaseStatus.purchased, pendingCompletePurchase: true, ), ]); return true; } @override Future<void> completePurchase(PurchaseDetails purchase) async { _purchaseStream.add([purchase.copyWith(pendingCompletePurchase: false)]); } @override T getPlatformAddition<T extends InAppPurchasePlatformAddition?>() { throw UnimplementedError(); } @override Future<bool> isAvailable() async { return Future<bool>.delayed(_isAvailableDelay, () => true); } @override Future<ProductDetailsResponse> queryProductDetails(Set<String> identifiers) { final notFoundIdentifiers = identifiers .where((identifier) => !availableProducts.containsKey(identifier)) .toList(); return Future.value( ProductDetailsResponse( productDetails: identifiers .map((identifier) => availableProducts[identifier]) .whereType<ProductDetails>() .toList(), notFoundIDs: notFoundIdentifiers, ), ); } @override Future<void> restorePurchases({String? applicationUserName}) { // No purchases are restored // in this stubbed implementation of InAppPurchase. return Future.value(); } }
news_toolkit/flutter_news_example/packages/purchase_client/lib/src/purchase_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/purchase_client/lib/src/purchase_client.dart", "repo_id": "news_toolkit", "token_count": 1262 }
897
import 'package:authentication_client/authentication_client.dart'; import 'package:flutter_news_example_api/client.dart'; /// {@template user} /// User model represents the current user with subscription plan. /// {@endtemplate} class User extends AuthenticationUser { /// {@macro user} const User({ required this.subscriptionPlan, required super.id, super.email, super.name, super.photo, super.isNewUser, }); /// Converts [AuthenticationUser] to [User] with [SubscriptionPlan]. factory User.fromAuthenticationUser({ required AuthenticationUser authenticationUser, required SubscriptionPlan subscriptionPlan, }) => User( email: authenticationUser.email, id: authenticationUser.id, name: authenticationUser.name, photo: authenticationUser.photo, isNewUser: authenticationUser.isNewUser, subscriptionPlan: subscriptionPlan, ); /// Whether the current user is anonymous. @override bool get isAnonymous => this == anonymous; /// Anonymous user which represents an unauthenticated user. static const User anonymous = User( id: '', subscriptionPlan: SubscriptionPlan.none, ); /// The current user's subscription plan. final SubscriptionPlan subscriptionPlan; }
news_toolkit/flutter_news_example/packages/user_repository/lib/src/models/user.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/user_repository/lib/src/models/user.dart", "repo_id": "news_toolkit", "token_count": 398 }
898
import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('AnalyticsState', () { group('AnalyticsInitial', () { test('supports value comparisons', () { expect(AnalyticsInitial(), AnalyticsInitial()); }); }); }); }
news_toolkit/flutter_news_example/test/analytics/bloc/analytics_state_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/analytics/bloc/analytics_state_test.dart", "repo_id": "news_toolkit", "token_count": 116 }
899
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('ArticleThemeOverride', () { testWidgets('renders ContentThemeOverrideBuilder', (tester) async { await tester.pumpApp( ArticleThemeOverride( isVideoArticle: false, child: SizedBox(), ), ); expect(find.byType(ContentThemeOverrideBuilder), findsOneWidget); }); testWidgets('provides ArticleThemeColors', (tester) async { late ArticleThemeColors colors; await tester.pumpApp( ArticleThemeOverride( isVideoArticle: false, child: Builder( builder: (context) { colors = Theme.of(context).extension<ArticleThemeColors>()!; return SizedBox(); }, ), ), ); expect(colors, isNotNull); }); testWidgets('renders child', (tester) async { final childKey = Key('__child__'); await tester.pumpApp( ArticleThemeOverride( isVideoArticle: false, child: SizedBox(key: childKey), ), ); expect(find.byKey(childKey), findsOneWidget); }); }); group('ArticleThemeColors', () { test('supports value comparisons', () { expect( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ), equals( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ), ), ); }); group('copyWith', () { test( 'returns same object ' 'when no properties are passed', () { expect( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ).copyWith(), equals( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ), ), ); }); test( 'returns object with updated captionNormal ' 'when captionNormal is passed', () { expect( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ).copyWith(captionNormal: Colors.white), equals( ArticleThemeColors( captionNormal: Colors.white, captionLight: Colors.black, ), ), ); }); test( 'returns object with updated captionLight ' 'when captionLight is passed', () { expect( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ).copyWith(captionLight: Colors.white), equals( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.white, ), ), ); }); }); group('lerp', () { test( 'returns same object ' 'when other is null', () { expect( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ).lerp(null, 0.5), equals( ArticleThemeColors( captionNormal: Colors.black, captionLight: Colors.black, ), ), ); }); test( 'returns object ' 'with interpolated colors ' 'when other is passed', () { const colorA = Colors.black; const colorB = Colors.white; const t = 0.5; expect( ArticleThemeColors( captionNormal: colorA, captionLight: colorA, ).lerp( ArticleThemeColors( captionNormal: colorB, captionLight: colorB, ), t, ), equals( ArticleThemeColors( captionNormal: Color.lerp(colorA, colorB, 0.5)!, captionLight: Color.lerp(colorA, colorB, 0.5)!, ), ), ); }); }); }); }
news_toolkit/flutter_news_example/test/article/widgets/article_theme_override_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_theme_override_test.dart", "repo_id": "news_toolkit", "token_count": 2178 }
900
import 'package:flutter_test/flutter_test.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:mocktail/mocktail.dart'; class MockStorage extends Mock implements Storage {} late Storage hydratedStorage; void initMockHydratedStorage() { TestWidgetsFlutterBinding.ensureInitialized(); hydratedStorage = MockStorage(); when( () => hydratedStorage.write(any(), any<dynamic>()), ).thenAnswer((_) async {}); HydratedBloc.storage = hydratedStorage; }
news_toolkit/flutter_news_example/test/helpers/mock_hydrated_storage.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/helpers/mock_hydrated_storage.dart", "repo_id": "news_toolkit", "token_count": 158 }
901
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_news_example/magic_link_prompt/magic_link_prompt.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import '../../helpers/helpers.dart'; void main() { const testEmail = '[email protected]'; const magicLinkPromptCloseIconKey = Key('magicLinkPrompt_closeIcon'); group('MagicLinkPromptPage', () { test('has a route', () { expect( MagicLinkPromptPage.route(email: testEmail), isA<MaterialPageRoute<void>>(), ); }); testWidgets('renders a MagicLinkPromptView', (tester) async { await tester.pumpApp( const MagicLinkPromptPage(email: testEmail), ); expect(find.byType(MagicLinkPromptView), findsOneWidget); }); testWidgets('router returns a valid navigation route', (tester) async { await tester.pumpApp( Scaffold( body: Builder( builder: (context) { return ElevatedButton( onPressed: () { Navigator.of(context) .push<void>(MagicLinkPromptPage.route(email: testEmail)); }, child: const Text('Tap me'), ); }, ), ), ); await tester.tap(find.text('Tap me')); await tester.pumpAndSettle(); expect(find.byType(MagicLinkPromptPage), findsOneWidget); }); group('navigates', () { testWidgets('back when pressed on close icon', (tester) async { final navigator = MockNavigator(); when(() => navigator.popUntil(any())).thenAnswer((_) async {}); await tester.pumpApp( const MagicLinkPromptPage(email: testEmail), navigator: navigator, ); await tester.tap(find.byKey(magicLinkPromptCloseIconKey)); await tester.pumpAndSettle(); verify(() => navigator.popUntil(any())).called(1); }); testWidgets('back when leading button is pressed.', (tester) async { final navigator = MockNavigator(); when(() => navigator.popUntil(any())).thenAnswer((_) async {}); await tester.pumpApp( const MagicLinkPromptPage(email: testEmail), navigator: navigator, ); await tester.tap(find.byKey(magicLinkPromptCloseIconKey)); await tester.pumpAndSettle(); verify(() => navigator.popUntil(any())).called(1); }); }); }); }
news_toolkit/flutter_news_example/test/magic_link_prompt/view/magic_link_prompt_page_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/magic_link_prompt/view/magic_link_prompt_page_test.dart", "repo_id": "news_toolkit", "token_count": 1111 }
902
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_news_example/notification_preferences/notification_preferences.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_repository/news_repository.dart'; import 'package:notifications_repository/notifications_repository.dart'; import '../../helpers/helpers.dart'; class MockNotificationPreferencesBloc extends Mock implements NotificationPreferencesBloc {} class MockNotificationPreferencesRepository extends Mock implements NotificationsRepository {} class MockCategoriesBloc extends Mock implements CategoriesBloc {} void main() { final NotificationPreferencesBloc bloc = MockNotificationPreferencesBloc(); final NotificationsRepository repository = MockNotificationPreferencesRepository(); final CategoriesBloc categoryBloc = MockCategoriesBloc(); group('NotificationPreferencesPage', () { const populatedState = CategoriesState( status: CategoriesStatus.populated, categories: [Category.business, Category.entertainment], ); test('has a route', () { expect( NotificationPreferencesPage.route(), isA<MaterialPageRoute<void>>(), ); }); testWidgets('renders NotificationPreferencesView', (tester) async { whenListen( categoryBloc, Stream.value(populatedState), initialState: populatedState, ); await tester.pumpApp( RepositoryProvider.value( value: repository, child: BlocProvider.value( value: categoryBloc, child: const NotificationPreferencesPage(), ), ), ); expect(find.byType(NotificationPreferencesView), findsOneWidget); }); }); group('NotificationPreferencesView', () { testWidgets('renders AppSwitch with state value', (tester) async { const notificationState = NotificationPreferencesState( selectedCategories: {Category.business}, status: NotificationPreferencesStatus.success, categories: { Category.business, Category.entertainment, }, ); whenListen( bloc, Stream.value(notificationState), initialState: notificationState, ); await tester.pumpApp( BlocProvider.value( value: bloc, child: const NotificationPreferencesView(), ), ); final appSwitch = find.byType(AppSwitch).first; final appSwitchWidget = tester.firstWidget<AppSwitch>(appSwitch); expect(appSwitchWidget.value, true); final appSwitch2 = find.byType(AppSwitch).last; final appSwitchWidget2 = tester.firstWidget<AppSwitch>(appSwitch2); expect(appSwitchWidget2.value, false); }); testWidgets( 'adds CategoriesPreferenceToggled to NotificationPreferencesBloc ' 'on AppSwitch toggled', (tester) async { const notificationState = NotificationPreferencesState( selectedCategories: {Category.business}, status: NotificationPreferencesStatus.success, categories: {Category.business}, ); whenListen( bloc, Stream.value(notificationState), initialState: notificationState, ); await tester.pumpApp( BlocProvider.value( value: bloc, child: const NotificationPreferencesView(), ), ); await tester.tap(find.byType(AppSwitch)); verify( () => bloc.add( CategoriesPreferenceToggled(category: Category.business), ), ).called(1); }); }); }
news_toolkit/flutter_news_example/test/notification_preferences/view/notification_preferences_page_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/notification_preferences/view/notification_preferences_page_test.dart", "repo_id": "news_toolkit", "token_count": 1461 }
903
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; 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'; import 'package:mocktail/mocktail.dart'; import 'package:user_repository/user_repository.dart'; import '../../../app/view/app_test.dart'; class MockInAppPurchaseRepository extends Mock implements InAppPurchaseRepository {} void main() { group('SubscriptionBloc', () { late InAppPurchaseRepository inAppPurchaseRepository; late UserRepository userRepository; final subscription = Subscription( id: 'dd339fda-33e9-49d0-9eb5-0ccb77eb760f', name: SubscriptionPlan.none, cost: SubscriptionCost( annual: 16200, monthly: 1499, ), benefits: const [ 'test benefits', 'another test benefits', ], ); setUp(() { inAppPurchaseRepository = MockInAppPurchaseRepository(); userRepository = MockUserRepository(); when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer((_) => Stream.empty()); }); group('on SubscriptionsRequested ', () { blocTest<SubscriptionsBloc, SubscriptionsState>( 'calls InAppPurchaseRepository.fetchSubscriptions ' 'and emits state with fetched subscriptions', setUp: () => when( inAppPurchaseRepository.fetchSubscriptions, ).thenAnswer( (_) async => [subscription], ), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(SubscriptionsRequested()), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( subscriptions: [subscription], ), ], ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds error to state if fetchSubscriptions throws', setUp: () => when( inAppPurchaseRepository.fetchSubscriptions, ).thenThrow(Exception()), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(SubscriptionsRequested()), expect: () => <SubscriptionsState>[], errors: () => [isA<Exception>()], ); }); group('on SubscriptionPurchaseRequested ', () { blocTest<SubscriptionsBloc, SubscriptionsState>( 'calls InAppPurchaseRepository.purchase ' 'and emits pending state', setUp: () => when( () => inAppPurchaseRepository.purchase( subscription: subscription, ), ).thenAnswer( (_) async {}, ), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(SubscriptionPurchaseRequested(subscription: subscription)), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), ], ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds error to state if fetchSubscriptions throws', setUp: () => when( () => inAppPurchaseRepository.purchase( subscription: subscription, ), ).thenThrow(Exception()), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(SubscriptionPurchaseRequested(subscription: subscription)), expect: () => [ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), ], errors: () => [isA<Exception>()], ); }); group('when InAppPurchaseRepository.purchaseUpdate', () { blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds PurchasePurchased ' 'changes purchaseStatus to pending', seed: () => SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.none, ), setUp: () => when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer( (_) => Stream.value( PurchasePurchased( subscription: subscription, ), ), ), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), ], ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds PurchaseDelivered ' 'changes purchaseStatus to completed', seed: () => SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), setUp: () { when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer( (_) => Stream.value( PurchaseDelivered( subscription: subscription, ), ), ); when( userRepository.updateSubscriptionPlan, ).thenAnswer((_) async {}); }, build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.completed, ), ], verify: (_) => verify(userRepository.updateSubscriptionPlan).called(1), ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds PurchaseDelivered ' 'changes purchaseStatus to completed', seed: () => SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), setUp: () => when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer( (_) => Stream.value( PurchaseFailed( failure: InternalInAppPurchaseFailure(subscription), ), ), ), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.failed, ), ], ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'adds PurchaseDelivered ' 'changes purchaseStatus to completed', seed: () => SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.pending, ), setUp: () => when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer( (_) => Stream.value( PurchaseCanceled(), ), ), build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), expect: () => <SubscriptionsState>[ SubscriptionsState.initial().copyWith( purchaseStatus: PurchaseStatus.failed, ), ], ); }); group('close', () { late StreamController<SubscriptionPlan> currentSubscriptionPlanController; late StreamController<PurchaseUpdate> subscriptionPurchaseUpdateController; setUp(() { currentSubscriptionPlanController = StreamController<SubscriptionPlan>(); subscriptionPurchaseUpdateController = StreamController<PurchaseUpdate>(); when(() => inAppPurchaseRepository.purchaseUpdate) .thenAnswer((_) => subscriptionPurchaseUpdateController.stream); }); blocTest<SubscriptionsBloc, SubscriptionsState>( 'cancels InAppPurchaseRepository.currentSubscriptionPlan subscription', build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), tearDown: () => expect(currentSubscriptionPlanController.hasListener, isFalse), ); blocTest<SubscriptionsBloc, SubscriptionsState>( 'cancels InAppPurchaseRepository.purchaseUpdate subscription', build: () => SubscriptionsBloc( inAppPurchaseRepository: inAppPurchaseRepository, userRepository: userRepository, ), tearDown: () => expect(subscriptionPurchaseUpdateController.hasListener, isFalse), ); }); }); }
news_toolkit/flutter_news_example/test/subscriptions/dialog/bloc/subscriptions_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/subscriptions/dialog/bloc/subscriptions_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 3911 }
904
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/notification_preferences/notification_preferences.dart'; import 'package:flutter_news_example/subscriptions/subscriptions.dart'; import 'package:flutter_news_example/terms_of_service/terms_of_service.dart'; import 'package:flutter_news_example/user_profile/user_profile.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:user_repository/user_repository.dart'; import '../../helpers/helpers.dart'; class MockUserProfileBloc extends MockBloc<UserProfileEvent, UserProfileState> implements UserProfileBloc {} class MockAnalyticsBloc extends MockBloc<AnalyticsEvent, AnalyticsState> implements AnalyticsBloc {} class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {} void main() { const termsOfServiceItemKey = Key('userProfilePage_termsOfServiceItem'); group('UserProfilePage', () { test('has a route', () { expect(UserProfilePage.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('renders UserProfileView', (tester) async { await tester.pumpApp(UserProfilePage()); expect(find.byType(UserProfileView), findsOneWidget); }); group('UserProfileView', () { late InAppPurchaseRepository inAppPurchaseRepository; late UserProfileBloc userProfileBloc; late AnalyticsBloc analyticsBloc; late AppBloc appBloc; final user = User( id: '1', email: 'email', subscriptionPlan: SubscriptionPlan.none, ); const notificationsEnabled = true; setUp(() { inAppPurchaseRepository = MockInAppPurchaseRepository(); userProfileBloc = MockUserProfileBloc(); analyticsBloc = MockAnalyticsBloc(); appBloc = MockAppBloc(); final initialState = UserProfileState.initial().copyWith( user: user, notificationsEnabled: notificationsEnabled, ); whenListen( userProfileBloc, Stream.value(initialState), initialState: initialState, ); whenListen( appBloc, Stream.fromIterable( <AppState>[AppState.unauthenticated()], ), initialState: AppState.authenticated(user), ); }); testWidgets( 'adds FetchNotificationsEnabled to UserProfileBloc ' 'when initialized and each time the app is resumed', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); verify( () => userProfileBloc.add(FetchNotificationsEnabled()), ).called(1); tester.binding .handleAppLifecycleStateChanged(AppLifecycleState.resumed); verify( () => userProfileBloc.add(FetchNotificationsEnabled()), ).called(1); tester.binding ..handleAppLifecycleStateChanged(AppLifecycleState.inactive) ..handleAppLifecycleStateChanged(AppLifecycleState.resumed); verify( () => userProfileBloc.add(FetchNotificationsEnabled()), ).called(1); }); testWidgets( 'navigates back ' 'when app back button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); await tester.tap(find.byType(AppBackButton)); await tester.pumpAndSettle(); expect(find.byType(UserProfileView), findsNothing); }); testWidgets( 'navigates back ' 'when user is unauthenticated', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), appBloc: appBloc, ); await tester.pumpAndSettle(); expect(find.byType(UserProfileView), findsNothing); }); testWidgets( 'adds TrackAnalyticsEvent to AnalyticsBloc ' 'with PushNotificationSubscriptionEvent ' 'when status is togglingNotificationsSucceeded ' 'and notificationsEnabled is true', (tester) async { whenListen( userProfileBloc, Stream.fromIterable([ UserProfileState.initial(), UserProfileState( user: User.anonymous, notificationsEnabled: true, status: UserProfileStatus.togglingNotificationsSucceeded, ), ]), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: userProfileBloc), BlocProvider.value(value: analyticsBloc), ], child: UserProfileView(), ), ); verify( () => analyticsBloc.add( TrackAnalyticsEvent(PushNotificationSubscriptionEvent()), ), ).called(1); }); testWidgets('renders UserProfileTitle', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byType(UserProfileTitle), findsOneWidget, ); }); testWidgets('renders user email', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is UserProfileItem && widget.title == user.email, ), findsOneWidget, ); }); testWidgets( 'renders notifications item ' 'with trailing AppSwitch', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is UserProfileItem && widget.key == Key('userProfilePage_notificationsItem') && widget.trailing is AppSwitch, ), findsOneWidget, ); expect( find.byWidgetPredicate( (widget) => widget is AppSwitch && widget.value == notificationsEnabled, ), findsOneWidget, ); }); group( 'renders UserProfileSubscribeBox ' 'when isUserSubscribed is false', () { testWidgets('correctly', (tester) async { whenListen( appBloc, Stream.fromIterable([ AppState.authenticated(user), ]), ); await tester.pumpApp( appBloc: appBloc, BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect(find.byType(UserProfileSubscribeBox), findsOneWidget); }); testWidgets('opens PurchaseSubscriptionDialog when tapped', (tester) async { whenListen( appBloc, Stream.fromIterable([ AppState.authenticated(user), ]), ); when(() => inAppPurchaseRepository.purchaseUpdate).thenAnswer( (_) => const Stream.empty(), ); when(inAppPurchaseRepository.fetchSubscriptions).thenAnswer( (invocation) async => [], ); await tester.pumpApp( inAppPurchaseRepository: inAppPurchaseRepository, appBloc: appBloc, BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); final subscriptionButton = find.byKey(Key('userProfileSubscribeBox_appButton')); await tester.scrollUntilVisible(subscriptionButton, -50); await tester.tap(subscriptionButton); await tester.pump(); expect( find.byType(PurchaseSubscriptionDialog), findsOneWidget, ); }); }); testWidgets( 'renders notification preferences item ' 'with trailing Icon', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is UserProfileItem && widget.key == Key('userProfilePage_notificationPreferencesItem') && widget.trailing is Icon, ), findsOneWidget, ); }); testWidgets('renders terms of use and privacy policy item', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is UserProfileItem && widget.key == Key('userProfilePage_termsOfServiceItem'), ), findsOneWidget, ); }); testWidgets('renders about item', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is UserProfileItem && widget.key == Key('userProfilePage_aboutItem'), ), findsOneWidget, ); }); testWidgets( 'adds ToggleNotifications to UserProfileBloc ' 'when notifications item trailing is tapped', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); await tester.tap(find.byType(AppSwitch)); verify(() => userProfileBloc.add(ToggleNotifications())).called(1); }); testWidgets( 'does nothing ' 'when notification preferences item trailing is tapped', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); final preferencesItem = find.byKey( Key('userProfilePage_notificationPreferencesItem_trailing'), ); await tester.ensureVisible(preferencesItem); await tester.tap(preferencesItem); await tester.pumpAndSettle(); }); group('UserProfileItem', () { testWidgets('renders ListTile', (tester) async { await tester.pumpApp( UserProfileItem( title: 'title', ), ); expect(find.widgetWithText(ListTile, 'title'), findsOneWidget); }); testWidgets('renders leading', (tester) async { const leadingKey = Key('__leading__'); await tester.pumpApp( UserProfileItem( title: 'title', leading: SizedBox(key: leadingKey), ), ); expect(find.byKey(leadingKey), findsOneWidget); }); testWidgets('renders trailing', (tester) async { const trailingKey = Key('__trailing__'); await tester.pumpApp( UserProfileItem( title: 'title', trailing: SizedBox(key: trailingKey), ), ); expect(find.byKey(trailingKey), findsOneWidget); }); testWidgets('calls onTap when tapped', (tester) async { var tapped = false; await tester.pumpApp( UserProfileItem( title: 'title', onTap: () => tapped = true, ), ); await tester.tap(find.byType(UserProfileItem)); expect(tapped, isTrue); }); }); group('UserProfileLogoutButton', () { testWidgets('renders AppButton', (tester) async { await tester.pumpApp(UserProfileLogoutButton()); expect(find.byType(AppButton), findsOneWidget); }); testWidgets( 'adds AppLogoutRequested to AppBloc ' 'when tapped', (tester) async { await tester.pumpApp( UserProfileLogoutButton(), appBloc: appBloc, ); await tester.tap(find.byType(UserProfileLogoutButton)); verify(() => appBloc.add(AppLogoutRequested())).called(1); }); }); group('navigates', () { testWidgets('when tapped on Terms of User & Privacy Policy', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); final termsOfService = find.byKey(termsOfServiceItemKey); await tester.dragUntilVisible( termsOfService, find.byType(UserProfileView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.ensureVisible(termsOfService); await tester.tap(termsOfService); await tester.pumpAndSettle(); expect(find.byType(TermsOfServicePage), findsOneWidget); }); testWidgets( 'to ManageSubscriptionPage ' 'when isUserSubscribed is true and ' 'tapped on Manage Subscription', (tester) async { final subscribedUser = User( id: '1', email: 'email', subscriptionPlan: SubscriptionPlan.premium, ); whenListen( appBloc, Stream.fromIterable([AppState.authenticated(subscribedUser)]), ); await tester.pumpApp( appBloc: appBloc, BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); final subscriptionItem = find.byKey(Key('userProfilePage_subscriptionItem')); await tester.ensureVisible(subscriptionItem); await tester.tap(subscriptionItem); await tester.pumpAndSettle(); expect(find.byType(ManageSubscriptionPage), findsOneWidget); }); testWidgets( 'to NotificationPreferencesPage ' 'when tapped on NotificationPreferences', (tester) async { await tester.pumpApp( BlocProvider.value( value: userProfileBloc, child: UserProfileView(), ), ); final subscriptionItem = find.byKey( Key('userProfilePage_notificationPreferencesItem'), ); await tester.dragUntilVisible( subscriptionItem, find.byType(UserProfileView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.ensureVisible(subscriptionItem); await tester.tap(subscriptionItem); await tester.pumpAndSettle(); expect(find.byType(NotificationPreferencesPage), findsOneWidget); }); }); }); }); }
news_toolkit/flutter_news_example/test/user_profile/view/user_profile_page_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/user_profile/view/user_profile_page_test.dart", "repo_id": "news_toolkit", "token_count": 7712 }
905
ba393198430278b6595976de84fe170f553cc728
packages/.ci/flutter_stable.version/0
{ "file_path": "packages/.ci/flutter_stable.version", "repo_id": "packages", "token_count": 18 }
906
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh # Does a sanity check that packages pass analysis with the lowest possible # versions of all dependencies. This is to catch cases where we add use of # new APIs but forget to update minimum versions of dependencies to where # those APIs are introduced. - name: analyze - downgraded script: .ci/scripts/tool_runner.sh args: ["analyze", "--downgrade", "--custom-analysis=script/configs/custom_analysis.yaml"]
packages/.ci/targets/analyze_downgraded.yaml/0
{ "file_path": "packages/.ci/targets/analyze_downgraded.yaml", "repo_id": "packages", "token_count": 142 }
907
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: update pods repo script: .ci/scripts/update_pods.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: Swift format script: .ci/scripts/tool_runner.sh # Non-Swift languages are formatted on Linux builders. # Skip them on Mac builder to avoid duplication. args: ["format", "--fail-on-change", "--no-dart", "--no-clang-format", "--no-kotlin", "--no-java" ] always: true - name: validate iOS and macOS podspecs script: .ci/scripts/tool_runner.sh args: ["podspec-check"] always: true
packages/.ci/targets/macos_repo_checks.yaml/0
{ "file_path": "packages/.ci/targets/macos_repo_checks.yaml", "repo_id": "packages", "token_count": 254 }
908
# Below is a list of Flutter team members who are suggested reviewers # for contributions to packages in this repository. # # These names are just suggestions. It is fine to have your changes # reviewed by someone else. packages/animations/** @goderbauer packages/camera/** @bparrishMines packages/cross_file/** @ditman packages/css_colors/** @stuartmorgan packages/dynamic_layouts/** @Piinks packages/extension_google_sign_in_as_googleapis_auth/** @ditman packages/file_selector/** @stuartmorgan packages/flutter_adaptive_scaffold/** @gspencergoog packages/flutter_image/** @stuartmorgan packages/flutter_lints/** @goderbauer packages/flutter_markdown/** @domesticmouse packages/flutter_migrate/** @stuartmorgan packages/flutter_template_images/** @stuartmorgan packages/go_router/** @chunhtai packages/go_router_builder/** @chunhtai packages/google_identity_services_web/** @ditman packages/google_maps_flutter/** @stuartmorgan packages/google_sign_in/** @stuartmorgan packages/image_picker/** @tarrinneal packages/in_app_purchase/** @bparrishMines packages/local_auth/** @stuartmorgan packages/metrics_center/** @keyonghan packages/multicast_dns/** @dnfield packages/palette_generator/** @gspencergoog packages/path_provider/** @stuartmorgan packages/pigeon/** @tarrinneal packages/platform/** @stuartmorgan packages/plugin_platform_interface/** @stuartmorgan packages/pointer_interceptor/** @ditman packages/process/** @stuartmorgan packages/quick_actions/** @bparrishMines packages/rfw/** @Hixie packages/shared_preferences/** @tarrinneal packages/standard_message_codec/** @jonahwilliams packages/two_dimensional_scrollables/** @Piinks packages/url_launcher/** @stuartmorgan packages/video_player/** @tarrinneal packages/web_benchmarks/** @yjbanov packages/webview_flutter/** @bparrishMines packages/xdg_directories/** @stuartmorgan third_party/packages/cupertino_icons/** @MitchellGoodwin # Plugin platform implementation rules. These should stay last, since the last # matching entry takes precedence. # - Web packages/camera/camera_web/** @ditman packages/file_selector/file_selector_web/** @ditman packages/google_maps_flutter/google_maps_flutter_web/** @ditman packages/google_sign_in/google_sign_in_web/** @ditman packages/image_picker/image_picker_for_web/** @ditman packages/pointer_interceptor/pointer_interceptor_web/** @ditman packages/shared_preferences/shared_preferences_web/** @ditman packages/url_launcher/url_launcher_web/** @ditman packages/video_player/video_player_web/** @ditman packages/webview_flutter/webview_flutter_web/** @ditman # - Android packages/camera/camera_android/** @camsim99 packages/camera/camera_android_camerax/** @camsim99 packages/espresso/** @reidbaker packages/file_selector/file_selector_android/** @gmackall packages/flutter_plugin_android_lifecycle/** @reidbaker packages/google_maps_flutter/google_maps_flutter_android/** @reidbaker packages/google_sign_in/google_sign_in_android/** @camsim99 packages/image_picker/image_picker_android/** @gmackall packages/in_app_purchase/in_app_purchase_android/** @gmackall packages/local_auth/local_auth_android/** @camsim99 packages/path_provider/path_provider_android/** @camsim99 packages/quick_actions/quick_actions_android/** @camsim99 packages/shared_preferences/shared_preferences_android/** @reidbaker packages/url_launcher/url_launcher_android/** @gmackall packages/video_player/video_player_android/** @camsim99 # Owned by ecosystem team for now during the wrapper evaluation. packages/webview_flutter/webview_flutter_android/** @bparrishMines # - iOS packages/camera/camera_avfoundation/** @hellohuanlin packages/file_selector/file_selector_ios/** @jmagman packages/google_maps_flutter/google_maps_flutter_ios/** @hellohuanlin packages/google_sign_in/google_sign_in_ios/** @vashworth packages/image_picker/image_picker_ios/** @vashworth packages/in_app_purchase/in_app_purchase_storekit/** @louisehsu packages/ios_platform_images/** @jmagman packages/local_auth/local_auth_darwin/** @louisehsu packages/path_provider/path_provider_foundation/** @jmagman packages/pigeon/**/ios/**/* @hellohuanlin packages/pointer_interceptor/pointer_interceptor_ios/** @ditman packages/quick_actions/quick_actions_ios/** @hellohuanlin packages/shared_preferences/shared_preferences_foundation/** @tarrinneal packages/url_launcher/url_launcher_ios/** @jmagman packages/video_player/video_player_avfoundation/** @hellohuanlin packages/webview_flutter/webview_flutter_wkwebview/** @hellohuanlin # - Linux packages/file_selector/file_selector_linux/** @cbracken packages/image_picker/image_picker_linux/** @cbracken packages/path_provider/path_provider_linux/** @cbracken packages/shared_preferences/shared_preferences_linux/** @cbracken packages/url_launcher/url_launcher_linux/** @cbracken # - macOS packages/file_selector/file_selector_macos/** @cbracken packages/image_picker/image_picker_macos/** @cbracken packages/url_launcher/url_launcher_macos/** @cbracken # - Windows packages/camera/camera_windows/** @cbracken packages/file_selector/file_selector_windows/** @cbracken packages/image_picker/image_picker_windows/** @cbracken packages/local_auth/local_auth_windows/** @cbracken packages/path_provider/path_provider_windows/** @cbracken packages/shared_preferences/shared_preferences_windows/** @cbracken packages/url_launcher/url_launcher_windows/** @cbracken
packages/CODEOWNERS/0
{ "file_path": "packages/CODEOWNERS", "repo_id": "packages", "token_count": 3572 }
909
# Example Catalog for package:animations. Run `flutter run --release` in this directory to launch the catalog on a device.
packages/packages/animations/example/README.md/0
{ "file_path": "packages/packages/animations/example/README.md", "repo_id": "packages", "token_count": 31 }
910
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/animations/example/android/gradle.properties/0
{ "file_path": "packages/packages/animations/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
911
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; /// The demo page for [SharedAxisPageTransitionsBuilder]. class SharedAxisTransitionDemo extends StatefulWidget { /// Creates the demo page for [SharedAxisPageTransitionsBuilder]. const SharedAxisTransitionDemo({super.key}); @override State<SharedAxisTransitionDemo> createState() { return _SharedAxisTransitionDemoState(); } } class _SharedAxisTransitionDemoState extends State<SharedAxisTransitionDemo> { SharedAxisTransitionType? _transitionType = SharedAxisTransitionType.horizontal; bool _isLoggedIn = false; void _updateTransitionType(SharedAxisTransitionType? newType) { setState(() { _transitionType = newType; }); } void _toggleLoginStatus() { setState(() { _isLoggedIn = !_isLoggedIn; }); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar(title: const Text('Shared axis')), body: SafeArea( child: Column( children: <Widget>[ Expanded( child: PageTransitionSwitcher( reverse: !_isLoggedIn, transitionBuilder: ( Widget child, Animation<double> animation, Animation<double> secondaryAnimation, ) { return SharedAxisTransition( animation: animation, secondaryAnimation: secondaryAnimation, transitionType: _transitionType!, child: child, ); }, child: _isLoggedIn ? _CoursePage() : _SignInPage(), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 15.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ TextButton( onPressed: _isLoggedIn ? _toggleLoginStatus : null, child: const Text('BACK'), ), ElevatedButton( onPressed: _isLoggedIn ? null : _toggleLoginStatus, child: const Text('NEXT'), ), ], ), ), const Divider(thickness: 2.0), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Radio<SharedAxisTransitionType>( value: SharedAxisTransitionType.horizontal, groupValue: _transitionType, onChanged: (SharedAxisTransitionType? newValue) { _updateTransitionType(newValue); }, ), const Text('X'), Radio<SharedAxisTransitionType>( value: SharedAxisTransitionType.vertical, groupValue: _transitionType, onChanged: (SharedAxisTransitionType? newValue) { _updateTransitionType(newValue); }, ), const Text('Y'), Radio<SharedAxisTransitionType>( value: SharedAxisTransitionType.scaled, groupValue: _transitionType, onChanged: (SharedAxisTransitionType? newValue) { _updateTransitionType(newValue); }, ), const Text('Z'), ], ), ], ), ), ); } } class _CoursePage extends StatelessWidget { @override Widget build(BuildContext context) { return ListView( children: <Widget>[ const Padding(padding: EdgeInsets.symmetric(vertical: 8.0)), Text( 'Streamling your courses', style: Theme.of(context).textTheme.headlineSmall, textAlign: TextAlign.center, ), const Padding(padding: EdgeInsets.symmetric(vertical: 5.0)), const Padding( padding: EdgeInsets.symmetric(horizontal: 10.0), child: Text( 'Bundled categories appear as groups in your feed. ' 'You can always change this later.', style: TextStyle( fontSize: 12.0, color: Colors.grey, ), textAlign: TextAlign.center, ), ), const _CourseSwitch(course: 'Arts & Crafts'), const _CourseSwitch(course: 'Business'), const _CourseSwitch(course: 'Illustration'), const _CourseSwitch(course: 'Design'), const _CourseSwitch(course: 'Culinary'), ], ); } } class _CourseSwitch extends StatefulWidget { const _CourseSwitch({ required this.course, }); final String course; @override _CourseSwitchState createState() => _CourseSwitchState(); } class _CourseSwitchState extends State<_CourseSwitch> { bool _value = true; @override Widget build(BuildContext context) { final String subtitle = _value ? 'Bundled' : 'Shown Individually'; return SwitchListTile( title: Text(widget.course), subtitle: Text(subtitle), value: _value, onChanged: (bool newValue) { setState(() { _value = newValue; }); }, ); } } class _SignInPage extends StatelessWidget { @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final double maxHeight = constraints.maxHeight; return Column( children: <Widget>[ Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 20)), Image.asset( 'assets/avatar_logo.png', width: 80, ), Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)), Text( 'Hi David Park', style: Theme.of(context).textTheme.headlineSmall, ), Padding(padding: EdgeInsets.symmetric(vertical: maxHeight / 50)), const Text( 'Sign in with your account', style: TextStyle( fontSize: 12.0, color: Colors.grey, ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Padding( padding: EdgeInsets.only( top: 40.0, left: 15.0, right: 15.0, bottom: 10.0, ), child: TextField( decoration: InputDecoration( suffixIcon: Icon( Icons.visibility, size: 20, color: Colors.black54, ), isDense: true, labelText: 'Email or phone number', border: OutlineInputBorder(), ), ), ), Padding( padding: const EdgeInsets.only(left: 10.0), child: TextButton( onPressed: () {}, child: const Text('FORGOT EMAIL?'), ), ), Padding( padding: const EdgeInsets.only(left: 10.0), child: TextButton( onPressed: () {}, child: const Text('CREATE ACCOUNT'), ), ), ], ), ], ); }, ); } }
packages/packages/animations/example/lib/shared_axis_transition.dart/0
{ "file_path": "packages/packages/animations/example/lib/shared_axis_transition.dart", "repo_id": "packages", "token_count": 4154 }
912
// 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_scale_transition.dart'; import 'package:animations/src/modal.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'FadeScaleTransitionConfiguration builds a new route', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder(builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return const _FlutterLogoModal(); }, ); }, child: const Icon(Icons.add), ), ); }), ), ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.byType(_FlutterLogoModal), findsOneWidget); }, ); testWidgets( 'FadeScaleTransitionConfiguration runs forward', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder(builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return _FlutterLogoModal(key: key); }, ); }, child: const Icon(Icons.add), ), ); }), ), ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); // Opacity duration: First 30% of 150ms, linear transition double topFadeTransitionOpacity = _getOpacity(key, tester); double topScale = _getScale(key, tester); expect(topFadeTransitionOpacity, 0.0); expect(topScale, 0.80); // 3/10 * 150ms = 45ms (total opacity animation duration) // 1/2 * 45ms = ~23ms elapsed for halfway point of opacity // animation await tester.pump(const Duration(milliseconds: 23)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // End of opacity animation await tester.pump(const Duration(milliseconds: 22)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 1.0); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // 100ms into the animation await tester.pump(const Duration(milliseconds: 55)); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // Get to the end of the animation await tester.pump(const Duration(milliseconds: 50)); topScale = _getScale(key, tester); expect(topScale, 1.0); await tester.pump(); expect(find.byType(_FlutterLogoModal), findsOneWidget); }, ); testWidgets( 'FadeScaleTransitionConfiguration runs forward', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder(builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return _FlutterLogoModal(key: key); }, ); }, child: const Icon(Icons.add), ), ); }), ), ), ); // Show the incoming modal and let it animate in fully. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); // Tap on modal barrier to start reverse animation. await tester.tapAt(Offset.zero); await tester.pump(); // Opacity duration: Linear transition throughout 75ms // No scale animations on exit transition. double topFadeTransitionOpacity = _getOpacity(key, tester); double topScale = _getScale(key, tester); expect(topFadeTransitionOpacity, 1.0); expect(topScale, 1.0); await tester.pump(const Duration(milliseconds: 25)); topFadeTransitionOpacity = _getOpacity(key, tester); topScale = _getScale(key, tester); expect(topFadeTransitionOpacity, closeTo(0.66, 0.05)); expect(topScale, 1.0); await tester.pump(const Duration(milliseconds: 25)); topFadeTransitionOpacity = _getOpacity(key, tester); topScale = _getScale(key, tester); expect(topFadeTransitionOpacity, closeTo(0.33, 0.05)); expect(topScale, 1.0); // End of opacity animation await tester.pump(const Duration(milliseconds: 25)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 0.0); topScale = _getScale(key, tester); expect(topScale, 1.0); await tester.pump(const Duration(milliseconds: 1)); expect(find.byType(_FlutterLogoModal), findsNothing); }, ); testWidgets( 'FadeScaleTransitionConfiguration does not jump when interrupted', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder(builder: (BuildContext context) { return Center( child: ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return _FlutterLogoModal(key: key); }, ); }, child: const Icon(Icons.add), ), ); }), ), ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); // Opacity duration: First 30% of 150ms, linear transition double topFadeTransitionOpacity = _getOpacity(key, tester); double topScale = _getScale(key, tester); expect(topFadeTransitionOpacity, 0.0); expect(topScale, 0.80); // 3/10 * 150ms = 45ms (total opacity animation duration) // End of opacity animation await tester.pump(const Duration(milliseconds: 45)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 1.0); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // 100ms into the animation await tester.pump(const Duration(milliseconds: 55)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 1.0); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // Start the reverse transition by interrupting the forwards // transition. await tester.tapAt(Offset.zero); await tester.pump(); // Opacity and scale values should remain the same after // the reverse animation starts. expect(_getOpacity(key, tester), topFadeTransitionOpacity); expect(_getScale(key, tester), topScale); // Should animate in reverse with 2/3 * 75ms = 50ms // using the enter transition's animation pattern // instead of the exit animation pattern. // Calculation for the time when the linear fade // transition should start if running backwards: // 3/10 * 75ms = 22.5ms // To get the 22.5ms timestamp, run backwards for: // 50ms - 22.5ms = ~27.5ms await tester.pump(const Duration(milliseconds: 27)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 1.0); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // Halfway through fade animation await tester.pump(const Duration(milliseconds: 12)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, closeTo(0.5, 0.05)); topScale = _getScale(key, tester); expect(topScale, greaterThan(0.80)); expect(topScale, lessThan(1.0)); // Complete the rest of the animation await tester.pump(const Duration(milliseconds: 11)); topFadeTransitionOpacity = _getOpacity(key, tester); expect(topFadeTransitionOpacity, 0.0); topScale = _getScale(key, tester); expect(topScale, 0.8); await tester.pump(const Duration(milliseconds: 1)); expect(find.byType(_FlutterLogoModal), findsNothing); }, ); testWidgets( 'State is not lost when transitioning', (WidgetTester tester) async { final GlobalKey bottomKey = GlobalKey(); final GlobalKey topKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder(builder: (BuildContext context) { return Center( child: Column( children: <Widget>[ ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return _FlutterLogoModal( key: topKey, name: 'top route', ); }, ); }, child: const Icon(Icons.add), ), _FlutterLogoModal( key: bottomKey, name: 'bottom route', ), ], ), ); }), ), ), ); // The bottom route's state should already exist. final _FlutterLogoModalState bottomState = tester.state( find.byKey(bottomKey), ); expect(bottomState.widget.name, 'bottom route'); // Start the enter transition of the modal route. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(); // The bottom route's state should be retained at the start of the // transition. expect( tester.state(find.byKey(bottomKey)), bottomState, ); // The top route's state should be created. final _FlutterLogoModalState topState = tester.state( find.byKey(topKey), ); expect(topState.widget.name, 'top route'); // Halfway point of forwards animation. await tester.pump(const Duration(milliseconds: 75)); expect( tester.state(find.byKey(bottomKey)), bottomState, ); expect( tester.state(find.byKey(topKey)), topState, ); // End the transition and see if top and bottom routes' // states persist. await tester.pumpAndSettle(); expect( tester.state(find.byKey( bottomKey, skipOffstage: false, )), bottomState, ); expect( tester.state(find.byKey(topKey)), topState, ); // Start the reverse animation. Both top and bottom // routes' states should persist. await tester.tapAt(Offset.zero); await tester.pump(); expect( tester.state(find.byKey(bottomKey)), bottomState, ); expect( tester.state(find.byKey(topKey)), topState, ); // Halfway point of the exit transition. await tester.pump(const Duration(milliseconds: 38)); expect( tester.state(find.byKey(bottomKey)), bottomState, ); expect( tester.state(find.byKey(topKey)), topState, ); // End the exit transition. The bottom route's state should // persist, whereas the top route's state should no longer // be present. await tester.pumpAndSettle(); expect( tester.state(find.byKey(bottomKey)), bottomState, ); expect(find.byKey(topKey), findsNothing); }, ); testWidgets( 'should preserve state', (WidgetTester tester) async { final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: FadeScaleTransition( animation: controller, child: const _FlutterLogoModal(), ), ), ), ), ); final State<StatefulWidget> state = tester.state( find.byType(_FlutterLogoModal), ); expect(state, isNotNull); controller.forward(); await tester.pump(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pump(const Duration(milliseconds: 150)); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pumpAndSettle(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); controller.reverse(); await tester.pump(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pump(const Duration(milliseconds: 150)); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pumpAndSettle(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); controller.forward(); await tester.pump(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pump(const Duration(milliseconds: 150)); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); await tester.pumpAndSettle(); expect(state, same(tester.state(find.byType(_FlutterLogoModal)))); }, ); } double _getOpacity(GlobalKey key, WidgetTester tester) { final Finder finder = find.ancestor( of: find.byKey(key), matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) { final FadeTransition transition = widget as FadeTransition; return a * transition.opacity.value; }); } double _getScale(GlobalKey key, WidgetTester tester) { final Finder finder = find.ancestor( of: find.byKey(key), matching: find.byType(ScaleTransition), ); return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) { final ScaleTransition transition = widget as ScaleTransition; return a * transition.scale.value; }); } class _FlutterLogoModal extends StatefulWidget { const _FlutterLogoModal({ super.key, this.name, }); final String? name; @override _FlutterLogoModalState createState() => _FlutterLogoModalState(); } class _FlutterLogoModalState extends State<_FlutterLogoModal> { @override Widget build(BuildContext context) { return const Center( child: SizedBox( width: 250, height: 250, child: Material( child: Center( child: FlutterLogo(size: 250), ), ), ), ); } }
packages/packages/animations/test/fade_scale_transition_test.dart/0
{ "file_path": "packages/packages/animations/test/fade_scale_transition_test.dart", "repo_id": "packages", "token_count": 7484 }
913
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #docregion FullAppExample import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; late List<CameraDescription> _cameras; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); _cameras = await availableCameras(); runApp(const CameraApp()); } /// CameraApp is the Main Application. class CameraApp extends StatefulWidget { /// Default Constructor const CameraApp({super.key}); @override State<CameraApp> createState() => _CameraAppState(); } class _CameraAppState extends State<CameraApp> { late CameraController controller; @override void initState() { super.initState(); controller = CameraController(_cameras[0], ResolutionPreset.max); controller.initialize().then((_) { if (!mounted) { return; } setState(() {}); }).catchError((Object e) { if (e is CameraException) { switch (e.code) { case 'CameraAccessDenied': // Handle access errors here. break; default: // Handle other errors here. break; } } }); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (!controller.value.isInitialized) { return Container(); } return MaterialApp( home: CameraPreview(controller), ); } } // #enddocregion FullAppExample
packages/packages/camera/camera/example/lib/readme_full_example.dart/0
{ "file_path": "packages/packages/camera/camera/example/lib/readme_full_example.dart", "repo_id": "packages", "token_count": 585 }
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:camera/camera.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeController extends ValueNotifier<CameraValue> implements CameraController { FakeController() : super(const CameraValue.uninitialized(fakeDescription)); static const CameraDescription fakeDescription = CameraDescription( name: '', lensDirection: CameraLensDirection.back, sensorOrientation: 0); @override Future<void> dispose() async { super.dispose(); } @override Widget buildPreview() { return const Texture(textureId: CameraController.kUninitializedCameraId); } @override int get cameraId => CameraController.kUninitializedCameraId; @override void debugCheckIsDisposed() {} @override bool get enableAudio => false; @override Future<double> getExposureOffsetStepSize() async => 1.0; @override Future<double> getMaxExposureOffset() async => 1.0; @override Future<double> getMaxZoomLevel() async => 1.0; @override Future<double> getMinExposureOffset() async => 1.0; @override Future<double> getMinZoomLevel() async => 1.0; @override ImageFormatGroup? get imageFormatGroup => null; @override Future<void> initialize() async {} @override Future<void> lockCaptureOrientation([DeviceOrientation? orientation]) async {} @override Future<void> pauseVideoRecording() async {} @override Future<void> prepareForVideoRecording() async {} @override ResolutionPreset get resolutionPreset => ResolutionPreset.low; @override Future<void> resumeVideoRecording() async {} @override Future<void> setExposureMode(ExposureMode mode) async {} @override Future<double> setExposureOffset(double offset) async => offset; @override Future<void> setExposurePoint(Offset? point) async {} @override Future<void> setFlashMode(FlashMode mode) async {} @override Future<void> setFocusMode(FocusMode mode) async {} @override Future<void> setFocusPoint(Offset? point) async {} @override Future<void> setZoomLevel(double zoom) async {} @override Future<void> startImageStream(onLatestImageAvailable onAvailable) async {} @override Future<void> startVideoRecording( {onLatestImageAvailable? onAvailable}) async {} @override Future<void> stopImageStream() async {} @override Future<XFile> stopVideoRecording() async => XFile(''); @override Future<XFile> takePicture() async => XFile(''); @override Future<void> unlockCaptureOrientation() async {} @override Future<void> pausePreview() async {} @override Future<void> resumePreview() async {} @override Future<void> setDescription(CameraDescription description) async {} @override CameraDescription get description => value.description; } void main() { group('RotatedBox (Android only)', () { testWidgets( 'when recording rotatedBox should turn according to recording orientation', ( WidgetTester tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; final FakeController controller = FakeController(); controller.value = controller.value.copyWith( isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable( DeviceOrientation.landscapeRight), recordingOrientation: const Optional<DeviceOrientation>.fromNullable( DeviceOrientation.landscapeLeft), previewSize: const Size(480, 640), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CameraPreview(controller), ), ); expect(find.byType(RotatedBox), findsOneWidget); final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 3); debugDefaultTargetPlatformOverride = null; }); testWidgets( 'when orientation locked rotatedBox should turn according to locked orientation', ( WidgetTester tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; final FakeController controller = FakeController(); controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: const Optional<DeviceOrientation>.fromNullable( DeviceOrientation.landscapeRight), recordingOrientation: const Optional<DeviceOrientation>.fromNullable( DeviceOrientation.landscapeLeft), previewSize: const Size(480, 640), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CameraPreview(controller), ), ); expect(find.byType(RotatedBox), findsOneWidget); final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 1); debugDefaultTargetPlatformOverride = null; }); testWidgets( 'when not locked and not recording rotatedBox should turn according to device orientation', ( WidgetTester tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; final FakeController controller = FakeController(); controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, recordingOrientation: const Optional<DeviceOrientation>.fromNullable( DeviceOrientation.landscapeLeft), previewSize: const Size(480, 640), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CameraPreview(controller), ), ); expect(find.byType(RotatedBox), findsOneWidget); final RotatedBox rotatedBox = tester.widget<RotatedBox>(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 0); debugDefaultTargetPlatformOverride = null; }); }, skip: kIsWeb); testWidgets('when not on Android there should not be a rotated box', (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; final FakeController controller = FakeController(); controller.value = controller.value.copyWith( isInitialized: true, previewSize: const Size(480, 640), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CameraPreview(controller), ), ); expect(find.byType(RotatedBox), findsNothing); expect(find.byType(Texture), findsOneWidget); debugDefaultTargetPlatformOverride = null; }); }
packages/packages/camera/camera/test/camera_preview_test.dart/0
{ "file_path": "packages/packages/camera/camera/test/camera_preview_test.dart", "repo_id": "packages", "token_count": 2501 }
915
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera; import android.graphics.Rect; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.os.Build.VERSION_CODES; import android.util.Range; import android.util.Rational; import android.util.Size; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; /** * Implementation of the @see CameraProperties interface using the @see * android.hardware.camera2.CameraCharacteristics class to access the different characteristics. */ public class CameraPropertiesImpl implements CameraProperties { private final CameraCharacteristics cameraCharacteristics; private final String cameraName; public CameraPropertiesImpl(@NonNull String cameraName, @NonNull CameraManager cameraManager) throws CameraAccessException { this.cameraName = cameraName; this.cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraName); } @NonNull @Override public String getCameraName() { return cameraName; } @NonNull @Override public Range<Integer>[] getControlAutoExposureAvailableTargetFpsRanges() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES); } @NonNull @Override public Range<Integer> getControlAutoExposureCompensationRange() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE); } @Override public double getControlAutoExposureCompensationStep() { Rational rational = cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP); return rational == null ? 0.0 : rational.doubleValue(); } @NonNull @Override public int[] getControlAutoFocusAvailableModes() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES); } @NonNull @Override public Integer getControlMaxRegionsAutoExposure() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE); } @NonNull @Override public Integer getControlMaxRegionsAutoFocus() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF); } @RequiresApi(api = VERSION_CODES.P) @Nullable @Override public int[] getDistortionCorrectionAvailableModes() { return cameraCharacteristics.get(CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES); } @NonNull @Override public Boolean getFlashInfoAvailable() { return cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); } @Override public int getLensFacing() { return cameraCharacteristics.get(CameraCharacteristics.LENS_FACING); } @Nullable @Override public Float getLensInfoMinimumFocusDistance() { return cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE); } @NonNull @Override public Float getScalerAvailableMaxDigitalZoom() { return cameraCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM); } @RequiresApi(api = VERSION_CODES.R) @Nullable @Override public Float getScalerMaxZoomRatio() { final Range<Float> range = cameraCharacteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE); if (range != null) { return range.getUpper(); } return null; } @RequiresApi(api = VERSION_CODES.R) @Nullable @Override public Float getScalerMinZoomRatio() { final Range<Float> range = cameraCharacteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE); if (range != null) { return range.getLower(); } return null; } @NonNull @Override public Rect getSensorInfoActiveArraySize() { return cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); } @NonNull @Override public Size getSensorInfoPixelArraySize() { return cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE); } @RequiresApi(api = VERSION_CODES.M) @NonNull @Override public Rect getSensorInfoPreCorrectionActiveArraySize() { return cameraCharacteristics.get( CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE); } @Override public int getSensorOrientation() { return cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); } @Override public int getHardwareLevel() { return cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); } @NonNull @Override public int[] getAvailableNoiseReductionModes() { return cameraCharacteristics.get( CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES); } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraPropertiesImpl.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraPropertiesImpl.java", "repo_id": "packages", "token_count": 1587 }
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.features.fpsrange; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.hardware.camera2.CaptureRequest; import android.util.Range; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DeviceInfo; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FpsRangeFeatureTest { @Before public void before() { DeviceInfo.BRAND = "Test Brand"; DeviceInfo.MODEL = "Test Model"; } @After public void after() { DeviceInfo.BRAND = null; DeviceInfo.MODEL = null; } @Test public void ctor_shouldInitializeFpsRangeWithHighestUpperValueFromRangeArray() { FpsRangeFeature fpsRangeFeature = createTestInstance(); assertEquals(13, (int) fpsRangeFeature.getValue().getUpper()); } @Test public void getDebugName_shouldReturnTheNameOfTheFeature() { FpsRangeFeature fpsRangeFeature = createTestInstance(); assertEquals("FpsRangeFeature", fpsRangeFeature.getDebugName()); } @Test public void getValue_shouldReturnHighestUpperRangeIfNotSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FpsRangeFeature fpsRangeFeature = createTestInstance(); assertEquals(13, (int) fpsRangeFeature.getValue().getUpper()); } @Test public void getValue_shouldEchoTheSetValue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FpsRangeFeature fpsRangeFeature = new FpsRangeFeature(mockCameraProperties); @SuppressWarnings("unchecked") Range<Integer> expectedValue = mock(Range.class); fpsRangeFeature.setValue(expectedValue); Range<Integer> actualValue = fpsRangeFeature.getValue(); assertEquals(expectedValue, actualValue); } @Test public void checkIsSupported_shouldReturnTrue() { FpsRangeFeature fpsRangeFeature = createTestInstance(); assertTrue(fpsRangeFeature.checkIsSupported()); } @Test @SuppressWarnings("unchecked") public void updateBuilder_shouldSetAeTargetFpsRange() { CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FpsRangeFeature fpsRangeFeature = createTestInstance(); fpsRangeFeature.updateBuilder(mockBuilder); verify(mockBuilder).set(eq(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE), any(Range.class)); } private static FpsRangeFeature createTestInstance() { @SuppressWarnings("unchecked") Range<Integer> rangeOne = mock(Range.class); @SuppressWarnings("unchecked") Range<Integer> rangeTwo = mock(Range.class); @SuppressWarnings("unchecked") Range<Integer> rangeThree = mock(Range.class); when(rangeOne.getUpper()).thenReturn(11); when(rangeTwo.getUpper()).thenReturn(12); when(rangeThree.getUpper()).thenReturn(13); // Use a wildcard, since `new Range<Integer>[] {rangeOne, rangeTwo, rangeThree}` // results in a 'Generic array creation' error. @SuppressWarnings("unchecked") Range<Integer>[] ranges = (Range<Integer>[]) new Range<?>[] {rangeOne, rangeTwo, rangeThree}; CameraProperties cameraProperties = mock(CameraProperties.class); when(cameraProperties.getControlAutoExposureAvailableTargetFpsRanges()).thenReturn(ranges); return new FpsRangeFeature(cameraProperties); } }
packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeatureTest.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeatureTest.java", "repo_id": "packages", "token_count": 1193 }
917
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.camera.core.Camera; import androidx.camera.core.CameraControl; import androidx.camera.core.CameraInfo; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraHostApi; import java.util.Objects; public class CameraHostApiImpl implements CameraHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; public CameraHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; } /** * Retrieves the {@link CameraInfo} instance that contains information about the {@link Camera} * instance with the specified identifier. */ @Override @NonNull public Long getCameraInfo(@NonNull Long identifier) { Camera camera = getCameraInstance(identifier); CameraInfo cameraInfo = camera.getCameraInfo(); CameraInfoFlutterApiImpl cameraInfoFlutterApiImpl = new CameraInfoFlutterApiImpl(binaryMessenger, instanceManager); cameraInfoFlutterApiImpl.create(cameraInfo, reply -> {}); return instanceManager.getIdentifierForStrongReference(cameraInfo); } /** * Retrieves the {@link CameraControl} instance that provides access to asynchronous operations * like zoom and focus & metering on the {@link Camera} instance with the specified identifier. */ @Override @NonNull public Long getCameraControl(@NonNull Long identifier) { Camera camera = getCameraInstance(identifier); CameraControl cameraControl = camera.getCameraControl(); CameraControlFlutterApiImpl cameraControlFlutterApiImpl = new CameraControlFlutterApiImpl(binaryMessenger, instanceManager); cameraControlFlutterApiImpl.create(cameraControl, reply -> {}); return instanceManager.getIdentifierForStrongReference(cameraControl); } /** Retrieives the {@link Camera} instance associated with the specified {@code identifier}. */ private Camera getCameraInstance(@NonNull Long identifier) { return (Camera) Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java", "repo_id": "packages", "token_count": 687 }
918
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.FocusMeteringResult; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultFlutterApi; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultFlutterApi.Reply; /** * Flutter API implementation for {@link FocusMeteringResult}. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class FocusMeteringResultFlutterApiImpl { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private FocusMeteringResultFlutterApi focusMeteringResultFlutterApi; /** * Constructs a {@link FocusMeteringResultFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public FocusMeteringResultFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; focusMeteringResultFlutterApi = new FocusMeteringResultFlutterApi(binaryMessenger); } /** * Stores the {@link FocusMeteringResult} instance and notifies Dart to create and store a new * {@link FocusMeteringResult} instance that is attached to this one. If {@code instance} has * already been added, this method does nothing. */ public void create(@NonNull FocusMeteringResult instance, @NonNull Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { focusMeteringResultFlutterApi.create( instanceManager.addHostCreatedInstance(instance), callback); } } /** Sets the Flutter API used to send messages to Dart. */ @VisibleForTesting void setApi(@NonNull FocusMeteringResultFlutterApi api) { this.focusMeteringResultFlutterApi = api; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java", "repo_id": "packages", "token_count": 664 }
919
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.ImageProxy; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PlaneProxyFlutterApi; /** * Flutter API implementation for {@link ImageProxy.PlaneProxy}. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class PlaneProxyFlutterApiImpl { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private PlaneProxyFlutterApi api; /** * Constructs a {@link PlaneProxyFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public PlaneProxyFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new PlaneProxyFlutterApi(binaryMessenger); } /** * Stores the {@link ImageProxy.PlaneProxy} instance and notifies Dart to create and store a new * {@link ImageProxy.PlaneProxy} instance that is attached to this one. If {@code instance} has * already been added, this method does nothing. */ public void create( @NonNull ImageProxy.PlaneProxy instance, @NonNull byte[] bytes, @NonNull Long pixelStride, @NonNull Long rowStride, @NonNull PlaneProxyFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create( instanceManager.addHostCreatedInstance(instance), bytes, pixelStride, rowStride, callback); } } /** * Sets the Flutter API used to send messages to Dart. * * <p>This is only visible for testing. */ @VisibleForTesting void setApi(@NonNull PlaneProxyFlutterApi api) { this.api = api; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java", "repo_id": "packages", "token_count": 734 }
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.ZoomState; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ZoomStateFlutterApi; public class ZoomStateFlutterApiImpl extends ZoomStateFlutterApi { private final InstanceManager instanceManager; public ZoomStateFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } /** * Creates a {@link ZoomState} on the Dart side with its minimum zoom ratio and maximum zoom * ratio. */ void create(@NonNull ZoomState zoomState, @NonNull Reply<Void> reply) { if (instanceManager.containsInstance(zoomState)) { return; } final Float minZoomRatio = zoomState.getMinZoomRatio(); final Float maxZoomRatio = zoomState.getMaxZoomRatio(); create( instanceManager.addHostCreatedInstance(zoomState), minZoomRatio.doubleValue(), maxZoomRatio.doubleValue(), reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java", "repo_id": "packages", "token_count": 426 }
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 static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import androidx.camera.video.FallbackStrategy; import androidx.camera.video.Quality; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoResolutionFallbackRule; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; public class FallbackStrategyTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public FallbackStrategy mockFallbackStrategy; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void hostApiCreate_makesCallToCreateExpectedFallbackStrategy() { final FallbackStrategyHostApiImpl hostApi = new FallbackStrategyHostApiImpl(instanceManager); final long instanceIdentifier = 45; final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); try (MockedStatic<FallbackStrategy> mockedFallbackStrategy = mockStatic(FallbackStrategy.class)) { for (VideoQuality videoQuality : VideoQuality.values()) { for (VideoResolutionFallbackRule fallbackRule : VideoResolutionFallbackRule.values()) { // Determine expected Quality based on videoQuality being tested. Quality convertedQuality = null; switch (videoQuality) { case SD: convertedQuality = Quality.SD; break; case HD: convertedQuality = Quality.HD; break; case FHD: convertedQuality = Quality.FHD; break; case UHD: convertedQuality = Quality.UHD; break; case LOWEST: convertedQuality = Quality.LOWEST; break; case HIGHEST: convertedQuality = Quality.HIGHEST; break; default: fail("The VideoQuality " + videoQuality.toString() + "is unhandled by this test."); } // Set Quality as final local variable to avoid error about using non-final (or effecitvely final) local variables in lambda expressions. final Quality expectedQuality = convertedQuality; // Mock calls to create FallbackStrategy according to fallbackRule being tested. switch (fallbackRule) { case HIGHER_QUALITY_OR_LOWER_THAN: mockedFallbackStrategy .when(() -> FallbackStrategy.higherQualityOrLowerThan(expectedQuality)) .thenAnswer((Answer<FallbackStrategy>) invocation -> mockFallbackStrategy); break; case HIGHER_QUALITY_THAN: mockedFallbackStrategy .when(() -> FallbackStrategy.higherQualityThan(expectedQuality)) .thenAnswer((Answer<FallbackStrategy>) invocation -> mockFallbackStrategy); break; case LOWER_QUALITY_OR_HIGHER_THAN: mockedFallbackStrategy .when(() -> FallbackStrategy.lowerQualityOrHigherThan(expectedQuality)) .thenAnswer((Answer<FallbackStrategy>) invocation -> mockFallbackStrategy); break; case LOWER_QUALITY_THAN: mockedFallbackStrategy .when(() -> FallbackStrategy.lowerQualityThan(expectedQuality)) .thenAnswer((Answer<FallbackStrategy>) invocation -> mockFallbackStrategy); break; default: fail( "The VideoResolutionFallbackRule " + fallbackRule.toString() + "is unhandled by this test."); } hostApi.create(instanceIdentifier, videoQuality, fallbackRule); assertEquals(instanceManager.getInstance(instanceIdentifier), mockFallbackStrategy); // Clear/reset FallbackStrategy mock and InstanceManager. mockedFallbackStrategy.reset(); instanceManager.clear(); } } } } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java", "repo_id": "packages", "token_count": 1941 }
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.Mockito.mock; import static org.mockito.Mockito.mockStatic; import android.util.Size; import androidx.camera.core.CameraInfo; import androidx.camera.video.FallbackStrategy; import androidx.camera.video.Quality; import androidx.camera.video.QualitySelector; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQualityData; 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.MockedStatic; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; public class QualitySelectorTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public QualitySelector mockQualitySelectorWithoutFallbackStrategy; @Mock public QualitySelector mockQualitySelectorWithFallbackStrategy; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void hostApiCreate_createsExpectedQualitySelectorWhenOneQualitySpecified() { final VideoQualityData expectedVideoQualityData = new VideoQualityData.Builder().setQuality(VideoQuality.UHD).build(); final List<VideoQualityData> videoQualityDataList = Arrays.asList(expectedVideoQualityData); final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); final long fallbackStrategyIdentifier = 9; final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); instanceManager.addDartCreatedInstance(mockFallbackStrategy, fallbackStrategyIdentifier); try (MockedStatic<QualitySelector> mockedQualitySelector = mockStatic(QualitySelector.class)) { mockedQualitySelector .when(() -> QualitySelector.from(Quality.UHD)) .thenAnswer( (Answer<QualitySelector>) invocation -> mockQualitySelectorWithoutFallbackStrategy); mockedQualitySelector .when(() -> QualitySelector.from(Quality.UHD, mockFallbackStrategy)) .thenAnswer( (Answer<QualitySelector>) invocation -> mockQualitySelectorWithFallbackStrategy); // Test with no fallback strategy. long instanceIdentifier = 0; hostApi.create(instanceIdentifier, videoQualityDataList, null); assertEquals( instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithoutFallbackStrategy); // Test with fallback strategy. instanceIdentifier = 1; hostApi.create(instanceIdentifier, videoQualityDataList, fallbackStrategyIdentifier); assertEquals( instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithFallbackStrategy); } } @Test public void hostApiCreate_createsExpectedQualitySelectorWhenOrderedListOfQualitiesSpecified() { final List<VideoQualityData> videoQualityDataList = Arrays.asList( new VideoQualityData.Builder().setQuality(VideoQuality.UHD).build(), new VideoQualityData.Builder().setQuality(VideoQuality.HIGHEST).build()); final List<Quality> expectedVideoQualityList = Arrays.asList(Quality.UHD, Quality.HIGHEST); final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); final long fallbackStrategyIdentifier = 9; final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); instanceManager.addDartCreatedInstance(mockFallbackStrategy, fallbackStrategyIdentifier); try (MockedStatic<QualitySelector> mockedQualitySelector = mockStatic(QualitySelector.class)) { mockedQualitySelector .when(() -> QualitySelector.fromOrderedList(expectedVideoQualityList)) .thenAnswer( (Answer<QualitySelector>) invocation -> mockQualitySelectorWithoutFallbackStrategy); mockedQualitySelector .when( () -> QualitySelector.fromOrderedList(expectedVideoQualityList, mockFallbackStrategy)) .thenAnswer( (Answer<QualitySelector>) invocation -> mockQualitySelectorWithFallbackStrategy); // Test with no fallback strategy. long instanceIdentifier = 0; hostApi.create(instanceIdentifier, videoQualityDataList, null); assertEquals( instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithoutFallbackStrategy); // Test with fallback strategy. instanceIdentifier = 1; hostApi.create(instanceIdentifier, videoQualityDataList, fallbackStrategyIdentifier); assertEquals( instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithFallbackStrategy); } } @Test public void getResolution_returnsExpectedResolutionInfo() { final CameraInfo mockCameraInfo = mock(CameraInfo.class); final long cameraInfoIdentifier = 6; final VideoQuality videoQuality = VideoQuality.FHD; final Size sizeResult = new Size(30, 40); final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); instanceManager.addDartCreatedInstance(mockCameraInfo, cameraInfoIdentifier); try (MockedStatic<QualitySelector> mockedQualitySelector = mockStatic(QualitySelector.class)) { mockedQualitySelector .when(() -> QualitySelector.getResolution(mockCameraInfo, Quality.FHD)) .thenAnswer((Answer<Size>) invocation -> sizeResult); final ResolutionInfo result = hostApi.getResolution(cameraInfoIdentifier, videoQuality); assertEquals(result.getWidth(), Long.valueOf(sizeResult.getWidth())); assertEquals(result.getHeight(), Long.valueOf(sizeResult.getHeight())); } } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java", "repo_id": "packages", "token_count": 2067 }
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. import 'package:flutter/services.dart'; import 'package:meta/meta.dart'; import 'camera_state.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'observer.dart'; import 'zoom_state.dart'; /// A data holder class that can be observed. /// /// For this wrapped class, observation can only fall within the lifecycle of the /// Android Activity to which this plugin is attached. /// /// See https://developer.android.com/reference/androidx/lifecycle/LiveData. @immutable class LiveData<T extends Object> extends JavaObject { /// Constructs a [LiveData] that is not automatically attached to a native object. LiveData.detached({this.binaryMessenger, this.instanceManager}) : _api = _LiveDataHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager), super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager); final _LiveDataHostApiImpl _api; /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager? instanceManager; /// Error message indicating a [LiveData] instance was constructed with a type /// currently unsupported by the wrapping of this class. static const String unsupportedLiveDataTypeErrorMessage = 'The type of LiveData passed to this method is current unspported; please see LiveDataSupportedTypeData in pigeons/camerax_library.dart if you wish to support a new type.'; /// Adds specified [Observer] to the list of observers of this instance. Future<void> observe(Observer<T> observer) { return _api.observeFromInstances(this, observer); } /// Removes all observers of this instance. Future<void> removeObservers() { return _api.removeObserversFromInstances(this); } /// Returns the current value. Future<T?>? getValue() { return _api.getValueFromInstances<T>(this); } } /// Host API implementation of [LiveData]. class _LiveDataHostApiImpl extends LiveDataHostApi { /// Constructs a [_LiveDataHostApiImpl]. /// /// If [binaryMessenger] 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]. _LiveDataHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; /// Adds specified [Observer] to the list of observers of the specified /// [LiveData] instance. Future<void> observeFromInstances( LiveData<dynamic> instance, Observer<dynamic> observer, ) { return observe( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(observer)!, ); } /// Removes all observers of the specified [LiveData] instance. Future<void> removeObserversFromInstances( LiveData<dynamic> instance, ) { return removeObservers( instanceManager.getIdentifier(instance)!, ); } /// Gets current value of specified [LiveData] instance. Future<T?>? getValueFromInstances<T extends Object>( LiveData<T> instance) async { LiveDataSupportedTypeData? typeData; switch (T) { case const (CameraState): typeData = LiveDataSupportedTypeData(value: LiveDataSupportedType.cameraState); case const (ZoomState): typeData = LiveDataSupportedTypeData(value: LiveDataSupportedType.zoomState); default: throw ArgumentError(LiveData.unsupportedLiveDataTypeErrorMessage); } final int? valueIdentifier = await getValue(instanceManager.getIdentifier(instance)!, typeData); return valueIdentifier == null ? null : instanceManager.getInstanceWithWeakReference<T>(valueIdentifier); } } /// Flutter API implementation for [LiveData]. /// /// 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 LiveDataFlutterApiImpl implements LiveDataFlutterApi { /// Constructs a [LiveDataFlutterApiImpl]. /// /// 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]. LiveDataFlutterApiImpl({ 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, LiveDataSupportedTypeData typeData, ) { switch (typeData.value) { case LiveDataSupportedType.cameraState: _instanceManager.addHostCreatedInstance( LiveData<CameraState>.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), identifier, onCopy: (LiveData<CameraState> original) => LiveData<CameraState>.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), ); return; case LiveDataSupportedType.zoomState: _instanceManager.addHostCreatedInstance( LiveData<ZoomState>.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), identifier, onCopy: (LiveData<ZoomState> original) => LiveData<ZoomState>.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), ); return; // This ignore statement is safe beause this error will be useful when // a new LiveDataSupportedType is being added, but the logic in this method // has not yet been updated. // ignore: no_default_cases default: throw ArgumentError(LiveData.unsupportedLiveDataTypeErrorMessage); } } }
packages/packages/camera/camera_android_camerax/lib/src/live_data.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/live_data.dart", "repo_id": "packages", "token_count": 2278 }
924
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart' show BinaryMessenger; import 'package:meta/meta.dart' show immutable; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; /// Represents zoom related information of a camera. /// /// See https://developer.android.com/reference/androidx/camera/core/ZoomState. @immutable class ZoomState extends JavaObject { /// Constructs a [CameraInfo] that is not automatically attached to a native object. ZoomState.detached( {super.binaryMessenger, super.instanceManager, required this.minZoomRatio, required this.maxZoomRatio}) : super.detached() { AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } /// The minimum zoom ratio of the camera represented by this instance. final double minZoomRatio; /// The maximum zoom ratio of the camera represented by this instance. final double maxZoomRatio; } /// Flutter API implementation of [ZoomState]. class ZoomStateFlutterApiImpl implements ZoomStateFlutterApi { /// Constructs a [ZoomStateFlutterApiImpl]. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an [InstanceManager] is being created. ZoomStateFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : 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. final InstanceManager instanceManager; @override void create(int identifier, double minZoomRatio, double maxZoomRatio) { instanceManager.addHostCreatedInstance( ZoomState.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, minZoomRatio: minZoomRatio, maxZoomRatio: maxZoomRatio), identifier, onCopy: (ZoomState original) { return ZoomState.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, minZoomRatio: original.minZoomRatio, maxZoomRatio: original.maxZoomRatio); }, ); } }
packages/packages/camera/camera_android_camerax/lib/src/zoom_state.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/zoom_state.dart", "repo_id": "packages", "token_count": 835 }
925
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/focus_metering_action_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:camera_android_camerax/src/camera_info.dart' as _i2; import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i5; import 'package:camera_android_camerax/src/metering_point.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i4; // 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 _FakeCameraInfo_0 extends _i1.SmartFake implements _i2.CameraInfo { _FakeCameraInfo_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [MeteringPoint]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockMeteringPoint extends _i1.Mock implements _i3.MeteringPoint { MockMeteringPoint() { _i1.throwOnMissingStub(this); } @override double get x => (super.noSuchMethod( Invocation.getter(#x), returnValue: 0.0, ) as double); @override double get y => (super.noSuchMethod( Invocation.getter(#y), returnValue: 0.0, ) as double); @override _i2.CameraInfo get cameraInfo => (super.noSuchMethod( Invocation.getter(#cameraInfo), returnValue: _FakeCameraInfo_0( this, Invocation.getter(#cameraInfo), ), ) as _i2.CameraInfo); } /// A class which mocks [TestFocusMeteringActionHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestFocusMeteringActionHostApi extends _i1.Mock implements _i4.TestFocusMeteringActionHostApi { MockTestFocusMeteringActionHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, List<_i5.MeteringPointInfo?>? meteringPointInfos, bool? disableAutoCancel, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, meteringPointInfos, disableAutoCancel, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i4.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart", "repo_id": "packages", "token_count": 1289 }
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:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/pending_recording.dart'; import 'package:camera_android_camerax/src/recording.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'pending_recording_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks( <Type>[TestPendingRecordingHostApi, TestInstanceManagerHostApi, Recording]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); test('start calls start on the Java side', () async { final MockTestPendingRecordingHostApi mockApi = MockTestPendingRecordingHostApi(); TestPendingRecordingHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final PendingRecording pendingRecording = PendingRecording.detached(instanceManager: instanceManager); const int pendingRecordingId = 2; instanceManager.addHostCreatedInstance(pendingRecording, pendingRecordingId, onCopy: (_) => PendingRecording.detached(instanceManager: instanceManager)); final Recording mockRecording = MockRecording(); const int mockRecordingId = 3; instanceManager.addHostCreatedInstance(mockRecording, mockRecordingId, onCopy: (_) => Recording.detached(instanceManager: instanceManager)); when(mockApi.start(pendingRecordingId)).thenReturn(mockRecordingId); expect(await pendingRecording.start(), mockRecording); verify(mockApi.start(pendingRecordingId)); }); test('flutterApiCreateTest', () async { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final PendingRecordingFlutterApi flutterApi = PendingRecordingFlutterApiImpl( instanceManager: instanceManager, ); flutterApi.create(0); expect(instanceManager.getInstanceWithWeakReference(0), isA<PendingRecording>()); }); }
packages/packages/camera/camera_android_camerax/test/pending_recording_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/pending_recording_test.dart", "repo_id": "packages", "token_count": 818 }
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 'dart:ui'; import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/resolution_strategy.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'resolution_strategy_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[ TestResolutionStrategyHostApi, TestInstanceManagerHostApi, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('ResolutionStrategy', () { tearDown(() { TestResolutionStrategyHostApi.setup(null); TestInstanceManagerHostApi.setup(null); }); test( 'detached resolutionStrategy constructors do not make call to Host API create', () { final MockTestResolutionStrategyHostApi mockApi = MockTestResolutionStrategyHostApi(); TestResolutionStrategyHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const Size boundSize = Size(70, 20); const int fallbackRule = 1; ResolutionStrategy.detached( boundSize: boundSize, fallbackRule: fallbackRule, instanceManager: instanceManager, ); verifyNever(mockApi.create( argThat(isA<int>()), argThat(isA<ResolutionInfo>() .having((ResolutionInfo size) => size.width, 'width', 50) .having((ResolutionInfo size) => size.height, 'height', 30)), fallbackRule, )); ResolutionStrategy.detachedHighestAvailableStrategy( instanceManager: instanceManager, ); verifyNever(mockApi.create( argThat(isA<int>()), null, null, )); }); test('HostApi create creates expected ResolutionStrategies', () { final MockTestResolutionStrategyHostApi mockApi = MockTestResolutionStrategyHostApi(); TestResolutionStrategyHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const Size boundSize = Size(50, 30); const int fallbackRule = 0; final ResolutionStrategy instance = ResolutionStrategy( boundSize: boundSize, fallbackRule: fallbackRule, instanceManager: instanceManager, ); verify(mockApi.create( instanceManager.getIdentifier(instance), argThat(isA<ResolutionInfo>() .having((ResolutionInfo size) => size.width, 'width', 50) .having((ResolutionInfo size) => size.height, 'height', 30)), fallbackRule, )); final ResolutionStrategy highestAvailableInstance = ResolutionStrategy.highestAvailableStrategy( instanceManager: instanceManager, ); verify(mockApi.create( instanceManager.getIdentifier(highestAvailableInstance), null, null, )); }); }); }
packages/packages/camera/camera_android_camerax/test/resolution_strategy_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/resolution_strategy_test.dart", "repo_id": "packages", "token_count": 1317 }
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:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; /// A mock [MethodChannel] implementation for use in tests. class MethodChannelMock { /// Creates a new instance with the specified channel name. /// /// This method channel will handle all method invocations specified by /// returning the value mapped to the method name key. If a delay is /// specified, results are returned after the delay has elapsed. MethodChannelMock({ required String channelName, this.delay, required this.methods, }) : methodChannel = MethodChannel(channelName) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(methodChannel, _handler); } final Duration? delay; final MethodChannel methodChannel; final Map<String, dynamic> methods; final List<MethodCall> log = <MethodCall>[]; Future<dynamic> _handler(MethodCall methodCall) async { log.add(methodCall); if (!methods.containsKey(methodCall.method)) { throw MissingPluginException('No TEST implementation found for method ' '${methodCall.method} on channel ${methodChannel.name}'); } return Future<dynamic>.delayed(delay ?? Duration.zero, () { final dynamic result = methods[methodCall.method]; if (result is Exception) { throw result; } return Future<dynamic>.value(result); }); } }
packages/packages/camera/camera_windows/test/utils/method_channel_mock.dart/0
{ "file_path": "packages/packages/camera/camera_windows/test/utils/method_channel_mock.dart", "repo_id": "packages", "token_count": 482 }
929
## 0.3.4+1 * Removes a few deprecated API usages. ## 0.3.4 * Updates to web code to package `web: ^0.5.0`. * Updates SDK version to Dart `^3.3.0`. ## 0.3.3+8 * Now supports `dart2wasm` compilation. * Updates minimum supported SDK version to Flutter 3.16/Dart 3.2. ## 0.3.3+7 * Updates README to improve example of instantiating an XFile. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.3.3+6 * Improves documentation about ignored parameters in IO implementation. ## 0.3.3+5 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.3.3+4 * Reverts an accidental change in a constructor argument's nullability. ## 0.3.3+3 * **RETRACTED** * Updates code to fix strict-cast violations. * Updates minimum SDK version to Flutter 3.0. ## 0.3.3+2 * Fixes lint warnings in tests. * Dartdoc correction for `readAsBytes` and `readAsString`. ## 0.3.3+1 * Fixes `lastModified` unimplemented error description. ## 0.3.3 * Removes unused Flutter dependencies. ## 0.3.2 * Improve web implementation so it can stream larger files. ## 0.3.1+5 * Unify XFile interface for web and mobile platforms ## 0.3.1+4 * The `dart:io` implementation of `saveTo` now does a file copy for path-based `XFile` instances, rather than reading the contents into memory. ## 0.3.1+3 * Fix example in README ## 0.3.1+2 * Fix package import in README * Remove 'Get Started' boilerplate in README ## 0.3.1+1 * Rehomed to `flutter/packages` repository. ## 0.3.1 * Fix nullability of `XFileBase`'s `path` and `name` to match the implementations to avoid potential analyzer issues. ## 0.3.0 * Migrated package to null-safety. * **breaking change** According to our unit tests, the API should be backwards-compatible. Some relevant changes were made, however: * Web: `lastModified` returns the epoch time as a default value, to maintain the `Future<DateTime>` return type (and not `null`) ## 0.2.1 * Prepare for breaking `package:http` change. ## 0.2.0 * **breaking change** Make sure the `saveTo` method returns a `Future` so it can be awaited and users are sure the file has been written to disk. ## 0.1.0+2 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 0.1.0+1 * Update Flutter SDK constraint. ## 0.1.0 * Initial open-source release.
packages/packages/cross_file/CHANGELOG.md/0
{ "file_path": "packages/packages/cross_file/CHANGELOG.md", "repo_id": "packages", "token_count": 806 }
930
// 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/rendering.dart'; import 'base_grid_layout.dart'; // The model that tracks the current max size of the Sliver in the mainAxis and // tracks if there is still space on the crossAxis. class _RunMetrics { _RunMetrics({ required this.maxSliver, required this.currentSizeUsed, required this.scrollOffset, }); /// The biggest sliver size for the current run. double maxSliver; /// The current size that has been used in the current run. double currentSizeUsed; /// The scroll offset in the current run. double scrollOffset; } /// A [DynamicSliverGridLayout] that uses dynamically sized tiles. /// /// Rather that providing a grid with a [DynamicSliverGridLayout] directly, instead /// provide the grid a [SliverGridDelegate], which can compute a /// [DynamicSliverGridLayout] given the current [SliverConstraints]. /// /// This layout is used by [SliverGridDelegateWithWrapping]. /// /// See also: /// /// * [SliverGridDelegateWithWrapping], which uses this layout. /// * [DynamicSliverGridLayout], which represents an arbitrary dynamic tile layout. /// * [DynamicSliverGridGeometry], which represents the size and position of a /// single tile in a grid. /// * [SliverGridDelegate.getLayout], which returns this object to describe the /// delegate's layout. /// * [RenderDynamicSliverGrid], which uses this class during its /// [RenderDynamicSliverGrid.performLayout] method. class SliverGridWrappingTileLayout extends DynamicSliverGridLayout { /// Creates a layout that uses dynamic sized and spaced tiles. /// /// All of the arguments must not be null and must not be negative. SliverGridWrappingTileLayout({ required this.mainAxisSpacing, required this.crossAxisSpacing, required this.childMainAxisExtent, required this.childCrossAxisExtent, required this.crossAxisExtent, required this.scrollDirection, }) : assert(mainAxisSpacing >= 0), assert(crossAxisSpacing >= 0), assert(childMainAxisExtent >= 0), assert(childCrossAxisExtent >= 0), assert(crossAxisExtent >= 0), assert(scrollDirection == Axis.horizontal || scrollDirection == Axis.vertical); /// The direction in which the layout should be built. final Axis scrollDirection; /// The extent of the child in the non-scrolling axis. final double crossAxisExtent; /// The number of logical pixels between each child along the main axis. final double mainAxisSpacing; /// The number of logical pixels between each child along the cross axis. final double crossAxisSpacing; /// The number of pixels from the leading edge of one tile to the trailing /// edge of the same tile in the main axis. final double childMainAxisExtent; /// The number of pixels from the leading edge of one tile to the trailing /// edge of the same tile in the cross axis. final double childCrossAxisExtent; /// The model that is used internally to keep track of how much space is left /// and how much has been used. final List<_RunMetrics> _model = <_RunMetrics>[ _RunMetrics(maxSliver: 0.0, currentSizeUsed: 0.0, scrollOffset: 0.0) ]; // This method provides the initial constraints for the child to layout, // and then it is updated with the final size later in // updateGeometryForChildIndex. @override DynamicSliverGridGeometry getGeometryForChildIndex(int index) { return DynamicSliverGridGeometry( scrollOffset: 0, crossAxisOffset: 0, mainAxisExtent: childMainAxisExtent, crossAxisExtent: childCrossAxisExtent, ); } @override DynamicSliverGridGeometry updateGeometryForChildIndex( int index, Size childSize, ) { final double scrollOffset = _model.last.scrollOffset; final double currentSizeUsed = _model.last.currentSizeUsed; late final double addedSize; switch (scrollDirection) { case Axis.vertical: addedSize = currentSizeUsed + childSize.width + crossAxisSpacing; case Axis.horizontal: addedSize = currentSizeUsed + childSize.height + mainAxisSpacing; } if (addedSize > crossAxisExtent && _model.last.currentSizeUsed > 0.0) { switch (scrollDirection) { case Axis.vertical: _model.add( _RunMetrics( maxSliver: childSize.height + mainAxisSpacing, currentSizeUsed: childSize.width + crossAxisSpacing, scrollOffset: scrollOffset + _model.last.maxSliver + mainAxisSpacing, ), ); case Axis.horizontal: _model.add( _RunMetrics( maxSliver: childSize.width + crossAxisSpacing, currentSizeUsed: childSize.height + mainAxisSpacing, scrollOffset: scrollOffset + _model.last.maxSliver + crossAxisSpacing, ), ); } return DynamicSliverGridGeometry( scrollOffset: _model.last.scrollOffset, crossAxisOffset: 0.0, mainAxisExtent: childSize.height + mainAxisSpacing, crossAxisExtent: childSize.width + crossAxisSpacing, ); } else { _model.last.currentSizeUsed = addedSize; } switch (scrollDirection) { case Axis.vertical: if (childSize.height + mainAxisSpacing > _model.last.maxSliver) { _model.last.maxSliver = childSize.height + mainAxisSpacing; } case Axis.horizontal: if (childSize.width + crossAxisSpacing > _model.last.maxSliver) { _model.last.maxSliver = childSize.width + crossAxisSpacing; } } return DynamicSliverGridGeometry( scrollOffset: scrollOffset, crossAxisOffset: currentSizeUsed, mainAxisExtent: childSize.height, crossAxisExtent: childSize.width, ); } @override bool reachedTargetScrollOffset(double targetOffset) { return _model.last.scrollOffset > targetOffset; } } /// A [SliverGridDelegate] for creating grids that wrap variably sized tiles. /// /// For example, if the grid is vertical, this delegate will create a layout /// where the children are laid out until they fill the horizontal axis and then /// they continue in the next row. If the grid is horizontal, this delegate will /// do the same but it will fill the vertical axis and will pass to another /// column until it finishes. /// /// This delegate creates grids with different sized tiles. Tiles /// can have fixed dimensions if [childCrossAxisExtent] or /// [childMainAxisExtent] are provided. /// /// See also: /// * [DynamicGridView.wrap], a constructor to use with this [SliverGridDelegate], /// like `GridView.extent`. /// * [DynamicGridView], which can use this delegate to control the layout of its /// tiles. /// * [RenderDynamicSliverGrid], which can use this delegate to control the /// layout of its tiles. class SliverGridDelegateWithWrapping extends SliverGridDelegate { /// Create a delegate that wraps variably sized tiles. /// /// The children widgets are provided with loose constraints, and if any of the /// extent parameters are set, the children are given tight constraints. /// The way that children are made to have loose constraints is by assigning /// the value of [double.infinity] to [childMainAxisExtent] and /// [childCrossAxisExtent]. /// To have same sized tiles with the wrapping, specify the [childCrossAxisExtent] /// and the [childMainAxisExtent] to be the same size. Or only one of them to /// be of a certain size in one of the axis. const SliverGridDelegateWithWrapping({ this.mainAxisSpacing = 0.0, this.crossAxisSpacing = 0.0, this.childCrossAxisExtent = double.infinity, this.childMainAxisExtent = double.infinity, }) : assert(mainAxisSpacing >= 0), assert(crossAxisSpacing >= 0); /// The number of pixels from the leading edge of one tile to the trailing /// edge of the same tile in the main axis. /// /// Defaults to [double.infinity] to provide the child with loose constraints. final double childMainAxisExtent; /// The number of pixels from the leading edge of one tile to the trailing /// edge of the same tile in the cross axis. /// /// Defaults to [double.infinity] to provide the child with loose constraints. final double childCrossAxisExtent; /// The number of logical pixels between each child along the main axis. /// /// Defaults to 0.0 final double mainAxisSpacing; /// The number of logical pixels between each child along the cross axis. /// /// Defaults to 0.0 final double crossAxisSpacing; bool _debugAssertIsValid() { assert(mainAxisSpacing >= 0.0); assert(crossAxisSpacing >= 0.0); return true; } @override SliverGridLayout getLayout(SliverConstraints constraints) { assert(_debugAssertIsValid()); return SliverGridWrappingTileLayout( childMainAxisExtent: childMainAxisExtent, childCrossAxisExtent: childCrossAxisExtent, mainAxisSpacing: mainAxisSpacing, crossAxisSpacing: crossAxisSpacing, scrollDirection: axisDirectionToAxis(constraints.axisDirection), crossAxisExtent: constraints.crossAxisExtent, ); } @override bool shouldRelayout(SliverGridDelegateWithWrapping oldDelegate) { return oldDelegate.mainAxisSpacing != mainAxisSpacing || oldDelegate.crossAxisSpacing != crossAxisSpacing; } }
packages/packages/dynamic_layouts/lib/src/wrap_layout.dart/0
{ "file_path": "packages/packages/dynamic_layouts/lib/src/wrap_layout.dart", "repo_id": "packages", "token_count": 3191 }
931
rootProject.name = 'espresso'
packages/packages/espresso/android/settings.gradle/0
{ "file_path": "packages/packages/espresso/android/settings.gradle", "repo_id": "packages", "token_count": 10 }
932
rootProject.name = 'file_selector_android'
packages/packages/file_selector/file_selector_android/android/settings.gradle/0
{ "file_path": "packages/packages/file_selector/file_selector_android/android/settings.gradle", "repo_id": "packages", "token_count": 14 }
933
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.9.3+3 * Fixes handling of unknown file extensions on macOS 11+. ## 0.9.3+2 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters. ## 0.9.3+1 * Updates to the latest version of `pigeon`. ## 0.9.3 * Adds `getSaveLocation` and deprecates `getSavePath`. * Updates minimum supported macOS version to 10.14. ## 0.9.2 * Adds support for MIME types on macOS 11+. ## 0.9.1+1 * Updates references to the deprecated `macUTIs`. ## 0.9.1 * Adds `getDirectoryPaths` implementation. ## 0.9.0+8 * Updates pigeon for null value handling fixes. * Updates minimum Flutter version to 3.3. ## 0.9.0+7 * Updates to `pigeon` version 9. ## 0.9.0+6 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.9.0+5 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates example code for `use_build_context_synchronously` lint. * Updates minimum Flutter version to 3.0. ## 0.9.0+4 * Converts platform channel to Pigeon. ## 0.9.0+3 * Changes XTypeGroup initialization from final to const. ## 0.9.0+2 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 0.9.0+1 * Updates README for endorsement. * Updates `flutter_test` to be a `dev_dependencies` entry. ## 0.9.0 * **BREAKING CHANGE**: Methods that take `XTypeGroup`s now throw an `ArgumentError` if any group is not a wildcard (all filter types null or empty), but doesn't include any of the filter types supported by macOS. * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.8.2+2 * Updates references to the obsolete master branch. ## 0.8.2+1 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.2 * Moves source to flutter/plugins. * Adds native unit tests. * Converts native implementation to Swift. * Switches to an internal method channel implementation. ## 0.0.4+1 * Update README ## 0.0.4 * Treat empty filter lists the same as null. ## 0.0.3 * Fix README ## 0.0.2 * Update SDK constraint to signal compatibility with null safety. ## 0.0.1 * Initial macOS implementation of `file_selector`.
packages/packages/file_selector/file_selector_macos/CHANGELOG.md/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/CHANGELOG.md", "repo_id": "packages", "token_count": 810 }
934
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'file_selector_macos' s.version = '0.0.1' s.summary = 'macOS implementation of file_selector.' s.description = <<-DESC Displays native macOS open and save panels. DESC s.license = { :type => 'BSD', :file => '../LICENSE' } s.homepage = 'https://github.com/flutter/packages/tree/main/packages/file_selector' s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_macos' } s.source_files = 'Classes/**/*' s.dependency 'FlutterMacOS' s.platform = :osx, '10.14' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.swift_version = '5.0' end
packages/packages/file_selector/file_selector_macos/macos/file_selector_macos.podspec/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/macos/file_selector_macos.podspec", "repo_id": "packages", "token_count": 415 }
935
// Mocks generated by Mockito 5.4.4 from annotations // in file_selector_windows/test/file_selector_windows_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:file_selector_windows/src/messages.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'test_api.g.dart' as _i3; // 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 _FakeFileDialogResult_0 extends _i1.SmartFake implements _i2.FileDialogResult { _FakeFileDialogResult_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [TestFileSelectorApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestFileSelectorApi extends _i1.Mock implements _i3.TestFileSelectorApi { MockTestFileSelectorApi() { _i1.throwOnMissingStub(this); } @override _i2.FileDialogResult showOpenDialog( _i2.SelectionOptions? options, String? initialDirectory, String? confirmButtonText, ) => (super.noSuchMethod( Invocation.method( #showOpenDialog, [ options, initialDirectory, confirmButtonText, ], ), returnValue: _FakeFileDialogResult_0( this, Invocation.method( #showOpenDialog, [ options, initialDirectory, confirmButtonText, ], ), ), ) as _i2.FileDialogResult); @override _i2.FileDialogResult showSaveDialog( _i2.SelectionOptions? options, String? initialDirectory, String? suggestedName, String? confirmButtonText, ) => (super.noSuchMethod( Invocation.method( #showSaveDialog, [ options, initialDirectory, suggestedName, confirmButtonText, ], ), returnValue: _FakeFileDialogResult_0( this, Invocation.method( #showSaveDialog, [ options, initialDirectory, suggestedName, confirmButtonText, ], ), ), ) as _i2.FileDialogResult); }
packages/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart", "repo_id": "packages", "token_count": 1251 }
936
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.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( theme: ThemeData.light().copyWith( navigationRailTheme: const NavigationRailThemeData( selectedIconTheme: IconThemeData( color: Colors.red, size: 28, ), selectedLabelTextStyle: TextStyle( fontSize: 16, color: Colors.red, ), unselectedLabelTextStyle: TextStyle( fontSize: 14, color: Colors.black, ), ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( type: BottomNavigationBarType.fixed, ), ), home: const MyHomePage(), ); } } /// Creates a basic adaptive page with navigational elements and a body using /// [AdaptiveScaffold]. class MyHomePage extends StatefulWidget { /// Creates a const [MyHomePage]. const MyHomePage({super.key, this.transitionDuration = 1000}); /// Declare transition duration. final int transitionDuration; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _selectedTab = 0; int _transitionDuration = 1000; // Initialize transition time variable. @override void initState() { super.initState(); setState(() { _transitionDuration = widget.transitionDuration; }); } // #docregion Example @override Widget build(BuildContext context) { // Define the children to display within the body at different breakpoints. final List<Widget> children = <Widget>[ for (int i = 0; i < 10; i++) Padding( padding: const EdgeInsets.all(8.0), child: Container( color: const Color.fromARGB(255, 255, 201, 197), height: 400, ), ) ]; return AdaptiveScaffold( // An option to override the default transition duration. transitionDuration: Duration(milliseconds: _transitionDuration), // An option to override the default breakpoints used for small, medium, // and large. smallBreakpoint: const WidthPlatformBreakpoint(end: 700), mediumBreakpoint: const WidthPlatformBreakpoint(begin: 700, end: 1000), largeBreakpoint: const WidthPlatformBreakpoint(begin: 1000), useDrawer: false, selectedIndex: _selectedTab, onSelectedIndexChange: (int index) { setState(() { _selectedTab = index; }); }, destinations: const <NavigationDestination>[ NavigationDestination( icon: Icon(Icons.inbox_outlined), selectedIcon: Icon(Icons.inbox), label: 'Inbox', ), NavigationDestination( icon: Icon(Icons.article_outlined), selectedIcon: Icon(Icons.article), label: 'Articles', ), NavigationDestination( icon: Icon(Icons.chat_outlined), selectedIcon: Icon(Icons.chat), label: 'Chat', ), NavigationDestination( icon: Icon(Icons.video_call_outlined), selectedIcon: Icon(Icons.video_call), label: 'Video', ), NavigationDestination( icon: Icon(Icons.home_outlined), selectedIcon: Icon(Icons.home), label: 'Inbox', ), ], body: (_) => GridView.count(crossAxisCount: 2, children: children), smallBody: (_) => ListView.builder( itemCount: children.length, itemBuilder: (_, int idx) => children[idx], ), // Define a default secondaryBody. secondaryBody: (_) => Container( color: const Color.fromARGB(255, 234, 158, 192), ), // Override the default secondaryBody during the smallBreakpoint to be // empty. Must use AdaptiveScaffold.emptyBuilder to ensure it is properly // overridden. smallSecondaryBody: AdaptiveScaffold.emptyBuilder, ); } // #enddocregion Example }
packages/packages/flutter_adaptive_scaffold/example/lib/adaptive_scaffold_demo.dart/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/lib/adaptive_scaffold_demo.dart", "repo_id": "packages", "token_count": 1770 }
937
// 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 'adaptive_layout.dart'; import 'breakpoints.dart'; import 'slot_layout.dart'; /// Gutter value between different parts of the body slot depending on /// material 3 design spec. const double kMaterialGutterValue = 8; /// Margin value of the compact breakpoint layout according to the material /// design 3 spec. const double kMaterialCompactMinMargin = 8; /// Margin value of the medium breakpoint layout according to the material /// design 3 spec. const double kMaterialMediumMinMargin = 12; //// Margin value of the expanded breakpoint layout according to the material /// design 3 spec. const double kMaterialExpandedMinMargin = 32; /// Implements the basic visual layout structure for /// [Material Design 3](https://m3.material.io/foundations/adaptive-design/overview) /// that adapts to a variety of screens. /// /// !["Example of a display made with AdaptiveScaffold"](../../example/demo_files/adaptiveScaffold.gif) /// /// [AdaptiveScaffold] provides a preset of layout, including positions and /// animations, by handling macro changes in navigational elements and bodies /// based on the current features of the screen, namely screen width and platform. /// For example, the navigational elements would be a [BottomNavigationBar] on a /// small mobile device or a [Drawer] on a small desktop device and a /// [NavigationRail] on larger devices. When the app's size changes, for example /// because its window is resized, the corresponding layout transition is animated. /// The layout and navigation changes are dictated by "breakpoints" which can be /// customized or overridden. /// /// Also provides a variety of helper methods for navigational elements, /// animations, and more. /// /// [AdaptiveScaffold] is based on [AdaptiveLayout] but is easier to use at the /// cost of being less customizable. Apps that would like more refined layout /// and/or animation should use [AdaptiveLayout]. /// /// ```dart /// AdaptiveScaffold( /// destinations: const [ /// NavigationDestination(icon: Icon(Icons.inbox), label: 'Inbox'), /// NavigationDestination(icon: Icon(Icons.article), label: 'Articles'), /// NavigationDestination(icon: Icon(Icons.chat), label: 'Chat'), /// NavigationDestination(icon: Icon(Icons.video_call), label: 'Video'), /// ], /// smallBody: (_) => ListView.builder( /// itemCount: children.length, /// itemBuilder: (_, idx) => children[idx] /// ), /// body: (_) => GridView.count(crossAxisCount: 2, children: children), /// ), /// ``` /// /// See also: /// /// * [AdaptiveLayout], which is what this widget is built upon internally and /// acts as a more customizable alternative. /// * [SlotLayout], which handles switching and animations between elements /// based on [Breakpoint]s. /// * [SlotLayout.from], which holds information regarding Widgets and the /// desired way to animate between switches. Often used within [SlotLayout]. /// * [Design Doc](https://flutter.dev/go/adaptive-layout-foldables). /// * [Material Design 3 Specifications] (https://m3.material.io/foundations/adaptive-design/overview). class AdaptiveScaffold extends StatefulWidget { /// Returns a const [AdaptiveScaffold] by passing information down to an /// [AdaptiveLayout]. const AdaptiveScaffold({ super.key, required this.destinations, this.selectedIndex = 0, this.leadingUnextendedNavRail, this.leadingExtendedNavRail, this.trailingNavRail, this.smallBody, this.body, this.largeBody, this.smallSecondaryBody, this.secondaryBody, this.largeSecondaryBody, this.bodyRatio, this.smallBreakpoint = Breakpoints.small, this.mediumBreakpoint = Breakpoints.medium, this.largeBreakpoint = Breakpoints.large, this.drawerBreakpoint = Breakpoints.smallDesktop, this.internalAnimations = true, this.transitionDuration = const Duration(seconds: 1), this.bodyOrientation = Axis.horizontal, this.onSelectedIndexChange, this.useDrawer = true, this.appBar, this.navigationRailWidth = 72, this.extendedNavigationRailWidth = 192, this.appBarBreakpoint, }); /// The destinations to be used in navigation items. These are converted to /// [NavigationRailDestination]s and [BottomNavigationBarItem]s and inserted /// into the appropriate places. If passing destinations, you must also pass a /// selected index to be used by the [NavigationRail]. final List<NavigationDestination> destinations; /// The index to be used by the [NavigationRail]. final int? selectedIndex; /// Option to display a leading widget at the top of the navigation rail /// at the middle breakpoint. final Widget? leadingUnextendedNavRail; /// Option to display a leading widget at the top of the navigation rail /// at the largest breakpoint. final Widget? leadingExtendedNavRail; /// Option to display a trailing widget below the destinations of the /// navigation rail at the largest breakpoint. final Widget? trailingNavRail; /// Widget to be displayed in the body slot at the smallest breakpoint. /// /// If nothing is entered for this property, then the default [body] is /// displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? smallBody; /// Widget to be displayed in the body slot at the middle breakpoint. /// /// The default displayed body. final WidgetBuilder? body; /// Widget to be displayed in the body slot at the largest breakpoint. /// /// If nothing is entered for this property, then the default [body] is /// displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? largeBody; /// Widget to be displayed in the secondaryBody slot at the smallest /// breakpoint. /// /// If nothing is entered for this property, then the default [secondaryBody] /// is displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? smallSecondaryBody; /// Widget to be displayed in the secondaryBody slot at the middle breakpoint. /// /// The default displayed secondaryBody. final WidgetBuilder? secondaryBody; /// Widget to be displayed in the secondaryBody slot at the largest /// breakpoint. /// /// If nothing is entered for this property, then the default [secondaryBody] /// is displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? largeSecondaryBody; /// Defines the fractional ratio of body to the secondaryBody. /// /// For example 0.3 would mean body takes up 30% of the available space and /// secondaryBody takes up the rest. /// /// If this value is null, the ratio is defined so that the split axis is in /// the center of the screen. final double? bodyRatio; /// The breakpoint defined for the small size, associated with mobile-like /// features. /// /// Defaults to [Breakpoints.small]. final Breakpoint smallBreakpoint; /// The breakpoint defined for the medium size, associated with tablet-like /// features. /// /// Defaults to [Breakpoints.mediumBreakpoint]. final Breakpoint mediumBreakpoint; /// The breakpoint defined for the large size, associated with desktop-like /// features. /// /// Defaults to [Breakpoints.largeBreakpoint]. final Breakpoint largeBreakpoint; /// Whether or not the developer wants the smooth entering slide transition on /// secondaryBody. /// /// Defaults to true. final bool internalAnimations; /// Defines the duration of transition between layouts. /// /// Defaults to [Duration(seconds: 1)]. final Duration transitionDuration; /// The orientation of the body and secondaryBody. Either horizontal (side by /// side) or vertical (top to bottom). /// /// Defaults to Axis.horizontal. final Axis bodyOrientation; /// Whether to use a [Drawer] over a [BottomNavigationBar] when not on mobile /// and Breakpoint is small. /// /// Defaults to true. final bool useDrawer; /// Option to override the drawerBreakpoint for the usage of [Drawer] over the /// usual [BottomNavigationBar]. /// /// Defaults to [Breakpoints.smallDesktop]. final Breakpoint drawerBreakpoint; /// An optional [Breakpoint] which overrides the [appBar] breakpoint to display /// an [AppBar] without depending on the drawer visibility. /// /// By default, an [AppBar] will show on [Breakpoints.smallDesktop] if [useDrawer] is set /// to true. final Breakpoint? appBarBreakpoint; /// Option to override the default [AppBar] when using drawer in desktop /// small. final PreferredSizeWidget? appBar; /// Callback function for when the index of a [NavigationRail] changes. final void Function(int)? onSelectedIndexChange; /// The width used for the internal [NavigationRail] at the medium [Breakpoint]. final double navigationRailWidth; /// The width used for the internal extended [NavigationRail] at the large /// [Breakpoint]. final double extendedNavigationRailWidth; /// Callback function for when the index of a [NavigationRail] changes. static WidgetBuilder emptyBuilder = (_) => const SizedBox(); /// Public helper method to be used for creating a [NavigationRailDestination] from /// a [NavigationDestination]. static NavigationRailDestination toRailDestination( NavigationDestination destination, ) { return NavigationRailDestination( label: Text(destination.label), icon: destination.icon, selectedIcon: destination.selectedIcon, ); } /// Creates a Material 3 Design Spec abiding [NavigationRail] from a /// list of [NavigationDestination]s. /// /// Takes in a [selectedIndex] property for the current selected item in /// the [NavigationRail] and [extended] for whether the [NavigationRail] /// is extended or not. static Builder standardNavigationRail({ required List<NavigationRailDestination> destinations, double width = 72, int? selectedIndex, bool extended = false, Color? backgroundColor, EdgeInsetsGeometry padding = const EdgeInsets.all(8.0), Widget? leading, Widget? trailing, void Function(int)? onDestinationSelected, double? groupAlignment, IconThemeData? selectedIconTheme, IconThemeData? unselectedIconTheme, TextStyle? selectedLabelTextStyle, TextStyle? unSelectedLabelTextStyle, NavigationRailLabelType labelType = NavigationRailLabelType.none, }) { if (extended && width == 72) { width = 192; } return Builder(builder: (BuildContext context) { return Padding( padding: padding, child: SizedBox( width: width, height: MediaQuery.of(context).size.height, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints(minHeight: constraints.maxHeight), child: IntrinsicHeight( child: NavigationRail( labelType: labelType, leading: leading, trailing: trailing, onDestinationSelected: onDestinationSelected, groupAlignment: groupAlignment, backgroundColor: backgroundColor, extended: extended, selectedIndex: selectedIndex, selectedIconTheme: selectedIconTheme, unselectedIconTheme: unselectedIconTheme, selectedLabelTextStyle: selectedLabelTextStyle, unselectedLabelTextStyle: unSelectedLabelTextStyle, destinations: destinations, ), ), ), ); }, ), ), ); }); } /// Public helper method to be used for creating a [BottomNavigationBar] from /// a list of [NavigationDestination]s. static Builder standardBottomNavigationBar({ required List<NavigationDestination> destinations, int? currentIndex, double iconSize = 24, ValueChanged<int>? onDestinationSelected, }) { return Builder( builder: (BuildContext context) { final NavigationBarThemeData currentNavBarTheme = NavigationBarTheme.of(context); return NavigationBarTheme( data: currentNavBarTheme.copyWith( iconTheme: MaterialStateProperty.resolveWith( (Set<MaterialState> states) { return currentNavBarTheme.iconTheme ?.resolve(states) ?.copyWith(size: iconSize) ?? IconTheme.of(context).copyWith(size: iconSize); }, ), ), child: MediaQuery( data: MediaQuery.of(context).removePadding(removeTop: true), child: NavigationBar( selectedIndex: currentIndex ?? 0, destinations: destinations, onDestinationSelected: onDestinationSelected, ), ), ); }, ); } /// Public helper method to be used for creating a staggered grid following m3 /// specs from a list of [Widget]s static Builder toMaterialGrid({ List<Widget> thisWidgets = const <Widget>[], List<Breakpoint> breakpoints = const <Breakpoint>[ Breakpoints.small, Breakpoints.medium, Breakpoints.large, ], double margin = 8, int itemColumns = 1, required BuildContext context, }) { return Builder(builder: (BuildContext context) { Breakpoint? currentBreakpoint; for (final Breakpoint breakpoint in breakpoints) { if (breakpoint.isActive(context)) { currentBreakpoint = breakpoint; } } double? thisMargin = margin; if (currentBreakpoint == Breakpoints.small) { if (thisMargin < kMaterialCompactMinMargin) { thisMargin = kMaterialCompactMinMargin; } } else if (currentBreakpoint == Breakpoints.medium) { if (thisMargin < kMaterialMediumMinMargin) { thisMargin = kMaterialMediumMinMargin; } } else if (currentBreakpoint == Breakpoints.large) { if (thisMargin < kMaterialExpandedMinMargin) { thisMargin = kMaterialExpandedMinMargin; } } return CustomScrollView( primary: false, controller: ScrollController(), shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter( child: Padding( padding: EdgeInsets.all(thisMargin), child: _BrickLayout( columns: itemColumns, columnSpacing: kMaterialGutterValue, itemPadding: const EdgeInsets.only(bottom: kMaterialGutterValue), children: thisWidgets, ), ), ), ], ); }); } /// Animation from bottom offscreen up onto the screen. static AnimatedWidget bottomToTop(Widget child, Animation<double> animation) { return SlideTransition( position: Tween<Offset>( begin: const Offset(0, 1), end: Offset.zero, ).animate(animation), child: child, ); } /// Animation from on the screen down off the screen. static AnimatedWidget topToBottom(Widget child, Animation<double> animation) { return SlideTransition( position: Tween<Offset>( begin: Offset.zero, end: const Offset(0, 1), ).animate(animation), child: child, ); } /// Animation from left off the screen into the screen. static AnimatedWidget leftOutIn(Widget child, Animation<double> animation) { return SlideTransition( position: Tween<Offset>( begin: const Offset(-1, 0), end: Offset.zero, ).animate(animation), child: child, ); } /// Animation from on screen to left off screen. static AnimatedWidget leftInOut(Widget child, Animation<double> animation) { return SlideTransition( position: Tween<Offset>( begin: Offset.zero, end: const Offset(-1, 0), ).animate(animation), child: child, ); } /// Animation from right off screen to on screen. static AnimatedWidget rightOutIn(Widget child, Animation<double> animation) { return SlideTransition( position: Tween<Offset>( begin: const Offset(1, 0), end: Offset.zero, ).animate(animation), child: child, ); } /// Fade in animation. static Widget fadeIn(Widget child, Animation<double> animation) { return FadeTransition( opacity: CurvedAnimation(parent: animation, curve: Curves.easeInCubic), child: child, ); } /// Fade out animation. static Widget fadeOut(Widget child, Animation<double> animation) { return FadeTransition( opacity: CurvedAnimation( parent: ReverseAnimation(animation), curve: Curves.easeInCubic, ), child: child, ); } /// Keep widget on screen while it is leaving static Widget stayOnScreen(Widget child, Animation<double> animation) { return FadeTransition( opacity: Tween<double>(begin: 1.0, end: 1.0).animate(animation), child: child, ); } @override State<AdaptiveScaffold> createState() => _AdaptiveScaffoldState(); } class _AdaptiveScaffoldState extends State<AdaptiveScaffold> { @override Widget build(BuildContext context) { final NavigationRailThemeData navRailTheme = Theme.of(context).navigationRailTheme; return Scaffold( appBar: widget.drawerBreakpoint.isActive(context) && widget.useDrawer || (widget.appBarBreakpoint?.isActive(context) ?? false) ? widget.appBar ?? AppBar() : null, drawer: widget.drawerBreakpoint.isActive(context) && widget.useDrawer ? Drawer( child: NavigationRail( extended: true, leading: widget.leadingExtendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((NavigationDestination destination) => AdaptiveScaffold.toRailDestination(destination)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, ), ) : null, body: AdaptiveLayout( transitionDuration: widget.transitionDuration, bodyOrientation: widget.bodyOrientation, bodyRatio: widget.bodyRatio, internalAnimations: widget.internalAnimations, primaryNavigation: SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ widget.mediumBreakpoint: SlotLayout.from( key: const Key('primaryNavigation'), builder: (_) => AdaptiveScaffold.standardNavigationRail( width: widget.navigationRailWidth, leading: widget.leadingUnextendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((NavigationDestination destination) => AdaptiveScaffold.toRailDestination(destination)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, backgroundColor: navRailTheme.backgroundColor, selectedIconTheme: navRailTheme.selectedIconTheme, unselectedIconTheme: navRailTheme.unselectedIconTheme, selectedLabelTextStyle: navRailTheme.selectedLabelTextStyle, unSelectedLabelTextStyle: navRailTheme.unselectedLabelTextStyle, ), ), widget.largeBreakpoint: SlotLayout.from( key: const Key('primaryNavigation1'), builder: (_) => AdaptiveScaffold.standardNavigationRail( width: widget.extendedNavigationRailWidth, extended: true, leading: widget.leadingExtendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((NavigationDestination destination) => AdaptiveScaffold.toRailDestination(destination)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, backgroundColor: navRailTheme.backgroundColor, selectedIconTheme: navRailTheme.selectedIconTheme, unselectedIconTheme: navRailTheme.unselectedIconTheme, selectedLabelTextStyle: navRailTheme.selectedLabelTextStyle, unSelectedLabelTextStyle: navRailTheme.unselectedLabelTextStyle, ), ), }, ), bottomNavigation: !widget.drawerBreakpoint.isActive(context) || !widget.useDrawer ? SlotLayout( config: <Breakpoint, SlotLayoutConfig>{ widget.smallBreakpoint: SlotLayout.from( key: const Key('bottomNavigation'), builder: (_) => AdaptiveScaffold.standardBottomNavigationBar( currentIndex: widget.selectedIndex, destinations: widget.destinations, onDestinationSelected: widget.onSelectedIndexChange, ), ), }, ) : null, body: SlotLayout( config: <Breakpoint, SlotLayoutConfig?>{ Breakpoints.standard: SlotLayout.from( key: const Key('body'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.body, ), if (widget.smallBody != null) widget.smallBreakpoint: (widget.smallBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('smallBody'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.smallBody, ) : null, if (widget.body != null) widget.mediumBreakpoint: (widget.body != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('body'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.body, ) : null, if (widget.largeBody != null) widget.largeBreakpoint: (widget.largeBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('largeBody'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.largeBody, ) : null, }, ), secondaryBody: SlotLayout( config: <Breakpoint, SlotLayoutConfig?>{ Breakpoints.standard: SlotLayout.from( key: const Key('sBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.secondaryBody, ), if (widget.smallSecondaryBody != null) widget.smallBreakpoint: (widget.smallSecondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('smallSBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.smallSecondaryBody, ) : null, if (widget.secondaryBody != null) widget.mediumBreakpoint: (widget.secondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('sBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.secondaryBody, ) : null, if (widget.largeSecondaryBody != null) widget.largeBreakpoint: (widget.largeSecondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('largeSBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.largeSecondaryBody, ) : null, }, ), ), ); } } class _BrickLayout extends StatelessWidget { const _BrickLayout({ this.columns = 1, this.itemPadding = EdgeInsets.zero, this.columnSpacing = 0, required this.children, }); final int columns; final double columnSpacing; final EdgeInsetsGeometry itemPadding; final List<Widget> children; @override Widget build(BuildContext context) { int i = -1; return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Expanded( child: CustomMultiChildLayout( delegate: _BrickLayoutDelegate( columns: columns, columnSpacing: columnSpacing, itemPadding: itemPadding, ), children: children .map<Widget>( (Widget child) => LayoutId(id: i += 1, child: child), ) .toList(), ), ), ], ); } } class _BrickLayoutDelegate extends MultiChildLayoutDelegate { _BrickLayoutDelegate({ this.columns = 1, this.columnSpacing = 0, this.itemPadding = EdgeInsets.zero, }); final int columns; final EdgeInsetsGeometry itemPadding; final double columnSpacing; @override void performLayout(Size size) { final BoxConstraints looseConstraints = BoxConstraints.loose(size); final BoxConstraints fullWidthConstraints = looseConstraints.tighten(width: size.width); final List<Size> childSizes = <Size>[]; int childCount = 0; // Count how many children we have. for (; hasChild(childCount); childCount += 1) {} final BoxConstraints itemConstraints = BoxConstraints( maxWidth: fullWidthConstraints.maxWidth / columns - columnSpacing / 2 - itemPadding.horizontal, ); for (int i = 0; i < childCount; i += 1) { childSizes.add(layoutChild(i, itemConstraints)); } int columnIndex = 0; int childId = 0; final double totalColumnSpacing = columnSpacing * (columns - 1); final double columnWidth = (size.width - totalColumnSpacing) / columns; final double topPadding = itemPadding.resolve(TextDirection.ltr).top; final List<double> columnUsage = List<double>.generate(columns, (int index) => topPadding); for (final Size childSize in childSizes) { positionChild( childId, Offset( columnSpacing * columnIndex + columnWidth * columnIndex + (columnWidth - childSize.width) / 2, columnUsage[columnIndex], ), ); columnUsage[columnIndex] += childSize.height + itemPadding.vertical; columnIndex = (columnIndex + 1) % columns; childId += 1; } } @override bool shouldRelayout(_BrickLayoutDelegate oldDelegate) { return itemPadding != oldDelegate.itemPadding || columnSpacing != oldDelegate.columnSpacing; } }
packages/packages/flutter_adaptive_scaffold/lib/src/adaptive_scaffold.dart/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/lib/src/adaptive_scaffold.dart", "repo_id": "packages", "token_count": 11378 }
938
# flutter_image_example Demonstrates how to use the flutter_image package.
packages/packages/flutter_image/example/README.md/0
{ "file_path": "packages/packages/flutter_image/example/README.md", "repo_id": "packages", "token_count": 23 }
939
name: flutter_image_example description: flutter_image_example publish_to: "none" version: 1.0.0+1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: cupertino_icons: ^1.0.2 flutter: sdk: flutter flutter_image: path: "../" dev_dependencies: flutter_lints: ^2.0.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/flutter_image/example/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_image/example/pubspec.yaml", "repo_id": "packages", "token_count": 183 }
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 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import '../shared/dropdown_menu.dart' as dropdown; import '../shared/markdown_demo_widget.dart'; import '../shared/markdown_extensions.dart'; // ignore_for_file: public_member_api_docs const String _notes = """ # Basic Markdown Demo --- The Basic Markdown Demo shows the effect of the four Markdown extension sets on formatting basic and extended Markdown tags. ## Overview The Dart [markdown](https://pub.dev/packages/markdown) package parses Markdown into HTML. The flutter_markdown package builds on this package using the abstract syntax tree generated by the parser to make a tree of widgets instead of HTML elements. The markdown package supports the basic block and inline Markdown syntax specified in the original Markdown implementation as well as a few Markdown extensions. The markdown package uses extension sets to make extension management easy. There are four pre-defined extension sets; none, Common Mark, GitHub Flavored, and GitHub Web. The default extension set used by the flutter_markdown package is GitHub Flavored. The Basic Markdown Demo shows the effect each of the pre-defined extension sets has on a test Markdown document with basic and extended Markdown tags. Use the Extension Set dropdown menu to select an extension set and view the Markdown widget's output. ## Comments Since GitHub Flavored is the default extension set, it is the initial setting for the formatted Markdown view in the demo. """; // TODO(goderbauer): Restructure the examples to avoid this ignore, https://github.com/flutter/flutter/issues/110208. // ignore: avoid_implementing_value_types class BasicMarkdownDemo extends StatefulWidget implements MarkdownDemoWidget { const BasicMarkdownDemo({super.key}); static const String _title = 'Basic Markdown Demo'; @override String get title => BasicMarkdownDemo._title; @override String get description => 'Shows the effect the four Markdown extension sets ' 'have on basic and extended Markdown tagged elements.'; @override Future<String> get data => rootBundle.loadString('assets/markdown_test_page.md'); @override Future<String> get notes => Future<String>.value(_notes); @override State<BasicMarkdownDemo> createState() => _BasicMarkdownDemoState(); } class _BasicMarkdownDemoState extends State<BasicMarkdownDemo> { MarkdownExtensionSet _extensionSet = MarkdownExtensionSet.githubFlavored; final Map<String, MarkdownExtensionSet> _menuItems = Map<String, MarkdownExtensionSet>.fromIterables( MarkdownExtensionSet.values.map((MarkdownExtensionSet e) => e.displayTitle), MarkdownExtensionSet.values, ); @override Widget build(BuildContext context) { return FutureBuilder<String>( future: widget.data, builder: (BuildContext context, AsyncSnapshot<String> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Column( children: <Widget>[ dropdown.DropdownMenu<MarkdownExtensionSet>( items: _menuItems, label: 'Extension Set:', initialValue: _extensionSet, onChanged: (MarkdownExtensionSet? value) { if (value != _extensionSet) { setState(() { _extensionSet = value!; }); } }, ), Expanded( child: Markdown( key: Key(_extensionSet.name), data: snapshot.data!, imageDirectory: 'https://raw.githubusercontent.com', extensionSet: _extensionSet.value, onTapLink: (String text, String? href, String title) => linkOnTapHandler(context, text, href, title), ), ), ], ); } else { return const CircularProgressIndicator(); } }, ); } // Handle the link. The [href] in the callback contains information // from the link. The url_launcher package or other similar package // can be used to execute the link. Future<void> linkOnTapHandler( BuildContext context, String text, String? href, String title, ) async { unawaited(showDialog<Widget>( context: context, builder: (BuildContext context) => _createDialog(context, text, href, title), )); } Widget _createDialog( BuildContext context, String text, String? href, String title) => AlertDialog( title: const Text('Reference Link'), content: SingleChildScrollView( child: ListBody( children: <Widget>[ Text( 'See the following link for more information:', style: Theme.of(context).textTheme.bodyLarge, ), const SizedBox(height: 8), Text( 'Link text: $text', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 8), Text( 'Link destination: $href', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 8), Text( 'Link title: $title', style: Theme.of(context).textTheme.bodyMedium, ), ], ), ), actions: <Widget>[ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('OK'), ) ], ); }
packages/packages/flutter_markdown/example/lib/demos/basic_markdown_demo.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/demos/basic_markdown_demo.dart", "repo_id": "packages", "token_count": 2347 }
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 'blockquote_test.dart' as blockquote_test; import 'custom_syntax_test.dart' as custome_syntax_test; import 'emphasis_test.dart' as emphasis_test; import 'footnote_test.dart' as footnote_test; import 'header_test.dart' as header_test; import 'horizontal_rule_test.dart' as horizontal_rule_test; import 'html_test.dart' as html_test; import 'image_test.dart' as image_test; import 'line_break_test.dart' as line_break_test; import 'link_test.dart' as link_test; import 'list_test.dart' as list_test; import 'scrollable_test.dart' as scrollable_test; import 'selection_area_compatibility_test.dart' as selection_area_test; import 'style_sheet_test.dart' as style_sheet_test; import 'table_test.dart' as table_test; import 'text_alignment_test.dart' as text_alignment_test; import 'text_scaler_test.dart' as text_scaler; import 'text_test.dart' as text_test; import 'uri_test.dart' as uri_test; void main() { blockquote_test.defineTests(); custome_syntax_test.defineTests(); emphasis_test.defineTests(); footnote_test.defineTests(); header_test.defineTests(); horizontal_rule_test.defineTests(); html_test.defineTests(); image_test.defineTests(); line_break_test.defineTests(); link_test.defineTests(); list_test.defineTests(); scrollable_test.defineTests(); selection_area_test.defineTests(); style_sheet_test.defineTests(); table_test.defineTests(); text_test.defineTests(); text_alignment_test.defineTests(); text_scaler.defineTests(); uri_test.defineTests(); }
packages/packages/flutter_markdown/test/all.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/all.dart", "repo_id": "packages", "token_count": 587 }
942
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Unordered List', () { testWidgets( 'simple 3 item list', (WidgetTester tester) async { const String data = '- Item 1\n- Item 2\n- Item 3'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '•', 'Item 1', '•', 'Item 2', '•', 'Item 3', ]); }, ); testWidgets( 'empty list item', (WidgetTester tester) async { const String data = '- \n- Item 2\n- Item 3'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '•', '•', 'Item 2', '•', 'Item 3', ]); }, ); testWidgets( // Example 236 from the GitHub Flavored Markdown specification. 'leading space are ignored', (WidgetTester tester) async { const String data = ' - one\n\n two'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '•', 'one', 'two', ]); }); testWidgets( 'leading spaces are ignored (non-paragraph test case)', (WidgetTester tester) async { const String data = '- one\n- two\n- three'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '•', 'one', '•', 'two', '•', 'three', ]); }, ); }); group('Ordered List', () { testWidgets( '2 distinct ordered lists with separate index values', (WidgetTester tester) async { const String data = '1. Item 1\n1. Item 2\n2. Item 3\n\n\n' '10. Item 10\n13. Item 11'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '1.', 'Item 1', '2.', 'Item 2', '3.', 'Item 3', '4.', 'Item 10', '5.', 'Item 11' ]); }, ); testWidgets('leading space are ignored', (WidgetTester tester) async { const String data = ' 1. one\n\n two'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>['1.', 'one', 'two']); }); }); group('Task List', () { testWidgets( 'simple 2 item task list', (WidgetTester tester) async { const String data = '- [x] Item 1\n- [ ] Item 2'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ String.fromCharCode(Icons.check_box.codePoint), 'Item 1', String.fromCharCode(Icons.check_box_outline_blank.codePoint), 'Item 2', ]); }, ); testWidgets('custom bullet builder', (WidgetTester tester) async { const String data = '* Item 1\n* Item 2\n1) Item 3\n2) Item 4'; Widget builder(int index, BulletStyle style) => Text( '$index ${style == BulletStyle.orderedList ? 'ordered' : 'unordered'}'); await tester.pumpWidget( boilerplate( Markdown(data: data, bulletBuilder: builder), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ '0 unordered', 'Item 1', '1 unordered', 'Item 2', '0 ordered', 'Item 3', '1 ordered', 'Item 4', ]); }); testWidgets( 'custom checkbox builder', (WidgetTester tester) async { const String data = '- [x] Item 1\n- [ ] Item 2'; Widget builder(bool checked) => Text('$checked'); await tester.pumpWidget( boilerplate( Markdown(data: data, checkboxBuilder: builder), ), ); final Iterable<Widget> widgets = tester.allWidgets; expectTextStrings(widgets, <String>[ 'true', 'Item 1', 'false', 'Item 2', ]); }, ); }); group('fitContent', () { testWidgets( 'uses maximum width when false', (WidgetTester tester) async { const String data = '- Foo\n- Bar'; await tester.pumpWidget( boilerplate( const Column( children: <Widget>[ MarkdownBody(fitContent: false, data: data), ], ), ), ); final double screenWidth = find.byType(Column).evaluate().first.size!.width; final double markdownBodyWidth = find.byType(MarkdownBody).evaluate().single.size!.width; expect(markdownBodyWidth, equals(screenWidth)); }, ); testWidgets( 'uses minimum width when true', (WidgetTester tester) async { const String data = '- Foo\n- Bar'; await tester.pumpWidget( boilerplate( const Column( children: <Widget>[ MarkdownBody(data: data), ], ), ), ); final double screenWidth = find.byType(Column).evaluate().first.size!.width; final double markdownBodyWidth = find.byType(MarkdownBody).evaluate().single.size!.width; expect(markdownBodyWidth, lessThan(screenWidth)); }, ); }); }
packages/packages/flutter_markdown/test/list_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/list_test.dart", "repo_id": "packages", "token_count": 3267 }
943
# Flutter Migrate ## Overview This is a tool that helps migrate legacy Flutter projects generated with old version of Flutter to modern Flutter templates. This allows old apps to access new features, update key dependenices and prevent slow bitrot of projects over time without domain knowledge of individual platforms like Android and iOS. ## Prerequisites This tool supports migrating apps generated with Flutter 1.0.0 and newer. However, projects generated with older versions of Flutter (beta, alpha, etc) may still be compatible with this tool, but results may vary and official support will not be provided. Projects that contain heavy modifications to the project's platform directories (eg, `android/`, `ios/`, `linux/`) may result in many conflicts. Currently, only full Flutter apps are supported. This tool will not work properly with plugins, or add-to-app Flutter apps. The project must be a git repository with no uncommitted changes. Git is used to revert any migrations that are broken. ## Usage To run the tool enter the root directory of your flutter project and run: `dart run <path_to_flutter_migrate_package>/bin/flutter_migrate.dart <subcommand> [parameters]` The core subcommand sequence to use is `start`, `apply`. * `start` will generate a migration that will be staged in the `migration_staging_directory` in your project home. This command may take some time to complete depending on network speed. The generated migration may have conflicts that should be manually resolved or resolved with the `resolve-conflicts` subcommand. * `apply` will apply staged changes to the actual project. Any merge conflicts should be resolved in the staging directory before applying These additional commands help you manage and navigate the migration: * `status` Prints the diffs of the staged changes as well as a list of the files with changes. Any files with conflicts will also be highlighted. * `abandon` Abandons the existing migration by deleting the staging directory. * `resolve-conflicts` Wizard that assists in resolving routine conflicts. The wizard will routinely show each conflict where the option to keep the old code, new code, or skip and resolve manually are presented.
packages/packages/flutter_migrate/README.md/0
{ "file_path": "packages/packages/flutter_migrate/README.md", "repo_id": "packages", "token_count": 531 }
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:process/process.dart'; import '../base/command.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/project.dart'; import '../base/terminal.dart'; import '../environment.dart'; import '../flutter_project_metadata.dart'; import '../manifest.dart'; import '../update_locks.dart'; import '../utils.dart'; /// Migrate subcommand that checks the migrate working directory for unresolved conflicts and /// applies the staged changes to the project. class MigrateApplyCommand extends MigrateCommand { MigrateApplyCommand({ bool verbose = false, required this.logger, required this.fileSystem, required this.terminal, required ProcessManager processManager, this.standalone = false, }) : _verbose = verbose, _processManager = processManager, migrateUtils = MigrateUtils( logger: logger, fileSystem: fileSystem, processManager: processManager, ) { argParser.addOption( 'staging-directory', help: 'Specifies the custom migration working directory used to stage ' 'and edit proposed changes. This path can be absolute or relative ' 'to the flutter project root. This defaults to ' '`$kDefaultMigrateStagingDirectoryName`', valueHelp: 'path', ); argParser.addOption( 'project-directory', help: 'The root directory of the flutter project. This defaults to the ' 'current working directory if omitted.', valueHelp: 'path', ); argParser.addFlag( 'force', abbr: 'f', help: 'Ignore unresolved merge conflicts and uncommitted changes and ' 'apply staged changes by force.', ); argParser.addFlag( 'keep-working-directory', help: 'Do not delete the working directory.', ); 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 ProcessManager _processManager; final Logger logger; final FileSystem fileSystem; final Terminal terminal; final MigrateUtils migrateUtils; final bool standalone; @override final String name = 'apply'; @override final String description = r'Accepts the changes produced by `$ flutter ' 'migrate start` and copies the changed files into ' 'your project files. All merge conflicts should ' 'be resolved before apply will complete ' 'successfully. If conflicts still exist, this ' 'command will print the remaining conflicted files.'; @override Future<CommandResult> runCommand() async { final String? projectDirectory = stringArg('project-directory'); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); final FlutterProject project = projectDirectory == null ? FlutterProject.current(fileSystem) : flutterProjectFactory .fromDirectory(fileSystem.directory(projectDirectory)); final FlutterToolsEnvironment environment = await FlutterToolsEnvironment.initializeFlutterToolsEnvironment( _processManager, logger); final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; if (!validateWorkingDirectory(project, logger)) { return CommandResult.fail(); } if (!await gitRepoExists(project.directory.path, logger, migrateUtils)) { logger.printStatus('No git repo found. Please run in a project with an ' 'initialized git repo or initialize one with:'); printCommand('git init', logger); return const CommandResult(ExitStatus.fail); } final bool force = boolArg('force') ?? false; 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( 'No migration in progress at $stagingDirectory. Please run:'); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } final File manifestFile = MigrateManifest.getManifestFileFromDirectory(stagingDirectory); final MigrateManifest manifest = MigrateManifest.fromFile(manifestFile); if (!checkAndPrintMigrateStatus(manifest, stagingDirectory, warnConflict: true, logger: logger) && !force) { logger.printStatus( 'Conflicting files found. Resolve these conflicts and try again.'); logger.printStatus('Guided conflict resolution wizard:'); printCommandText('resolve-conflicts', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } if (await hasUncommittedChanges( project.directory.path, logger, migrateUtils) && !force) { return const CommandResult(ExitStatus.fail); } logger.printStatus('Applying migration.'); // Copy files from working directory to project root final List<String> allFilesToCopy = <String>[]; allFilesToCopy.addAll(manifest.mergedFiles); allFilesToCopy.addAll(manifest.conflictFiles); allFilesToCopy.addAll(manifest.addedFiles); if (allFilesToCopy.isNotEmpty && _verbose) { logger.printStatus('Modifying ${allFilesToCopy.length} files.', indent: 2); } for (final String localPath in allFilesToCopy) { if (_verbose) { logger.printStatus('Writing $localPath'); } final File workingFile = stagingDirectory.childFile(localPath); final File targetFile = project.directory.childFile(localPath); if (!workingFile.existsSync()) { continue; } if (!targetFile.existsSync()) { targetFile.createSync(recursive: true); } try { targetFile.writeAsStringSync(workingFile.readAsStringSync(), flush: true); } on FileSystemException { targetFile.writeAsBytesSync(workingFile.readAsBytesSync(), flush: true); } } // Delete files slated for deletion. if (manifest.deletedFiles.isNotEmpty) { logger.printStatus('Deleting ${manifest.deletedFiles.length} files.', indent: 2); } for (final String localPath in manifest.deletedFiles) { final File targetFile = project.directory.childFile(localPath); targetFile.deleteSync(); } // Update the migrate config files to reflect latest migration. if (_verbose) { logger.printStatus('Updating .migrate_configs'); } final FlutterProjectMetadata metadata = FlutterProjectMetadata( project.directory.childFile('.metadata'), logger); final String currentGitHash = environment.getString('FlutterVersion.frameworkRevision') ?? ''; metadata.migrateConfig.populate( projectDirectory: project.directory, currentRevision: currentGitHash, logger: logger, ); // Clean up the working directory final bool keepWorkingDirectory = boolArg('keep-working-directory') ?? false; if (!keepWorkingDirectory) { stagingDirectory.deleteSync(recursive: true); } // Detect pub dependency locking. Run flutter pub upgrade --major-versions await updatePubspecDependencies(project, migrateUtils, logger, terminal); // Detect gradle lockfiles in android directory. Delete lockfiles and regenerate with ./gradlew tasks (any gradle task that requires a build). await updateGradleDependencyLocking( project, migrateUtils, logger, terminal, _verbose, fileSystem); logger.printStatus('Migration complete. You may use commands like `git ' 'status`, `git diff` and `git restore <file>` to continue ' 'working with the migrated files.'); return const CommandResult(ExitStatus.success); } }
packages/packages/flutter_migrate/lib/src/commands/apply.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/commands/apply.dart", "repo_id": "packages", "token_count": 2877 }
945
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:file/memory.dart'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_migrate/src/base/common.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/io.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/base/signals.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; class LocalFileSystemFake extends LocalFileSystem { LocalFileSystemFake.test({required super.signals}) : super.test(); @override Directory get superSystemTempDirectory => directory('/does_not_exist'); } void main() { group('fsUtils', () { late MemoryFileSystem fs; late FileSystemUtils fsUtils; setUp(() { fs = MemoryFileSystem.test(); fsUtils = FileSystemUtils( fileSystem: fs, ); }); testWithoutContext('getUniqueFile creates a unique file name', () async { final File fileA = fsUtils.getUniqueFile( fs.currentDirectory, 'foo', 'json') ..createSync(); final File fileB = fsUtils.getUniqueFile(fs.currentDirectory, 'foo', 'json'); expect(fileA.path, '/foo_01.json'); expect(fileB.path, '/foo_02.json'); }); testWithoutContext('getUniqueDirectory creates a unique directory name', () async { final Directory directoryA = fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo')..createSync(); final Directory directoryB = fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo'); expect(directoryA.path, '/foo_01'); expect(directoryB.path, '/foo_02'); }); }); group('copyDirectorySync', () { /// Test file_systems.copyDirectorySync() using MemoryFileSystem. /// Copies between 2 instances of file systems which is also supported by copyDirectorySync(). testWithoutContext('test directory copy', () async { final MemoryFileSystem sourceMemoryFs = MemoryFileSystem.test(); const String sourcePath = '/some/origin'; final Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true); sourceMemoryFs.currentDirectory = sourcePath; final File sourceFile1 = sourceMemoryFs.file('some_file.txt') ..writeAsStringSync('bleh'); final DateTime writeTime = sourceFile1.lastModifiedSync(); sourceMemoryFs .file('sub_dir/another_file.txt') .createSync(recursive: true); sourceMemoryFs.directory('empty_directory').createSync(); // Copy to another memory file system instance. final MemoryFileSystem targetMemoryFs = MemoryFileSystem.test(); const String targetPath = '/some/non-existent/target'; final Directory targetDirectory = targetMemoryFs.directory(targetPath); copyDirectory(sourceDirectory, targetDirectory); expect(targetDirectory.existsSync(), true); targetMemoryFs.currentDirectory = targetPath; expect(targetMemoryFs.directory('empty_directory').existsSync(), true); expect( targetMemoryFs.file('sub_dir/another_file.txt').existsSync(), true); expect(targetMemoryFs.file('some_file.txt').readAsStringSync(), 'bleh'); // Assert that the copy operation hasn't modified the original file in some way. expect( sourceMemoryFs.file('some_file.txt').lastModifiedSync(), writeTime); // There's still 3 things in the original directory as there were initially. expect(sourceMemoryFs.directory(sourcePath).listSync().length, 3); }); testWithoutContext('Skip files if shouldCopyFile returns false', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Directory origin = fileSystem.directory('/origin'); origin.createSync(); fileSystem .file(fileSystem.path.join('origin', 'a.txt')) .writeAsStringSync('irrelevant'); fileSystem.directory('/origin/nested').createSync(); fileSystem .file(fileSystem.path.join('origin', 'nested', 'a.txt')) .writeAsStringSync('irrelevant'); fileSystem .file(fileSystem.path.join('origin', 'nested', 'b.txt')) .writeAsStringSync('irrelevant'); final Directory destination = fileSystem.directory('/destination'); copyDirectory(origin, destination, shouldCopyFile: (File origin, File dest) { return origin.basename == 'b.txt'; }); expect(destination.existsSync(), isTrue); expect(destination.childDirectory('nested').existsSync(), isTrue); expect( destination.childDirectory('nested').childFile('b.txt').existsSync(), isTrue); expect(destination.childFile('a.txt').existsSync(), isFalse); expect( destination.childDirectory('nested').childFile('a.txt').existsSync(), isFalse); }); testWithoutContext('Skip directories if shouldCopyDirectory returns false', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Directory origin = fileSystem.directory('/origin'); origin.createSync(); fileSystem .file(fileSystem.path.join('origin', 'a.txt')) .writeAsStringSync('irrelevant'); fileSystem.directory('/origin/nested').createSync(); fileSystem .file(fileSystem.path.join('origin', 'nested', 'a.txt')) .writeAsStringSync('irrelevant'); fileSystem .file(fileSystem.path.join('origin', 'nested', 'b.txt')) .writeAsStringSync('irrelevant'); final Directory destination = fileSystem.directory('/destination'); copyDirectory(origin, destination, shouldCopyDirectory: (Directory directory) { return !directory.path.endsWith('nested'); }); expect(destination, exists); expect(destination.childDirectory('nested'), isNot(exists)); expect(destination.childDirectory('nested').childFile('b.txt'), isNot(exists)); }); }); group('LocalFileSystem', () { late FakeProcessSignal fakeSignal; late ProcessSignal signalUnderTest; setUp(() { fakeSignal = FakeProcessSignal(); signalUnderTest = ProcessSignal(fakeSignal); }); testWithoutContext('runs shutdown hooks', () async { final Signals signals = Signals.test(); final LocalFileSystem localFileSystem = LocalFileSystem.test( signals: signals, ); final Directory temp = localFileSystem.systemTempDirectory; expect(temp.existsSync(), isTrue); expect(localFileSystem.shutdownHooks.registeredHooks, hasLength(1)); final BufferLogger logger = BufferLogger.test(); await localFileSystem.shutdownHooks.runShutdownHooks(logger); expect(temp.existsSync(), isFalse); expect(logger.traceText, contains('Running 1 shutdown hook')); }); testWithoutContext('deletes system temp entry on a fatal signal', () async { final Completer<void> completer = Completer<void>(); final Signals signals = Signals.test(); final LocalFileSystem localFileSystem = LocalFileSystem.test( signals: signals, fatalSignals: <ProcessSignal>[signalUnderTest], ); final Directory temp = localFileSystem.systemTempDirectory; signals.addHandler(signalUnderTest, (ProcessSignal s) { completer.complete(); }); expect(temp.existsSync(), isTrue); fakeSignal.controller.add(fakeSignal); await completer.future; expect(temp.existsSync(), isFalse); }); testWithoutContext('throwToolExit when temp not found', () async { final Signals signals = Signals.test(); final LocalFileSystemFake localFileSystem = LocalFileSystemFake.test( signals: signals, ); try { localFileSystem.systemTempDirectory; fail('expected tool exit'); } on ToolExit catch (e) { expect( e.message, 'Your system temp directory (/does_not_exist) does not exist. ' 'Did you set an invalid override in your environment? ' 'See issue https://github.com/flutter/flutter/issues/74042 for more context.'); } }); }); } class FakeProcessSignal extends Fake implements io.ProcessSignal { final StreamController<io.ProcessSignal> controller = StreamController<io.ProcessSignal>(); @override Stream<io.ProcessSignal> watch() => controller.stream; } /// Various convenience file system methods. class FileSystemUtils { FileSystemUtils({ required FileSystem fileSystem, }) : _fileSystem = fileSystem; final FileSystem _fileSystem; /// Appends a number to a filename in order to make it unique under a /// directory. File getUniqueFile(Directory dir, String baseName, String ext) { final FileSystem fs = dir.fileSystem; int i = 1; while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext'; final File file = fs.file(dir.fileSystem.path.join(dir.path, name)); if (!file.existsSync()) { file.createSync(recursive: true); return file; } i += 1; } } // /// Appends a number to a filename in order to make it unique under a // /// directory. // File getUniqueFile(Directory dir, String baseName, String ext) { // return _getUniqueFile(dir, baseName, ext); // } /// Appends a number to a directory name in order to make it unique under a /// directory. Directory getUniqueDirectory(Directory dir, String baseName) { final FileSystem fs = dir.fileSystem; int i = 1; while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}'; final Directory directory = fs.directory(_fileSystem.path.join(dir.path, name)); if (!directory.existsSync()) { return directory; } i += 1; } } } /// Creates `destDir` if needed, then recursively copies `srcDir` to /// `destDir`, invoking [onFileCopied], if specified, for each /// source/destination file pair. /// /// Skips files if [shouldCopyFile] returns `false`. /// Does not recurse over directories if [shouldCopyDirectory] returns `false`. void copyDirectory( Directory srcDir, Directory destDir, { bool Function(File srcFile, File destFile)? shouldCopyFile, bool Function(Directory)? shouldCopyDirectory, void Function(File srcFile, File destFile)? onFileCopied, }) { if (!srcDir.existsSync()) { throw Exception( 'Source directory "${srcDir.path}" does not exist, nothing to copy'); } if (!destDir.existsSync()) { destDir.createSync(recursive: true); } for (final FileSystemEntity entity in srcDir.listSync()) { final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename); if (entity is Link) { final Link newLink = destDir.fileSystem.link(newPath); newLink.createSync(entity.targetSync()); } else if (entity is File) { final File newFile = destDir.fileSystem.file(newPath); if (shouldCopyFile != null && !shouldCopyFile(entity, newFile)) { continue; } newFile.writeAsBytesSync(entity.readAsBytesSync()); onFileCopied?.call(entity, newFile); } else if (entity is Directory) { if (shouldCopyDirectory != null && !shouldCopyDirectory(entity)) { continue; } copyDirectory( entity, destDir.fileSystem.directory(newPath), shouldCopyFile: shouldCopyFile, onFileCopied: onFileCopied, ); } else { throw Exception( '${entity.path} is neither File nor Directory, was ${entity.runtimeType}'); } } }
packages/packages/flutter_migrate/test/base/file_system_test.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/base/file_system_test.dart", "repo_id": "packages", "token_count": 4279 }
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 'dart:io'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/io.dart'; import 'package:flutter_migrate/src/base/signals.dart'; import 'package:process/process.dart'; import 'common.dart'; /// The [FileSystem] for the integration test environment. LocalFileSystem fileSystem = LocalFileSystem.test(signals: LocalSignals.instance); /// The [ProcessManager] for the integration test environment. const ProcessManager processManager = LocalProcessManager(); /// Creates a temporary directory but resolves any symlinks to return the real /// underlying path to avoid issues with breakpoints/hot reload. /// https://github.com/flutter/flutter/pull/21741 Directory createResolvedTempDirectorySync(String prefix) { assert(prefix.endsWith('.')); final Directory tempDirectory = fileSystem.systemTempDirectory.createTempSync('flutter_$prefix'); return fileSystem.directory(tempDirectory.resolveSymbolicLinksSync()); } void writeFile(String path, String content, {bool writeFutureModifiedDate = false}) { final File file = fileSystem.file(path) ..createSync(recursive: true) ..writeAsStringSync(content, flush: true); // Some integration tests on Windows to not see this file as being modified // recently enough for the hot reload to pick this change up unless the // modified time is written in the future. if (writeFutureModifiedDate) { file.setLastModifiedSync(DateTime.now().add(const Duration(seconds: 5))); } } void writePackages(String folder) { writeFile(fileSystem.path.join(folder, '.packages'), ''' test:${fileSystem.path.join(fileSystem.currentDirectory.path, 'lib')}/ '''); } Future<void> getPackages(String folder) async { final List<String> command = <String>[ fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'), 'pub', 'get', ]; final ProcessResult result = await processManager.run(command, workingDirectory: folder); if (result.exitCode != 0) { throw Exception( 'flutter pub get failed: ${result.stderr}\n${result.stdout}'); } }
packages/packages/flutter_migrate/test/src/test_utils.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/test_utils.dart", "repo_id": "packages", "token_count": 685 }
947
rootProject.name = 'flutter_plugin_android_lifecycle'
packages/packages/flutter_plugin_android_lifecycle/android/settings.gradle/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/android/settings.gradle", "repo_id": "packages", "token_count": 17 }
948
There are several kinds of errors or exceptions in go_router. * GoError and AssertionError This kind of errors are thrown when go_router is used incorrectly, for example, if the root [GoRoute.path](https://pub.dev/documentation/go_router/latest/go_router/GoRoute/path.html) does not start with `/` or a builder in GoRoute is not provided. These errors should not be caught and must be fixed in code in order to use go_router. * GoException This kind of exception are thrown when the configuration of go_router cannot handle incoming requests from users or other part of the code. For example, an GoException is thrown when user enter url that can't be parsed according to pattern specified in the `GoRouter.routes`. These exceptions can be handled in various callbacks. Once can provide a callback to `GoRouter.onException` to handle this exception. In this callback, one can choose to ignore, redirect, or push different pages depending on the situation. See [Exception Handling](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/exception_handling.dart) on a runnable example. The `GoRouter.errorBuilder` and `GoRouter.errorPageBuilder` can also be used to handle exceptions. ```dart GoRouter( /* ... */ errorBuilder: (context, state) => ErrorScreen(state.error), ); ``` By default, go_router comes with default error screens for both `MaterialApp` and `CupertinoApp` as well as a default error screen in the case that none is used. **Note** the `GoRouter.onException` supersedes other exception handling APIs.
packages/packages/go_router/doc/error-handling.md/0
{ "file_path": "packages/packages/go_router/doc/error-handling.md", "repo_id": "packages", "token_count": 428 }
949
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:url_launcher/link.dart'; import '../data.dart'; import 'author_details.dart'; /// A screen to display book details. class BookDetailsScreen extends StatelessWidget { /// Creates a [BookDetailsScreen]. const BookDetailsScreen({ super.key, this.book, }); /// The book to be displayed. final Book? book; @override Widget build(BuildContext context) { if (book == null) { return const Scaffold( body: Center( child: Text('No book found.'), ), ); } return Scaffold( appBar: AppBar( title: Text(book!.title), ), body: Center( child: Column( children: <Widget>[ Text( book!.title, style: Theme.of(context).textTheme.headlineMedium, ), Text( book!.author.name, style: Theme.of(context).textTheme.titleMedium, ), TextButton( onPressed: () { Navigator.of(context).push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => AuthorDetailsScreen(author: book!.author), ), ); }, child: const Text('View author (navigator.push)'), ), Link( uri: Uri.parse('/author/${book!.author.id}'), builder: (BuildContext context, FollowLink? followLink) => TextButton( onPressed: followLink, child: const Text('View author (Link)'), ), ), TextButton( onPressed: () { context.push('/author/${book!.author.id}'); }, child: const Text('View author (GoRouter.push)'), ), ], ), ), ); } }
packages/packages/go_router/example/lib/books/src/screens/book_details.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/screens/book_details.dart", "repo_id": "packages", "token_count": 1075 }
950
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:logging/logging.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: Navigator Observer'; @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, title: title, ); final GoRouter _router = GoRouter( observers: <NavigatorObserver>[MyNavObserver()], routes: <GoRoute>[ GoRoute( // if there's no name, path will be used as name for observers path: '/', builder: (BuildContext context, GoRouterState state) => const Page1Screen(), routes: <GoRoute>[ GoRoute( name: 'page2', path: 'page2/:p1', builder: (BuildContext context, GoRouterState state) => const Page2Screen(), routes: <GoRoute>[ GoRoute( name: 'page3', path: 'page3', builder: (BuildContext context, GoRouterState state) => const Page3Screen(), ), ], ), ], ), ], ); } /// The Navigator observer. class MyNavObserver extends NavigatorObserver { /// Creates a [MyNavObserver]. MyNavObserver() { log.onRecord.listen((LogRecord e) => debugPrint('$e')); } /// The logged message. final Logger log = Logger('MyNavObserver'); @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => log.info('didPush: ${route.str}, previousRoute= ${previousRoute?.str}'); @override void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => log.info('didPop: ${route.str}, previousRoute= ${previousRoute?.str}'); @override void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) => log.info('didRemove: ${route.str}, previousRoute= ${previousRoute?.str}'); @override void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => log.info('didReplace: new= ${newRoute?.str}, old= ${oldRoute?.str}'); @override void didStartUserGesture( Route<dynamic> route, Route<dynamic>? previousRoute, ) => log.info('didStartUserGesture: ${route.str}, ' 'previousRoute= ${previousRoute?.str}'); @override void didStopUserGesture() => log.info('didStopUserGesture'); } extension on Route<dynamic> { String get str => 'route(${settings.name}: ${settings.arguments})'; } /// The screen of the first page. class Page1Screen extends StatelessWidget { /// Creates a [Page1Screen]. const Page1Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.goNamed( 'page2', pathParameters: <String, String>{'p1': 'pv1'}, queryParameters: <String, String>{'q1': 'qv1'}, ), child: const Text('Go to page 2'), ), ], ), ), ); } /// The screen of the second page. class Page2Screen extends StatelessWidget { /// Creates a [Page2Screen]. const Page2Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.goNamed( 'page3', pathParameters: <String, String>{'p1': 'pv2'}, ), child: const Text('Go to page 3'), ), ], ), ), ); } /// The screen of the third page. class Page3Screen extends StatelessWidget { /// Creates a [Page3Screen]. const Page3Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/'), child: const Text('Go to home page'), ), ], ), ), ); }
packages/packages/go_router/example/lib/others/nav_observer.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/nav_observer.dart", "repo_id": "packages", "token_count": 2167 }
951
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_examples/redirection.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(example.App()); expect(find.text('Login'), findsOneWidget); // Directly set the url to the home page. Map<String, dynamic> testRouteInformation = <String, dynamic>{ 'location': '/', }; ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); await tester.pumpAndSettle(); // Still show login page due to redirection expect(find.text('Login'), findsOneWidget); await tester.tap(find.text('Login')); await tester.pumpAndSettle(); expect(find.text('HomeScreen'), findsOneWidget); testRouteInformation = <String, dynamic>{ 'location': '/login', }; message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); await tester.pumpAndSettle(); // Got redirected back to home page. expect(find.text('HomeScreen'), findsOneWidget); // Tap logout. await tester.tap(find.byType(IconButton)); await tester.pumpAndSettle(); expect(find.text('Login'), findsOneWidget); }); }
packages/packages/go_router/example/test/redirection_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/redirection_test.dart", "repo_id": "packages", "token_count": 603 }
952
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'configuration.dart'; import 'logging.dart'; import 'misc/errors.dart'; import 'path_utils.dart'; import 'route.dart'; import 'state.dart'; /// The function signature for [RouteMatchList.visitRouteMatches] /// /// Return false to stop the walk. typedef RouteMatchVisitor = bool Function(RouteMatchBase); /// The base class for various route matches. abstract class RouteMatchBase with Diagnosticable { /// An abstract route match base const RouteMatchBase(); /// The matched route. RouteBase get route; /// The page key. ValueKey<String> get pageKey; /// The location string that matches the [route]. /// /// for example: /// /// uri = '/family/f2/person/p2' /// route = GoRoute('/family/:id') /// /// matchedLocation = '/family/f2' String get matchedLocation; /// Gets the state that represent this route match. GoRouterState buildState( RouteConfiguration configuration, RouteMatchList matches); /// Generates a list of [RouteMatchBase] objects by matching the `route` and /// its sub-routes with `uri`. /// /// This method returns empty list if it can't find a complete match in the /// `route`. /// /// The `rootNavigatorKey` is required to match routes with /// parentNavigatorKey. /// /// The extracted path parameters, as the result of the matching, are stored /// into `pathParameters`. static List<RouteMatchBase> match({ required RouteBase route, required Map<String, String> pathParameters, required GlobalKey<NavigatorState> rootNavigatorKey, required Uri uri, }) { return _matchByNavigatorKey( route: route, matchedPath: '', remainingLocation: uri.path, matchedLocation: '', pathParameters: pathParameters, scopedNavigatorKey: rootNavigatorKey, uri: uri, )[null] ?? const <RouteMatchBase>[]; } static const Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _empty = <GlobalKey<NavigatorState>?, List<RouteMatchBase>>{}; /// Returns a navigator key to route matches maps. /// /// The null key corresponds to the route matches of `scopedNavigatorKey`. /// The scopedNavigatorKey must not be part of the returned map; otherwise, /// it is impossible to order the matches. static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKey({ required RouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 required String matchedLocation, // e.g. /family/f2 required Map<String, String> pathParameters, required GlobalKey<NavigatorState> scopedNavigatorKey, required Uri uri, }) { final Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> result; if (route is ShellRouteBase) { result = _matchByNavigatorKeyForShellRoute( route: route, matchedPath: matchedPath, remainingLocation: remainingLocation, matchedLocation: matchedLocation, pathParameters: pathParameters, scopedNavigatorKey: scopedNavigatorKey, uri: uri, ); } else if (route is GoRoute) { result = _matchByNavigatorKeyForGoRoute( route: route, matchedPath: matchedPath, remainingLocation: remainingLocation, matchedLocation: matchedLocation, pathParameters: pathParameters, scopedNavigatorKey: scopedNavigatorKey, uri: uri, ); } else { assert(false, 'Unexpected route type: $route'); return _empty; } // Grab the route matches for the scope navigator key and put it into the // matches for `null`. if (result.containsKey(scopedNavigatorKey)) { final List<RouteMatchBase> matchesForScopedNavigator = result.remove(scopedNavigatorKey)!; assert(matchesForScopedNavigator.isNotEmpty); result .putIfAbsent(null, () => <RouteMatchBase>[]) .addAll(matchesForScopedNavigator); } return result; } static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKeyForShellRoute({ required ShellRouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 required String matchedLocation, // e.g. /family/f2 required Map<String, String> pathParameters, required GlobalKey<NavigatorState> scopedNavigatorKey, required Uri uri, }) { final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey == scopedNavigatorKey ? null : route.parentNavigatorKey; Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>? subRouteMatches; late GlobalKey<NavigatorState> navigatorKeyUsed; for (final RouteBase subRoute in route.routes) { navigatorKeyUsed = route.navigatorKeyForSubRoute(subRoute); subRouteMatches = _matchByNavigatorKey( route: subRoute, matchedPath: matchedPath, remainingLocation: remainingLocation, matchedLocation: matchedLocation, pathParameters: pathParameters, uri: uri, scopedNavigatorKey: navigatorKeyUsed, ); assert(!subRouteMatches .containsKey(route.navigatorKeyForSubRoute(subRoute))); if (subRouteMatches.isNotEmpty) { break; } } if (subRouteMatches?.isEmpty ?? true) { return _empty; } final RouteMatchBase result = ShellRouteMatch( route: route, // The RouteConfiguration should have asserted the subRouteMatches must // have at least one match for this ShellRouteBase. matches: subRouteMatches!.remove(null)!, matchedLocation: remainingLocation, pageKey: ValueKey<String>(route.hashCode.toString()), navigatorKey: navigatorKeyUsed, ); subRouteMatches.putIfAbsent(parentKey, () => <RouteMatchBase>[]).insert( 0, result, ); return subRouteMatches; } static Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>> _matchByNavigatorKeyForGoRoute({ required GoRoute route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 required String matchedLocation, // e.g. /family/f2 required Map<String, String> pathParameters, required GlobalKey<NavigatorState> scopedNavigatorKey, required Uri uri, }) { final GlobalKey<NavigatorState>? parentKey = route.parentNavigatorKey == scopedNavigatorKey ? null : route.parentNavigatorKey; final RegExpMatch? regExpMatch = route.matchPatternAsPrefix(remainingLocation); if (regExpMatch == null) { return _empty; } final Map<String, String> encodedParams = route.extractPathParams(regExpMatch); // A temporary map to hold path parameters. This map is merged into // pathParameters only when this route is part of the returned result. final Map<String, String> currentPathParameter = encodedParams.map<String, String>((String key, String value) => MapEntry<String, String>(key, Uri.decodeComponent(value))); final String pathLoc = patternToPath(route.path, encodedParams); final String newMatchedLocation = concatenatePaths(matchedLocation, pathLoc); final String newMatchedPath = concatenatePaths(matchedPath, route.path); if (newMatchedLocation.toLowerCase() == uri.path.toLowerCase()) { // A complete match. pathParameters.addAll(currentPathParameter); return <GlobalKey<NavigatorState>?, List<RouteMatchBase>>{ parentKey: <RouteMatchBase>[ RouteMatch( route: route, matchedLocation: newMatchedLocation, pageKey: ValueKey<String>(newMatchedPath), ), ], }; } assert(uri.path.startsWith(newMatchedLocation)); assert(remainingLocation.isNotEmpty); final String childRestLoc = uri.path.substring( newMatchedLocation.length + (newMatchedLocation == '/' ? 0 : 1)); Map<GlobalKey<NavigatorState>?, List<RouteMatchBase>>? subRouteMatches; for (final RouteBase subRoute in route.routes) { subRouteMatches = _matchByNavigatorKey( route: subRoute, matchedPath: newMatchedPath, remainingLocation: childRestLoc, matchedLocation: newMatchedLocation, pathParameters: pathParameters, uri: uri, scopedNavigatorKey: scopedNavigatorKey, ); if (subRouteMatches.isNotEmpty) { break; } } if (subRouteMatches?.isEmpty ?? true) { // If not finding a sub route match, it is considered not matched for this // route even if this route match part of the `remainingLocation`. return _empty; } pathParameters.addAll(currentPathParameter); subRouteMatches!.putIfAbsent(parentKey, () => <RouteMatchBase>[]).insert( 0, RouteMatch( route: route, matchedLocation: newMatchedLocation, pageKey: ValueKey<String>(newMatchedPath), )); return subRouteMatches; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<RouteBase>('route', route)); } } /// An matched result by matching a [GoRoute] against a location. /// /// This is typically created by calling [RouteMatchBase.match]. @immutable class RouteMatch extends RouteMatchBase { /// Constructor for [RouteMatch]. const RouteMatch({ required this.route, required this.matchedLocation, required this.pageKey, }); /// The matched route. @override final GoRoute route; @override final String matchedLocation; @override final ValueKey<String> pageKey; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is RouteMatch && route == other.route && matchedLocation == other.matchedLocation && pageKey == other.pageKey; } @override int get hashCode => Object.hash(route, matchedLocation, pageKey); @override GoRouterState buildState( RouteConfiguration configuration, RouteMatchList matches) { return GoRouterState( configuration, uri: matches.uri, matchedLocation: matchedLocation, fullPath: matches.fullPath, pathParameters: matches.pathParameters, pageKey: pageKey, name: route.name, path: route.path, extra: matches.extra, topRoute: matches.lastOrNull?.route, ); } } /// An matched result by matching a [ShellRoute] against a location. /// /// This is typically created by calling [RouteMatchBase.match]. @immutable class ShellRouteMatch extends RouteMatchBase { /// Create a match. ShellRouteMatch({ required this.route, required this.matches, required this.matchedLocation, required this.pageKey, required this.navigatorKey, }) : assert(matches.isNotEmpty); @override final ShellRouteBase route; RouteMatch get _lastLeaf { RouteMatchBase currentMatch = matches.last; while (currentMatch is ShellRouteMatch) { currentMatch = currentMatch.matches.last; } return currentMatch as RouteMatch; } /// The navigator key used for this match. final GlobalKey<NavigatorState> navigatorKey; @override final String matchedLocation; /// The matches that will be built under this shell route. final List<RouteMatchBase> matches; @override final ValueKey<String> pageKey; @override GoRouterState buildState( RouteConfiguration configuration, RouteMatchList matches) { // The route related data is stored in the leaf route match. final RouteMatch leafMatch = _lastLeaf; if (leafMatch is ImperativeRouteMatch) { matches = leafMatch.matches; } return GoRouterState( configuration, uri: matches.uri, matchedLocation: matchedLocation, fullPath: matches.fullPath, pathParameters: matches.pathParameters, pageKey: pageKey, extra: matches.extra, topRoute: matches.lastOrNull?.route, ); } /// Creates a new shell route match with the given matches. /// /// This is typically used when pushing or popping [RouteMatchBase] from /// [RouteMatchList]. @internal ShellRouteMatch copyWith({ required List<RouteMatchBase>? matches, }) { return ShellRouteMatch( matches: matches ?? this.matches, route: route, matchedLocation: matchedLocation, pageKey: pageKey, navigatorKey: navigatorKey, ); } @override bool operator ==(Object other) { return other is ShellRouteMatch && route == other.route && matchedLocation == other.matchedLocation && const ListEquality<RouteMatchBase>().equals(matches, other.matches) && pageKey == other.pageKey; } @override int get hashCode => Object.hash(route, matchedLocation, Object.hashAll(matches), pageKey); } /// The route match that represent route pushed through [GoRouter.push]. class ImperativeRouteMatch extends RouteMatch { /// Constructor for [ImperativeRouteMatch]. ImperativeRouteMatch( {required super.pageKey, required this.matches, required this.completer}) : super( route: _getsLastRouteFromMatches(matches), matchedLocation: _getsMatchedLocationFromMatches(matches), ); static GoRoute _getsLastRouteFromMatches(RouteMatchList matchList) { if (matchList.isError) { return GoRoute( path: 'error', builder: (_, __) => throw UnimplementedError()); } return matchList.last.route; } static String _getsMatchedLocationFromMatches(RouteMatchList matchList) { if (matchList.isError) { return matchList.uri.toString(); } return matchList.last.matchedLocation; } /// The matches that produces this route match. final RouteMatchList matches; /// The completer for the future returned by [GoRouter.push]. final Completer<Object?> completer; /// Called when the corresponding [Route] associated with this route match is /// completed. void complete([dynamic value]) { completer.complete(value); } @override GoRouterState buildState( RouteConfiguration configuration, RouteMatchList matches) { return super.buildState(configuration, this.matches); } @override bool operator ==(Object other) { return other is ImperativeRouteMatch && completer == other.completer && matches == other.matches && super == other; } @override int get hashCode => Object.hash(super.hashCode, completer, matches.hashCode); } /// The list of [RouteMatchBase] objects. /// /// This can contains tree structure if there are [ShellRouteMatch] in the list. /// /// This corresponds to the GoRouter's history. @immutable class RouteMatchList with Diagnosticable { /// RouteMatchList constructor. RouteMatchList({ required this.matches, required this.uri, this.extra, this.error, required this.pathParameters, }) : fullPath = _generateFullPath(matches); /// Constructs an empty matches object. static RouteMatchList empty = RouteMatchList( matches: const <RouteMatchBase>[], uri: Uri(), pathParameters: const <String, String>{}); /// The route matches. final List<RouteMatchBase> matches; /// Parameters for the matched route, URI-encoded. /// /// The parameters only reflects [RouteMatch]s that are not /// [ImperativeRouteMatch]. final Map<String, String> pathParameters; /// The uri of the current match. /// /// This uri only reflects [RouteMatch]s that are not [ImperativeRouteMatch]. final Uri uri; /// An extra object to pass along with the navigation. final Object? extra; /// An exception if there was an error during matching. final GoException? error; /// the full path pattern that matches the uri. /// /// For example: /// /// ```dart /// '/family/:fid/person/:pid' /// ``` final String fullPath; /// Generates the full path (ex: `'/family/:fid/person/:pid'`) of a list of /// [RouteMatch]. /// /// This method ignores [ImperativeRouteMatch]s in the `matches`, as they /// don't contribute to the path. /// /// This methods considers that [matches]'s elements verify the go route /// structure given to `GoRouter`. For example, if the routes structure is /// /// ```dart /// GoRoute( /// path: '/a', /// routes: [ /// GoRoute( /// path: 'b', /// routes: [ /// GoRoute( /// path: 'c', /// ), /// ], /// ), /// ], /// ), /// ``` /// /// The [matches] must be the in same order of how GoRoutes are matched. /// /// ```dart /// [RouteMatchA(), RouteMatchB(), RouteMatchC()] /// ``` static String _generateFullPath(Iterable<RouteMatchBase> matches) { final StringBuffer buffer = StringBuffer(); bool addsSlash = false; for (final RouteMatchBase match in matches .where((RouteMatchBase match) => match is! ImperativeRouteMatch)) { if (addsSlash) { buffer.write('/'); } final String pathSegment; if (match is RouteMatch) { pathSegment = match.route.path; } else if (match is ShellRouteMatch) { pathSegment = _generateFullPath(match.matches); } else { assert(false, 'Unexpected match type: $match'); continue; } buffer.write(pathSegment); addsSlash = pathSegment.isNotEmpty && (addsSlash || pathSegment != '/'); } return buffer.toString(); } /// Returns true if there are no matches. bool get isEmpty => matches.isEmpty; /// Returns true if there are matches. bool get isNotEmpty => matches.isNotEmpty; /// Returns a new instance of RouteMatchList with the input `match` pushed /// onto the current instance. RouteMatchList push(ImperativeRouteMatch match) { if (match.matches.isError) { return copyWith(matches: <RouteMatchBase>[...matches, match]); } return copyWith( matches: _createNewMatchUntilIncompatible( matches, match.matches.matches, match, ), ); } static List<RouteMatchBase> _createNewMatchUntilIncompatible( List<RouteMatchBase> currentMatches, List<RouteMatchBase> otherMatches, ImperativeRouteMatch match, ) { final List<RouteMatchBase> newMatches = currentMatches.toList(); if (otherMatches.last is ShellRouteMatch && newMatches.isNotEmpty && otherMatches.last.route == newMatches.last.route) { assert(newMatches.last is ShellRouteMatch); final ShellRouteMatch lastShellRouteMatch = newMatches.removeLast() as ShellRouteMatch; newMatches.add( // Create a new copy of the `lastShellRouteMatch`. lastShellRouteMatch.copyWith( matches: _createNewMatchUntilIncompatible(lastShellRouteMatch.matches, (otherMatches.last as ShellRouteMatch).matches, match), ), ); return newMatches; } newMatches .add(_cloneBranchAndInsertImperativeMatch(otherMatches.last, match)); return newMatches; } static RouteMatchBase _cloneBranchAndInsertImperativeMatch( RouteMatchBase branch, ImperativeRouteMatch match) { if (branch is ShellRouteMatch) { return branch.copyWith( matches: <RouteMatchBase>[ _cloneBranchAndInsertImperativeMatch(branch.matches.last, match), ], ); } // Add the input `match` instead of the incompatibleMatch since it contains // page key and push future. assert(branch.route == match.route); return match; } /// Returns a new instance of RouteMatchList with the input `match` removed /// from the current instance. RouteMatchList remove(RouteMatchBase match) { final List<RouteMatchBase> newMatches = _removeRouteMatchFromList(matches, match); if (newMatches == matches) { return this; } final String fullPath = _generateFullPath(newMatches); if (this.fullPath == fullPath) { return copyWith( matches: newMatches, ); } // Need to remove path parameters that are no longer in the fullPath. final List<String> newParameters = <String>[]; patternToRegExp(fullPath, newParameters); final Set<String> validParameters = newParameters.toSet(); final Map<String, String> newPathParameters = Map<String, String>.fromEntries( pathParameters.entries.where((MapEntry<String, String> value) => validParameters.contains(value.key)), ); final Uri newUri = uri.replace(path: patternToPath(fullPath, newPathParameters)); return copyWith( matches: newMatches, uri: newUri, pathParameters: newPathParameters, ); } /// Returns a new List from the input matches with target removed. /// /// This method recursively looks into any ShellRouteMatch in matches and /// removes target if it found a match in the match list nested in /// ShellRouteMatch. /// /// This method returns a new list as long as the target is found in the /// matches' subtree. /// /// If a target is found, the target and every node after the target in tree /// order is removed. static List<RouteMatchBase> _removeRouteMatchFromList( List<RouteMatchBase> matches, RouteMatchBase target) { // Remove is caused by pop; therefore, start searching from the end. for (int index = matches.length - 1; index >= 0; index -= 1) { final RouteMatchBase match = matches[index]; if (match == target) { // Remove any redirect only route immediately before the target. while (index > 0) { final RouteMatchBase lookBefore = matches[index - 1]; if (lookBefore is! RouteMatch || !lookBefore.route.redirectOnly) { break; } index -= 1; } return matches.sublist(0, index); } if (match is ShellRouteMatch) { final List<RouteMatchBase> newSubMatches = _removeRouteMatchFromList(match.matches, target); if (newSubMatches == match.matches) { // Didn't find target in the newSubMatches. continue; } // Removes `match` if its sub match list become empty after the remove. return <RouteMatchBase>[ ...matches.sublist(0, index), if (newSubMatches.isNotEmpty) match.copyWith(matches: newSubMatches), ]; } } // Target is not in the match subtree. return matches; } /// The last leaf route. /// /// If the last RouteMatchBase from [matches] is a ShellRouteMatch, it /// recursively goes into its [ShellRouteMatch.matches] until it reach the leaf /// [RouteMatch]. /// /// Throws a [StateError] if [matches] is empty. RouteMatch get last { if (matches.last is RouteMatch) { return matches.last as RouteMatch; } return (matches.last as ShellRouteMatch)._lastLeaf; } /// The last leaf route or null if [matches] is empty /// /// If the last RouteMatchBase from [matches] is a ShellRouteMatch, it /// recursively goes into its [ShellRouteMatch.matches] until it reach the leaf /// [RouteMatch]. RouteMatch? get lastOrNull { if (matches.isEmpty) { return null; } return last; } /// Returns true if the current match intends to display an error screen. bool get isError => error != null; /// The routes for each of the matches. List<RouteBase> get routes { final List<RouteBase> result = <RouteBase>[]; visitRouteMatches((RouteMatchBase match) { result.add(match.route); return true; }); return result; } /// Traverse route matches in this match list in preorder until visitor /// returns false. /// /// This method visit recursively into shell route matches. @internal void visitRouteMatches(RouteMatchVisitor visitor) { _visitRouteMatches(matches, visitor); } static bool _visitRouteMatches( List<RouteMatchBase> matches, RouteMatchVisitor visitor) { for (final RouteMatchBase routeMatch in matches) { if (!visitor(routeMatch)) { return false; } if (routeMatch is ShellRouteMatch && !_visitRouteMatches(routeMatch.matches, visitor)) { return false; } } return true; } /// Create a new [RouteMatchList] with given parameter replaced. @internal RouteMatchList copyWith({ List<RouteMatchBase>? matches, Uri? uri, Map<String, String>? pathParameters, }) { return RouteMatchList( matches: matches ?? this.matches, uri: uri ?? this.uri, extra: extra, error: error, pathParameters: pathParameters ?? this.pathParameters); } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is RouteMatchList && uri == other.uri && extra == other.extra && error == other.error && const ListEquality<RouteMatchBase>().equals(matches, other.matches) && const MapEquality<String, String>() .equals(pathParameters, other.pathParameters); } @override int get hashCode { return Object.hash( Object.hashAll(matches), uri, extra, error, Object.hashAllUnordered( pathParameters.entries.map<int>((MapEntry<String, String> entry) => Object.hash(entry.key, entry.value)), ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Uri>('uri', uri)); properties .add(DiagnosticsProperty<List<RouteMatchBase>>('matches', matches)); } } /// Handles encoding and decoding of [RouteMatchList] objects to a format /// suitable for using with [StandardMessageCodec]. /// /// The primary use of this class is for state restoration and browser history. @internal class RouteMatchListCodec extends Codec<RouteMatchList, Map<Object?, Object?>> { /// Creates a new [RouteMatchListCodec] object. RouteMatchListCodec(RouteConfiguration configuration) : decoder = _RouteMatchListDecoder(configuration), encoder = _RouteMatchListEncoder(configuration); static const String _locationKey = 'location'; static const String _extraKey = 'state'; static const String _imperativeMatchesKey = 'imperativeMatches'; static const String _pageKey = 'pageKey'; static const String _codecKey = 'codec'; static const String _jsonCodecName = 'json'; static const String _customCodecName = 'custom'; static const String _encodedKey = 'encoded'; @override final Converter<RouteMatchList, Map<Object?, Object?>> encoder; @override final Converter<Map<Object?, Object?>, RouteMatchList> decoder; } class _RouteMatchListEncoder extends Converter<RouteMatchList, Map<Object?, Object?>> { const _RouteMatchListEncoder(this.configuration); final RouteConfiguration configuration; @override Map<Object?, Object?> convert(RouteMatchList input) { final List<ImperativeRouteMatch> imperativeMatches = <ImperativeRouteMatch>[]; input.visitRouteMatches((RouteMatchBase match) { if (match is ImperativeRouteMatch) { imperativeMatches.add(match); } return true; }); final List<Map<Object?, Object?>> encodedImperativeMatches = imperativeMatches .map((ImperativeRouteMatch e) => _toPrimitives( e.matches.uri.toString(), e.matches.extra, pageKey: e.pageKey.value)) .toList(); return _toPrimitives(input.uri.toString(), input.extra, imperativeMatches: encodedImperativeMatches); } Map<Object?, Object?> _toPrimitives(String location, Object? extra, {List<Map<Object?, Object?>>? imperativeMatches, String? pageKey}) { Map<String, Object?> encodedExtra; if (configuration.extraCodec != null) { encodedExtra = <String, Object?>{ RouteMatchListCodec._codecKey: RouteMatchListCodec._customCodecName, RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode(extra), }; } else { String jsonEncodedExtra; try { jsonEncodedExtra = json.encoder.convert(extra); } on JsonUnsupportedObjectError { jsonEncodedExtra = json.encoder.convert(null); log( 'An extra with complex data type ${extra.runtimeType} is provided ' 'without a codec. Consider provide a codec to GoRouter to ' 'prevent extra being dropped during serialization.', level: Level.WARNING); } encodedExtra = <String, Object?>{ RouteMatchListCodec._codecKey: RouteMatchListCodec._jsonCodecName, RouteMatchListCodec._encodedKey: jsonEncodedExtra, }; } return <Object?, Object?>{ RouteMatchListCodec._locationKey: location, RouteMatchListCodec._extraKey: encodedExtra, if (imperativeMatches != null) RouteMatchListCodec._imperativeMatchesKey: imperativeMatches, if (pageKey != null) RouteMatchListCodec._pageKey: pageKey, }; } } class _RouteMatchListDecoder extends Converter<Map<Object?, Object?>, RouteMatchList> { _RouteMatchListDecoder(this.configuration); final RouteConfiguration configuration; @override RouteMatchList convert(Map<Object?, Object?> input) { final String rootLocation = input[RouteMatchListCodec._locationKey]! as String; final Map<Object?, Object?> encodedExtra = input[RouteMatchListCodec._extraKey]! as Map<Object?, Object?>; final Object? extra; if (encodedExtra[RouteMatchListCodec._codecKey] == RouteMatchListCodec._jsonCodecName) { extra = json.decoder .convert(encodedExtra[RouteMatchListCodec._encodedKey]! as String); } else { extra = configuration.extraCodec ?.decode(encodedExtra[RouteMatchListCodec._encodedKey]); } RouteMatchList matchList = configuration.findMatch(rootLocation, extra: extra); final List<Object?>? imperativeMatches = input[RouteMatchListCodec._imperativeMatchesKey] as List<Object?>?; if (imperativeMatches != null) { for (final Map<Object?, Object?> encodedImperativeMatch in imperativeMatches.whereType<Map<Object?, Object?>>()) { final RouteMatchList imperativeMatchList = convert(encodedImperativeMatch); final ValueKey<String> pageKey = ValueKey<String>( encodedImperativeMatch[RouteMatchListCodec._pageKey]! as String); final ImperativeRouteMatch imperativeMatch = ImperativeRouteMatch( pageKey: pageKey, // TODO(chunhtai): Figure out a way to preserve future. // https://github.com/flutter/flutter/issues/128122. completer: Completer<Object?>(), matches: imperativeMatchList, ); matchList = matchList.push(imperativeMatch); } } return matchList; } }
packages/packages/go_router/lib/src/match.dart/0
{ "file_path": "packages/packages/go_router/lib/src/match.dart", "repo_id": "packages", "token_count": 11348 }
953
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { group('RouteBuilder', () { testWidgets('Builds GoRoute', (WidgetTester tester) async { final RouteConfiguration config = createRouteConfiguration( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, navigatorKey: GlobalKey<NavigatorState>(), ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatch>[ RouteMatch( route: config.routes.first as GoRoute, matchedLocation: '/', pageKey: const ValueKey<String>('/'), ), ], uri: Uri.parse('/'), pathParameters: const <String, String>{}); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); expect(find.byType(_DetailsScreen), findsOneWidget); }); testWidgets('Builds ShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(); final RouteConfiguration config = createRouteConfiguration( routes: <RouteBase>[ ShellRoute( navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return _DetailsScreen(); }, routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, navigatorKey: GlobalKey<NavigatorState>(), ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatchBase>[ ShellRouteMatch( route: config.routes.first as ShellRouteBase, matchedLocation: '', pageKey: const ValueKey<String>(''), navigatorKey: shellNavigatorKey, matches: <RouteMatchBase>[ RouteMatch( route: config.routes.first.routes.first as GoRoute, matchedLocation: '/', pageKey: const ValueKey<String>('/'), ), ], ), ], uri: Uri.parse('/'), pathParameters: const <String, String>{}, ); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); expect(find.byType(_DetailsScreen), findsOneWidget); }); testWidgets('Uses the correct navigatorKey', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final RouteConfiguration config = createRouteConfiguration( navigatorKey: rootNavigatorKey, routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatch>[ RouteMatch( route: config.routes.first as GoRoute, matchedLocation: '/', pageKey: const ValueKey<String>('/'), ), ], uri: Uri.parse('/'), pathParameters: const <String, String>{}); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); expect(find.byKey(rootNavigatorKey), findsOneWidget); }); testWidgets('Builds a Navigator for ShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell'); final RouteConfiguration config = createRouteConfiguration( navigatorKey: rootNavigatorKey, routes: <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return _HomeScreen( child: child, ); }, navigatorKey: shellNavigatorKey, routes: <RouteBase>[ GoRoute( path: '/details', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatchBase>[ ShellRouteMatch( route: config.routes.first as ShellRouteBase, matchedLocation: '', pageKey: const ValueKey<String>(''), navigatorKey: shellNavigatorKey, matches: <RouteMatchBase>[ RouteMatch( route: config.routes.first.routes.first as GoRoute, matchedLocation: '/details', pageKey: const ValueKey<String>('/details'), ), ]), ], uri: Uri.parse('/details'), pathParameters: const <String, String>{}); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); expect(find.byType(_HomeScreen, skipOffstage: false), findsOneWidget); expect(find.byType(_DetailsScreen), findsOneWidget); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); }); testWidgets('Builds a Navigator for ShellRoute with parentNavigatorKey', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell'); final RouteConfiguration config = createRouteConfiguration( navigatorKey: rootNavigatorKey, routes: <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return _HomeScreen( child: child, ); }, navigatorKey: shellNavigatorKey, routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, // This screen should stack onto the root navigator. parentNavigatorKey: rootNavigatorKey, ), ], ), ], ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatch>[ RouteMatch( route: config.routes.first.routes.first as GoRoute, matchedLocation: '/a/details', pageKey: const ValueKey<String>('/a/details'), ), ], uri: Uri.parse('/a/details'), pathParameters: const <String, String>{}); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); // The Details screen should be visible, but the HomeScreen should be // offstage (underneath) the DetailsScreen. expect(find.byType(_HomeScreen), findsNothing); expect(find.byType(_DetailsScreen), findsOneWidget); }); testWidgets('Uses the correct restorationScopeId for ShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell'); final RouteConfiguration config = createRouteConfiguration( navigatorKey: rootNavigatorKey, routes: <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return _HomeScreen(child: child); }, navigatorKey: shellNavigatorKey, restorationScopeId: 'scope1', routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], ), ], redirectLimit: 10, topRedirect: (BuildContext context, GoRouterState state) { return null; }, ); final RouteMatchList matches = RouteMatchList( matches: <RouteMatchBase>[ ShellRouteMatch( route: config.routes.first as ShellRouteBase, matchedLocation: '', pageKey: const ValueKey<String>(''), navigatorKey: shellNavigatorKey, matches: <RouteMatchBase>[ RouteMatch( route: config.routes.first.routes.first as GoRoute, matchedLocation: '/a', pageKey: const ValueKey<String>('/a'), ), ], ), ], uri: Uri.parse('/b'), pathParameters: const <String, String>{}, ); await tester.pumpWidget( _BuilderTestWidget( routeConfiguration: config, matches: matches, ), ); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); expect( (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, 'scope1'); }); testWidgets('Uses the correct restorationScopeId for StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell'); final GoRouter goRouter = GoRouter( initialLocation: '/a', navigatorKey: rootNavigatorKey, routes: <RouteBase>[ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) => _HomeScreen(child: navigationShell), branches: <StatefulShellBranch>[ StatefulShellBranch( navigatorKey: shellNavigatorKey, restorationScopeId: 'scope1', routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return _DetailsScreen(); }, ), ], ), ], ), ], ); addTearDown(goRouter.dispose); await tester.pumpWidget(MaterialApp.router( routerConfig: goRouter, )); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); expect( (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, 'scope1'); }); }); } class _HomeScreen extends StatelessWidget { const _HomeScreen({ required this.child, }); final Widget child; @override Widget build(BuildContext context) { return Scaffold( body: Column( children: <Widget>[ const Text('Home Screen'), Expanded(child: child), ], ), ); } } class _DetailsScreen extends StatelessWidget { @override Widget build(BuildContext context) { return const Scaffold( body: Text('Details Screen'), ); } } class _BuilderTestWidget extends StatelessWidget { _BuilderTestWidget({ required this.routeConfiguration, required this.matches, }) : builder = _routeBuilder(routeConfiguration); final RouteConfiguration routeConfiguration; final RouteBuilder builder; final RouteMatchList matches; /// Builds a [RouteBuilder] for tests static RouteBuilder _routeBuilder(RouteConfiguration configuration) { return RouteBuilder( configuration: configuration, builderWithNav: ( BuildContext context, Widget child, ) { return child; }, errorPageBuilder: ( BuildContext context, GoRouterState state, ) { return MaterialPage<dynamic>( child: Text('Error: ${state.error}'), ); }, errorBuilder: ( BuildContext context, GoRouterState state, ) { return Text('Error: ${state.error}'); }, restorationScopeId: null, observers: <NavigatorObserver>[], onPopPageWithRouteMatch: (_, __, ___) => false, ); } @override Widget build(BuildContext context) { return MaterialApp( home: builder.build(context, matches, false), ); } }
packages/packages/go_router/test/builder_test.dart/0
{ "file_path": "packages/packages/go_router/test/builder_test.dart", "repo_id": "packages", "token_count": 6821 }
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 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:go_router/src/logging.dart'; import 'package:logging/logging.dart'; void main() { test('setLogging does not clear listeners', () { final StreamSubscription<LogRecord> subscription = logger.onRecord.listen( expectAsync1<void, LogRecord>((LogRecord r) {}, count: 2), ); addTearDown(subscription.cancel); setLogging(enabled: true); logger.info('message'); setLogging(); logger.info('message'); }); testWidgets( 'It should not log anything the if debugLogDiagnostics is false', (WidgetTester tester) async { final StreamSubscription<LogRecord> subscription = Logger.root.onRecord.listen( expectAsync1((LogRecord data) {}, count: 0), ); addTearDown(subscription.cancel); GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (_, GoRouterState state) => const Text('home'), ), ], ); }, ); testWidgets( 'It should not log the known routes and the initial route if debugLogDiagnostics is true', (WidgetTester tester) async { final List<String> logs = <String>[]; Logger.root.onRecord.listen( (LogRecord event) => logs.add(event.message), ); GoRouter( debugLogDiagnostics: true, routes: <RouteBase>[ GoRoute( path: '/', builder: (_, GoRouterState state) => const Text('home'), ), ], ); expect( logs, const <String>[ 'Full paths for routes:\n => /\n', 'setting initial location null' ], ); }, ); }
packages/packages/go_router/test/logging_test.dart/0
{ "file_path": "packages/packages/go_router/test/logging_test.dart", "repo_id": "packages", "token_count": 830 }
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:go_router/go_router.dart'; void main() { const GoRouterState state = GoRouterState(); final GoRouter router = GoRouter(routes: <RouteBase>[]); state.fullpath; state.params; state.subloc; state.queryParams; state.namedLocation( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); router.namedLocation( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); router.goNamed( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); router.pushNamed( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); router.pushReplacementNamed( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); router.replaceNamed( 'name', params: <String, String>{}, queryParams: <String, String>{}, ); state.queryParametersAll; state.location; }
packages/packages/go_router/test_fixes/go_router.dart/0
{ "file_path": "packages/packages/go_router/test_fixes/go_router.dart", "repo_id": "packages", "token_count": 422 }
956
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'extra_example.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $requiredExtraRoute, $optionalExtraRoute, $splashRoute, ]; RouteBase get $requiredExtraRoute => GoRouteData.$route( path: '/requiredExtra', factory: $RequiredExtraRouteExtension._fromState, ); extension $RequiredExtraRouteExtension on RequiredExtraRoute { static RequiredExtraRoute _fromState(GoRouterState state) => RequiredExtraRoute( $extra: state.extra as Extra, ); String get location => GoRouteData.$location( '/requiredExtra', ); void go(BuildContext context) => context.go(location, extra: $extra); Future<T?> push<T>(BuildContext context) => context.push<T>(location, extra: $extra); void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: $extra); void replace(BuildContext context) => context.replace(location, extra: $extra); } RouteBase get $optionalExtraRoute => GoRouteData.$route( path: '/optionalExtra', factory: $OptionalExtraRouteExtension._fromState, ); extension $OptionalExtraRouteExtension on OptionalExtraRoute { static OptionalExtraRoute _fromState(GoRouterState state) => OptionalExtraRoute( $extra: state.extra as Extra?, ); String get location => GoRouteData.$location( '/optionalExtra', ); void go(BuildContext context) => context.go(location, extra: $extra); Future<T?> push<T>(BuildContext context) => context.push<T>(location, extra: $extra); void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: $extra); void replace(BuildContext context) => context.replace(location, extra: $extra); } RouteBase get $splashRoute => GoRouteData.$route( path: '/splash', factory: $SplashRouteExtension._fromState, ); extension $SplashRouteExtension on SplashRoute { static SplashRoute _fromState(GoRouterState state) => const SplashRoute(); String get location => GoRouteData.$location( '/splash', ); 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/example/lib/extra_example.g.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/extra_example.g.dart", "repo_id": "packages", "token_count": 851 }
957
name: go_router_builder_example description: go_router_builder examples publish_to: none environment: sdk: ^3.1.0 dependencies: collection: ^1.15.0 flutter: sdk: flutter go_router: ^10.0.0 provider: 6.0.5 dev_dependencies: build_runner: ^2.3.0 build_verify: ^3.1.0 flutter_test: sdk: flutter go_router_builder: path: .. test: ^1.17.0 flutter: uses-material-design: true
packages/packages/go_router_builder/example/pubspec.yaml/0
{ "file_path": "packages/packages/go_router_builder/example/pubspec.yaml", "repo_id": "packages", "token_count": 182 }
958
# google_identity_services_web_example * `lib/main.dart`: An example on how to use the google_identiy_services_web `id` library from Dart. * `lib/main_oauth.dart`: An example for the `oauth2` library from the same SDK.
packages/packages/google_identity_services_web/example/README.md/0
{ "file_path": "packages/packages/google_identity_services_web/example/README.md", "repo_id": "packages", "token_count": 75 }
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. @TestOn('browser') // Uses package:web library; import 'package:google_identity_services_web/loader.dart'; import 'package:test/test.dart'; import 'package:web/web.dart' as web; import 'tools.dart'; // NOTE: This file needs to be separated from the others because Content // Security Policies can never be *relaxed* once set. // // In order to not introduce a dependency in the order of the tests, we split // them in different files, depending on the strictness of their CSP: // // * js_loader_test.dart : default TT configuration (not enforced) // * js_loader_tt_custom_test.dart : TT are customized, but allowed // * js_loader_tt_forbidden_test.dart: TT are completely disallowed void main() { group('loadWebSdk (TrustedTypes forbidden)', () { final web.HTMLDivElement target = web.document.createElement('div') as web.HTMLDivElement; injectMetaTag(<String, String>{ 'http-equiv': 'Content-Security-Policy', 'content': "trusted-types 'none';", }); test('Fail with TrustedTypesException', () { expect(() { loadWebSdk(target: target); }, throwsA(isA<TrustedTypesException>())); }); }); }
packages/packages/google_identity_services_web/test/js_loader_tt_forbidden_test.dart/0
{ "file_path": "packages/packages/google_identity_services_web/test/js_loader_tt_forbidden_test.dart", "repo_id": "packages", "token_count": 433 }
960
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:integration_test/integration_test.dart'; import 'src/maps_controller.dart' as maps_controller; import 'src/maps_inspector.dart' as maps_inspector; import 'src/tiles_inspector.dart' as tiles_inspector; /// Recombine all test files in `src` into a single test app. /// /// This is done to ensure that all the integration tests run in the same FTL app, /// rather than spinning multiple different tasks. void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); maps_controller.runTests(); maps_inspector.runTests(); tiles_inspector.runTests(); }
packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/google_maps_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/integration_test/google_maps_test.dart", "repo_id": "packages", "token_count": 228 }
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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'fake_google_maps_flutter_platform.dart'; Widget _mapWithTileOverlays(Set<TileOverlay> tileOverlays) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), tileOverlays: tileOverlays, ), ); } void main() { late FakeGoogleMapsFlutterPlatform platform; setUp(() { platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('Initializing a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.tileOverlaySets.last, equals(<TileOverlay>{t1})); }); testWidgets('Adding a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_2')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1, t2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.tileOverlaySets.last, equals(<TileOverlay>{t1, t2})); }); testWidgets('Removing a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.tileOverlaySets.last, equals(<TileOverlay>{})); }); testWidgets('Updating a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1'), zIndex: 10); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.tileOverlaySets.last, equals(<TileOverlay>{t2})); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart", "repo_id": "packages", "token_count": 1045 }
962
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.googlemaps; import android.content.Context; import androidx.annotation.VisibleForTesting; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.MapsInitializer.Renderer; import com.google.android.gms.maps.OnMapsSdkInitializedCallback; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; /** GoogleMaps initializer used to initialize the Google Maps SDK with preferred settings. */ final class GoogleMapInitializer implements OnMapsSdkInitializedCallback, MethodChannel.MethodCallHandler { private final MethodChannel methodChannel; private final Context context; private static MethodChannel.Result initializationResult; private boolean rendererInitialized = false; GoogleMapInitializer(Context context, BinaryMessenger binaryMessenger) { this.context = context; methodChannel = new MethodChannel(binaryMessenger, "plugins.flutter.dev/google_maps_android_initializer"); methodChannel.setMethodCallHandler(this); } @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { switch (call.method) { case "initializer#preferRenderer": { String preferredRenderer = (String) call.argument("value"); initializeWithPreferredRenderer(preferredRenderer, result); break; } default: result.notImplemented(); } } /** * Initializes map renderer to with preferred renderer type. Renderer can be initialized only once * per application context. * * <p>Supported renderer types are "latest", "legacy" and "default". */ private void initializeWithPreferredRenderer( String preferredRenderer, MethodChannel.Result result) { if (rendererInitialized || initializationResult != null) { result.error( "Renderer already initialized", "Renderer initialization called multiple times", null); } else { initializationResult = result; switch (preferredRenderer) { case "latest": initializeWithRendererRequest(Renderer.LATEST); break; case "legacy": initializeWithRendererRequest(Renderer.LEGACY); break; case "default": initializeWithRendererRequest(null); break; default: initializationResult.error( "Invalid renderer type", "Renderer initialization called with invalid renderer type", null); initializationResult = null; } } } /** * Initializes map renderer to with preferred renderer type. * * <p>This method is visible for testing purposes only and should never be used outside this * class. */ @VisibleForTesting public void initializeWithRendererRequest(MapsInitializer.Renderer renderer) { MapsInitializer.initialize(context, renderer, this); } /** Is called by Google Maps SDK to determine which version of the renderer was initialized. */ @Override public void onMapsSdkInitialized(MapsInitializer.Renderer renderer) { rendererInitialized = true; if (initializationResult != null) { switch (renderer) { case LATEST: initializationResult.success("latest"); break; case LEGACY: initializationResult.success("legacy"); break; default: initializationResult.error( "Unknown renderer type", "Initialized with unknown renderer type", null); } initializationResult = null; } } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapInitializer.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapInitializer.java", "repo_id": "packages", "token_count": 1302 }
963
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.googlemaps; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.List; import java.util.Map; class PolylinesController { private final Map<String, PolylineController> polylineIdToController; private final Map<String, String> googleMapsPolylineIdToDartPolylineId; private final MethodChannel methodChannel; private GoogleMap googleMap; private final float density; PolylinesController(MethodChannel methodChannel, float density) { this.polylineIdToController = new HashMap<>(); this.googleMapsPolylineIdToDartPolylineId = new HashMap<>(); this.methodChannel = methodChannel; this.density = density; } void setGoogleMap(GoogleMap googleMap) { this.googleMap = googleMap; } void addPolylines(List<Object> polylinesToAdd) { if (polylinesToAdd != null) { for (Object polylineToAdd : polylinesToAdd) { addPolyline(polylineToAdd); } } } void changePolylines(List<Object> polylinesToChange) { if (polylinesToChange != null) { for (Object polylineToChange : polylinesToChange) { changePolyline(polylineToChange); } } } void removePolylines(List<Object> polylineIdsToRemove) { if (polylineIdsToRemove == null) { return; } for (Object rawPolylineId : polylineIdsToRemove) { if (rawPolylineId == null) { continue; } String polylineId = (String) rawPolylineId; final PolylineController polylineController = polylineIdToController.remove(polylineId); if (polylineController != null) { polylineController.remove(); googleMapsPolylineIdToDartPolylineId.remove(polylineController.getGoogleMapsPolylineId()); } } } boolean onPolylineTap(String googlePolylineId) { String polylineId = googleMapsPolylineIdToDartPolylineId.get(googlePolylineId); if (polylineId == null) { return false; } methodChannel.invokeMethod("polyline#onTap", Convert.polylineIdToJson(polylineId)); PolylineController polylineController = polylineIdToController.get(polylineId); if (polylineController != null) { return polylineController.consumeTapEvents(); } return false; } private void addPolyline(Object polyline) { if (polyline == null) { return; } PolylineBuilder polylineBuilder = new PolylineBuilder(density); String polylineId = Convert.interpretPolylineOptions(polyline, polylineBuilder); PolylineOptions options = polylineBuilder.build(); addPolyline(polylineId, options, polylineBuilder.consumeTapEvents()); } private void addPolyline( String polylineId, PolylineOptions polylineOptions, boolean consumeTapEvents) { final Polyline polyline = googleMap.addPolyline(polylineOptions); PolylineController controller = new PolylineController(polyline, consumeTapEvents, density); polylineIdToController.put(polylineId, controller); googleMapsPolylineIdToDartPolylineId.put(polyline.getId(), polylineId); } private void changePolyline(Object polyline) { if (polyline == null) { return; } String polylineId = getPolylineId(polyline); PolylineController polylineController = polylineIdToController.get(polylineId); if (polylineController != null) { Convert.interpretPolylineOptions(polyline, polylineController); } } @SuppressWarnings("unchecked") private static String getPolylineId(Object polyline) { Map<String, Object> polylineMap = (Map<String, Object>) polyline; return (String) polylineMap.get("polylineId"); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylinesController.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylinesController.java", "repo_id": "packages", "token_count": 1321 }
964
mock-maker-inline
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker", "repo_id": "packages", "token_count": 7 }
965
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show Offset; import 'package:flutter/foundation.dart' show ValueChanged, VoidCallback, immutable; import 'types.dart'; Object _offsetToJson(Offset offset) { return <Object>[offset.dx, offset.dy]; } /// Text labels for a [Marker] info window. @immutable class InfoWindow { /// Creates an immutable representation of a label on for [Marker]. const InfoWindow({ this.title, this.snippet, this.anchor = const Offset(0.5, 0.0), this.onTap, }); /// Text labels specifying that no text is to be displayed. static const InfoWindow noText = InfoWindow(); /// Text displayed in an info window when the user taps the marker. /// /// A null value means no title. final String? title; /// Additional text displayed below the [title]. /// /// A null value means no additional text. final String? snippet; /// The icon image point that will be the anchor of the info window when /// displayed. /// /// The image point is specified in normalized coordinates: An anchor of /// (0.0, 0.0) means the top left corner of the image. An anchor /// of (1.0, 1.0) means the bottom right corner of the image. final Offset anchor; /// onTap callback for this [InfoWindow]. final VoidCallback? onTap; /// Creates a new [InfoWindow] object whose values are the same as this instance, /// unless overwritten by the specified parameters. InfoWindow copyWith({ String? titleParam, String? snippetParam, Offset? anchorParam, VoidCallback? onTapParam, }) { return InfoWindow( title: titleParam ?? title, snippet: snippetParam ?? snippet, anchor: anchorParam ?? anchor, onTap: onTapParam ?? onTap, ); } Object _toJson() { final Map<String, Object> json = <String, Object>{}; void addIfPresent(String fieldName, Object? value) { if (value != null) { json[fieldName] = value; } } addIfPresent('title', title); addIfPresent('snippet', snippet); addIfPresent('anchor', _offsetToJson(anchor)); return json; } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is InfoWindow && title == other.title && snippet == other.snippet && anchor == other.anchor; } @override int get hashCode => Object.hash(title.hashCode, snippet, anchor); @override String toString() { return 'InfoWindow{title: $title, snippet: $snippet, anchor: $anchor}'; } } /// Uniquely identifies a [Marker] among [GoogleMap] markers. /// /// This does not have to be globally unique, only unique among the list. @immutable class MarkerId extends MapsObjectId<Marker> { /// Creates an immutable identifier for a [Marker]. const MarkerId(super.value); } /// Marks a geographical location on the map. /// /// A marker icon is drawn oriented against the device's screen rather than /// the map's surface; that is, it will not necessarily change orientation /// due to map rotations, tilting, or zooming. @immutable class Marker implements MapsObject<Marker> { /// Creates a set of marker configuration options. /// /// Default marker options. /// /// Specifies a marker that /// * is fully opaque; [alpha] is 1.0 /// * uses icon bottom center to indicate map position; [anchor] is (0.5, 1.0) /// * has default tap handling; [consumeTapEvents] is false /// * is stationary; [draggable] is false /// * is drawn against the screen, not the map; [flat] is false /// * has a default icon; [icon] is `BitmapDescriptor.defaultMarker` /// * anchors the info window at top center; [infoWindowAnchor] is (0.5, 0.0) /// * has no info window text; [infoWindowText] is `InfoWindowText.noText` /// * is positioned at 0, 0; [position] is `LatLng(0.0, 0.0)` /// * has an axis-aligned icon; [rotation] is 0.0 /// * is visible; [visible] is true /// * is placed at the base of the drawing order; [zIndex] is 0.0 /// * reports [onTap] events /// * reports [onDragEnd] events const Marker({ required this.markerId, this.alpha = 1.0, this.anchor = const Offset(0.5, 1.0), this.consumeTapEvents = false, this.draggable = false, this.flat = false, this.icon = BitmapDescriptor.defaultMarker, this.infoWindow = InfoWindow.noText, this.position = const LatLng(0.0, 0.0), this.rotation = 0.0, this.visible = true, this.zIndex = 0.0, this.clusterManagerId, this.onTap, this.onDrag, this.onDragStart, this.onDragEnd, }) : assert(0.0 <= alpha && alpha <= 1.0); /// Uniquely identifies a [Marker]. final MarkerId markerId; @override MarkerId get mapsId => markerId; /// Marker clustering is managed by [ClusterManager] with [clusterManagerId]. final ClusterManagerId? clusterManagerId; /// The opacity of the marker, between 0.0 and 1.0 inclusive. /// /// 0.0 means fully transparent, 1.0 means fully opaque. final double alpha; /// The icon image point that will be placed at the [position] of the marker. /// /// The image point is specified in normalized coordinates: An anchor of /// (0.0, 0.0) means the top left corner of the image. An anchor /// of (1.0, 1.0) means the bottom right corner of the image. final Offset anchor; /// True if the marker icon consumes tap events. If not, the map will perform /// default tap handling by centering the map on the marker and displaying its /// info window. final bool consumeTapEvents; /// True if the marker is draggable by user touch events. final bool draggable; /// True if the marker is rendered flatly against the surface of the Earth, so /// that it will rotate and tilt along with map camera movements. final bool flat; /// A description of the bitmap used to draw the marker icon. final BitmapDescriptor icon; /// A Google Maps InfoWindow. /// /// The window is displayed when the marker is tapped. final InfoWindow infoWindow; /// Geographical location of the marker. final LatLng position; /// Rotation of the marker image in degrees clockwise from the [anchor] point. final double rotation; /// True if the marker is visible. final bool visible; /// The z-index of the marker, used to determine relative drawing order of /// map overlays. /// /// Overlays are drawn in order of z-index, so that lower values means drawn /// earlier, and thus appearing to be closer to the surface of the Earth. final double zIndex; /// Callbacks to receive tap events for markers placed on this map. final VoidCallback? onTap; /// Signature reporting the new [LatLng] at the start of a drag event. final ValueChanged<LatLng>? onDragStart; /// Signature reporting the new [LatLng] at the end of a drag event. final ValueChanged<LatLng>? onDragEnd; /// Signature reporting the new [LatLng] during the drag event. final ValueChanged<LatLng>? onDrag; /// Creates a new [Marker] object whose values are the same as this instance, /// unless overwritten by the specified parameters. Marker copyWith({ double? alphaParam, Offset? anchorParam, bool? consumeTapEventsParam, bool? draggableParam, bool? flatParam, BitmapDescriptor? iconParam, InfoWindow? infoWindowParam, LatLng? positionParam, double? rotationParam, bool? visibleParam, double? zIndexParam, VoidCallback? onTapParam, ValueChanged<LatLng>? onDragStartParam, ValueChanged<LatLng>? onDragParam, ValueChanged<LatLng>? onDragEndParam, ClusterManagerId? clusterManagerIdParam, }) { return Marker( markerId: markerId, alpha: alphaParam ?? alpha, anchor: anchorParam ?? anchor, consumeTapEvents: consumeTapEventsParam ?? consumeTapEvents, draggable: draggableParam ?? draggable, flat: flatParam ?? flat, icon: iconParam ?? icon, infoWindow: infoWindowParam ?? infoWindow, position: positionParam ?? position, rotation: rotationParam ?? rotation, visible: visibleParam ?? visible, zIndex: zIndexParam ?? zIndex, onTap: onTapParam ?? onTap, onDragStart: onDragStartParam ?? onDragStart, onDrag: onDragParam ?? onDrag, onDragEnd: onDragEndParam ?? onDragEnd, clusterManagerId: clusterManagerIdParam ?? clusterManagerId, ); } /// Creates a new [Marker] object whose values are the same as this instance. @override Marker clone() => copyWith(); /// Converts this object to something serializable in JSON. @override Object toJson() { final Map<String, Object> json = <String, Object>{}; void addIfPresent(String fieldName, Object? value) { if (value != null) { json[fieldName] = value; } } addIfPresent('markerId', markerId.value); addIfPresent('alpha', alpha); addIfPresent('anchor', _offsetToJson(anchor)); addIfPresent('consumeTapEvents', consumeTapEvents); addIfPresent('draggable', draggable); addIfPresent('flat', flat); addIfPresent('icon', icon.toJson()); addIfPresent('infoWindow', infoWindow._toJson()); addIfPresent('position', position.toJson()); addIfPresent('rotation', rotation); addIfPresent('visible', visible); addIfPresent('zIndex', zIndex); addIfPresent('clusterManagerId', clusterManagerId?.value); return json; } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is Marker && markerId == other.markerId && alpha == other.alpha && anchor == other.anchor && consumeTapEvents == other.consumeTapEvents && draggable == other.draggable && flat == other.flat && icon == other.icon && infoWindow == other.infoWindow && position == other.position && rotation == other.rotation && visible == other.visible && zIndex == other.zIndex && clusterManagerId == other.clusterManagerId; } @override int get hashCode => markerId.hashCode; @override String toString() { return 'Marker{markerId: $markerId, alpha: $alpha, anchor: $anchor, ' 'consumeTapEvents: $consumeTapEvents, draggable: $draggable, flat: $flat, ' 'icon: $icon, infoWindow: $infoWindow, position: $position, rotation: $rotation, ' 'visible: $visible, zIndex: $zIndex, onTap: $onTap, onDragStart: $onDragStart, ' 'onDrag: $onDrag, onDragEnd: $onDragEnd, clusterManagerId: $clusterManagerId}'; } }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart", "repo_id": "packages", "token_count": 3623 }
966
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../map_configuration.dart'; /// Returns a JSON representation of [config]. /// /// This is intended for two purposes: /// - Conversion of [MapConfiguration] to the map options dictionary used by /// legacy platform interface methods. /// - Conversion of [MapConfiguration] to the default method channel /// implementation's representation. /// /// Both of these are parts of the public interface, so any change to the /// representation other than adding a new field requires a breaking change to /// the package. Map<String, Object> jsonForMapConfiguration(MapConfiguration config) { final EdgeInsets? padding = config.padding; return <String, Object>{ if (config.compassEnabled != null) 'compassEnabled': config.compassEnabled!, if (config.mapToolbarEnabled != null) 'mapToolbarEnabled': config.mapToolbarEnabled!, if (config.cameraTargetBounds != null) 'cameraTargetBounds': config.cameraTargetBounds!.toJson(), if (config.mapType != null) 'mapType': config.mapType!.index, if (config.minMaxZoomPreference != null) 'minMaxZoomPreference': config.minMaxZoomPreference!.toJson(), if (config.rotateGesturesEnabled != null) 'rotateGesturesEnabled': config.rotateGesturesEnabled!, if (config.scrollGesturesEnabled != null) 'scrollGesturesEnabled': config.scrollGesturesEnabled!, if (config.tiltGesturesEnabled != null) 'tiltGesturesEnabled': config.tiltGesturesEnabled!, if (config.zoomControlsEnabled != null) 'zoomControlsEnabled': config.zoomControlsEnabled!, if (config.zoomGesturesEnabled != null) 'zoomGesturesEnabled': config.zoomGesturesEnabled!, if (config.liteModeEnabled != null) 'liteModeEnabled': config.liteModeEnabled!, if (config.trackCameraPosition != null) 'trackCameraPosition': config.trackCameraPosition!, if (config.myLocationEnabled != null) 'myLocationEnabled': config.myLocationEnabled!, if (config.myLocationButtonEnabled != null) 'myLocationButtonEnabled': config.myLocationButtonEnabled!, if (padding != null) 'padding': <double>[ padding.top, padding.left, padding.bottom, padding.right, ], if (config.indoorViewEnabled != null) 'indoorEnabled': config.indoorViewEnabled!, if (config.trafficEnabled != null) 'trafficEnabled': config.trafficEnabled!, if (config.buildingsEnabled != null) 'buildingsEnabled': config.buildingsEnabled!, if (config.cloudMapId != null) 'cloudMapId': config.cloudMapId!, if (config.style != null) 'style': config.style!, }; }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart", "repo_id": "packages", "token_count": 915 }
967
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; const String _kCloudMapId = '000000000000000'; // Dummy map ID. void main() { group('diffs', () { // A options instance with every field set, to test diffs against. final MapConfiguration diffBase = MapConfiguration( webGestureHandling: WebGestureHandling.auto, compassEnabled: false, mapToolbarEnabled: false, cameraTargetBounds: CameraTargetBounds(LatLngBounds( northeast: const LatLng(30, 20), southwest: const LatLng(10, 40))), mapType: MapType.normal, minMaxZoomPreference: const MinMaxZoomPreference(1.0, 10.0), rotateGesturesEnabled: false, scrollGesturesEnabled: false, tiltGesturesEnabled: false, fortyFiveDegreeImageryEnabled: false, trackCameraPosition: false, zoomControlsEnabled: false, zoomGesturesEnabled: false, liteModeEnabled: false, myLocationEnabled: false, myLocationButtonEnabled: false, padding: const EdgeInsets.all(5.0), indoorViewEnabled: false, trafficEnabled: false, buildingsEnabled: false, style: 'diff base style', ); test('only include changed fields', () async { const MapConfiguration nullOptions = MapConfiguration(); // Everything should be null since nothing changed. expect(diffBase.diffFrom(diffBase), nullOptions); }); test('only apply non-null fields', () async { const MapConfiguration smallDiff = MapConfiguration(compassEnabled: true); final MapConfiguration updated = diffBase.applyDiff(smallDiff); // The diff should be updated. expect(updated.compassEnabled, true); // Spot check that other fields weren't stomped. expect(updated.mapToolbarEnabled, isNot(null)); expect(updated.cameraTargetBounds, isNot(null)); expect(updated.mapType, isNot(null)); expect(updated.zoomControlsEnabled, isNot(null)); expect(updated.liteModeEnabled, isNot(null)); expect(updated.padding, isNot(null)); expect(updated.trafficEnabled, isNot(null)); expect(updated.cloudMapId, null); }); test('handle webGestureHandling', () async { const MapConfiguration diff = MapConfiguration(webGestureHandling: WebGestureHandling.none); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.webGestureHandling, WebGestureHandling.none); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle compassEnabled', () async { const MapConfiguration diff = MapConfiguration(compassEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.compassEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle mapToolbarEnabled', () async { const MapConfiguration diff = MapConfiguration(mapToolbarEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.mapToolbarEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle cameraTargetBounds', () async { final CameraTargetBounds newBounds = CameraTargetBounds(LatLngBounds( northeast: const LatLng(55, 15), southwest: const LatLng(5, 15))); final MapConfiguration diff = MapConfiguration(cameraTargetBounds: newBounds); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.cameraTargetBounds, newBounds); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle mapType', () async { const MapConfiguration diff = MapConfiguration(mapType: MapType.satellite); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.mapType, MapType.satellite); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle minMaxZoomPreference', () async { const MinMaxZoomPreference newZoomPref = MinMaxZoomPreference(3.3, 4.5); const MapConfiguration diff = MapConfiguration(minMaxZoomPreference: newZoomPref); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.minMaxZoomPreference, newZoomPref); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle rotateGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(rotateGesturesEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.rotateGesturesEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle scrollGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(scrollGesturesEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.scrollGesturesEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle tiltGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(tiltGesturesEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.tiltGesturesEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle fortyFiveDegreeImageryEnabled', () async { const MapConfiguration diff = MapConfiguration(fortyFiveDegreeImageryEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.fortyFiveDegreeImageryEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle trackCameraPosition', () async { const MapConfiguration diff = MapConfiguration(trackCameraPosition: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.trackCameraPosition, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle zoomControlsEnabled', () async { const MapConfiguration diff = MapConfiguration(zoomControlsEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.zoomControlsEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle zoomGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(zoomGesturesEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.zoomGesturesEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle liteModeEnabled', () async { const MapConfiguration diff = MapConfiguration(liteModeEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.liteModeEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle myLocationEnabled', () async { const MapConfiguration diff = MapConfiguration(myLocationEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.myLocationEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle myLocationButtonEnabled', () async { const MapConfiguration diff = MapConfiguration(myLocationButtonEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.myLocationButtonEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle padding', () async { const EdgeInsets newPadding = EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0); const MapConfiguration diff = MapConfiguration(padding: newPadding); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.padding, newPadding); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle indoorViewEnabled', () async { const MapConfiguration diff = MapConfiguration(indoorViewEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.indoorViewEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle trafficEnabled', () async { const MapConfiguration diff = MapConfiguration(trafficEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.trafficEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle buildingsEnabled', () async { const MapConfiguration diff = MapConfiguration(buildingsEnabled: true); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.buildingsEnabled, true); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle cloudMapId', () async { const MapConfiguration diff = MapConfiguration(cloudMapId: _kCloudMapId); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.cloudMapId, _kCloudMapId); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); test('handle style', () async { const String aStlye = 'a style'; const MapConfiguration diff = MapConfiguration(style: aStlye); const MapConfiguration empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); // A diff applied to empty options should be the diff itself. expect(empty.applyDiff(diff), diff); // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. expect(updated.style, aStlye); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); }); group('isEmpty', () { test('is true for empty', () async { const MapConfiguration nullOptions = MapConfiguration(); expect(nullOptions.isEmpty, true); }); test('is false with compassEnabled', () async { const MapConfiguration diff = MapConfiguration(compassEnabled: true); expect(diff.isEmpty, false); }); test('is false with mapToolbarEnabled', () async { const MapConfiguration diff = MapConfiguration(mapToolbarEnabled: true); expect(diff.isEmpty, false); }); test('is false with cameraTargetBounds', () async { final CameraTargetBounds newBounds = CameraTargetBounds(LatLngBounds( northeast: const LatLng(55, 15), southwest: const LatLng(5, 15))); final MapConfiguration diff = MapConfiguration(cameraTargetBounds: newBounds); expect(diff.isEmpty, false); }); test('is false with mapType', () async { const MapConfiguration diff = MapConfiguration(mapType: MapType.satellite); expect(diff.isEmpty, false); }); test('is false with minMaxZoomPreference', () async { const MinMaxZoomPreference newZoomPref = MinMaxZoomPreference(3.3, 4.5); const MapConfiguration diff = MapConfiguration(minMaxZoomPreference: newZoomPref); expect(diff.isEmpty, false); }); test('is false with rotateGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(rotateGesturesEnabled: true); expect(diff.isEmpty, false); }); test('is false with scrollGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(scrollGesturesEnabled: true); expect(diff.isEmpty, false); }); test('is false with tiltGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(tiltGesturesEnabled: true); expect(diff.isEmpty, false); }); test('is false with trackCameraPosition', () async { const MapConfiguration diff = MapConfiguration(trackCameraPosition: true); expect(diff.isEmpty, false); }); test('is false with zoomControlsEnabled', () async { const MapConfiguration diff = MapConfiguration(zoomControlsEnabled: true); expect(diff.isEmpty, false); }); test('is false with zoomGesturesEnabled', () async { const MapConfiguration diff = MapConfiguration(zoomGesturesEnabled: true); expect(diff.isEmpty, false); }); test('is false with liteModeEnabled', () async { const MapConfiguration diff = MapConfiguration(liteModeEnabled: true); expect(diff.isEmpty, false); }); test('is false with myLocationEnabled', () async { const MapConfiguration diff = MapConfiguration(myLocationEnabled: true); expect(diff.isEmpty, false); }); test('is false with myLocationButtonEnabled', () async { const MapConfiguration diff = MapConfiguration(myLocationButtonEnabled: true); expect(diff.isEmpty, false); }); test('is false with padding', () async { const EdgeInsets newPadding = EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0); const MapConfiguration diff = MapConfiguration(padding: newPadding); expect(diff.isEmpty, false); }); test('is false with indoorViewEnabled', () async { const MapConfiguration diff = MapConfiguration(indoorViewEnabled: true); expect(diff.isEmpty, false); }); test('is false with trafficEnabled', () async { const MapConfiguration diff = MapConfiguration(trafficEnabled: true); expect(diff.isEmpty, false); }); test('is false with buildingsEnabled', () async { const MapConfiguration diff = MapConfiguration(buildingsEnabled: true); expect(diff.isEmpty, false); }); test('is false with cloudMapId', () async { const MapConfiguration diff = MapConfiguration(cloudMapId: _kCloudMapId); expect(diff.isEmpty, false); }); test('is false with style', () async { const MapConfiguration diff = MapConfiguration(style: 'a style'); expect(diff.isEmpty, false); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart", "repo_id": "packages", "token_count": 7310 }
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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'; // ignore: implementation_imports import 'package:google_maps_flutter_web/src/utils.dart'; import 'package:integration_test/integration_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'google_maps_controller_test.mocks.dart'; // This value is used when comparing long~num, like // LatLng values. const String _kCloudMapId = '000000000000000'; // Dummy map ID. @GenerateNiceMocks(<MockSpec<dynamic>>[ MockSpec<CirclesController>(), MockSpec<PolygonsController>(), MockSpec<PolylinesController>(), MockSpec<MarkersController>(), MockSpec<TileOverlaysController>(), ]) /// Test Google Map Controller void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('GoogleMapController', () { const int mapId = 33930; late GoogleMapController controller; late StreamController<MapEvent<Object?>> stream; // Creates a controller with the default mapId and stream controller, and any `options` needed. GoogleMapController createController({ CameraPosition initialCameraPosition = const CameraPosition(target: LatLng(0, 0)), MapObjects mapObjects = const MapObjects(), MapConfiguration mapConfiguration = const MapConfiguration(), }) { return GoogleMapController( mapId: mapId, streamController: stream, widgetConfiguration: MapWidgetConfiguration( initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr), mapObjects: mapObjects, mapConfiguration: mapConfiguration, ); } setUp(() { stream = StreamController<MapEvent<Object?>>.broadcast(); }); group('construct/dispose', () { setUp(() { controller = createController(); }); testWidgets('constructor creates widget', (WidgetTester tester) async { expect(controller.widget, isNotNull); expect(controller.widget, isA<HtmlElementView>()); expect((controller.widget! as HtmlElementView).viewType, endsWith('$mapId')); }); testWidgets('widget is cached when reused', (WidgetTester tester) async { final Widget? first = controller.widget; final Widget? again = controller.widget; expect(identical(first, again), isTrue); }); group('dispose', () { testWidgets('closes the stream and removes the widget', (WidgetTester tester) async { controller.dispose(); expect(stream.isClosed, isTrue); expect(controller.widget, isNull); }); testWidgets('cannot call getVisibleRegion after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { await controller.getVisibleRegion(); }, throwsAssertionError); }); testWidgets('cannot call getScreenCoordinate after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { await controller.getScreenCoordinate( const LatLng(43.3072465, -5.6918241), ); }, throwsAssertionError); }); testWidgets('cannot call getLatLng after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { await controller.getLatLng( const ScreenCoordinate(x: 640, y: 480), ); }, throwsAssertionError); }); testWidgets('cannot call moveCamera after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { await controller.moveCamera(CameraUpdate.zoomIn()); }, throwsAssertionError); }); testWidgets('cannot call getZoomLevel after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { await controller.getZoomLevel(); }, throwsAssertionError); }); testWidgets('cannot updateCircles after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { controller.updateCircles( CircleUpdates.from( const <Circle>{}, const <Circle>{}, ), ); }, throwsAssertionError); }); testWidgets('cannot updatePolygons after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { controller.updatePolygons( PolygonUpdates.from( const <Polygon>{}, const <Polygon>{}, ), ); }, throwsAssertionError); }); testWidgets('cannot updatePolylines after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { controller.updatePolylines( PolylineUpdates.from( const <Polyline>{}, const <Polyline>{}, ), ); }, throwsAssertionError); }); testWidgets('cannot updateMarkers after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { controller.updateMarkers( MarkerUpdates.from( const <Marker>{}, const <Marker>{}, ), ); }, throwsAssertionError); expect(() { controller.showInfoWindow(const MarkerId('any')); }, throwsAssertionError); expect(() { controller.hideInfoWindow(const MarkerId('any')); }, throwsAssertionError); }); testWidgets('cannot updateTileOverlays after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { controller.updateTileOverlays(const <TileOverlay>{}); }, throwsAssertionError); }); testWidgets('isInfoWindowShown defaults to false', (WidgetTester tester) async { controller.dispose(); expect(controller.isInfoWindowShown(const MarkerId('any')), false); }); }); }); group('init', () { late MockCirclesController circles; late MockMarkersController markers; late MockPolygonsController polygons; late MockPolylinesController polylines; late MockTileOverlaysController tileOverlays; late gmaps.GMap map; setUp(() { circles = MockCirclesController(); markers = MockMarkersController(); polygons = MockPolygonsController(); polylines = MockPolylinesController(); tileOverlays = MockTileOverlaysController(); map = gmaps.GMap(createDivElement()); }); testWidgets('listens to map events', (WidgetTester tester) async { controller = createController() ..debugSetOverrides( createMap: (_, __) => map, circles: circles, markers: markers, polygons: polygons, polylines: polylines, ) ..init(); // Trigger events on the map, and verify they've been broadcast to the stream final Stream<MapEvent<Object?>> capturedEvents = stream.stream.take(5); gmaps.Event.trigger( map, 'click', <Object>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)], ); gmaps.Event.trigger( map, 'rightclick', <Object>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)], ); // The following line causes 2 events gmaps.Event.trigger(map, 'bounds_changed', <Object>[]); gmaps.Event.trigger(map, 'idle', <Object>[]); final List<MapEvent<Object?>> events = await capturedEvents.toList(); expect(events[0], isA<MapTapEvent>()); expect(events[1], isA<MapLongPressEvent>()); expect(events[2], isA<CameraMoveStartedEvent>()); expect(events[3], isA<CameraMoveEvent>()); expect(events[4], isA<CameraIdleEvent>()); }); testWidgets("binds geometry controllers to map's", (WidgetTester tester) async { controller = createController() ..debugSetOverrides( createMap: (_, __) => map, circles: circles, markers: markers, polygons: polygons, polylines: polylines, tileOverlays: tileOverlays, ) ..init(); verify(circles.bindToMap(mapId, map)); verify(markers.bindToMap(mapId, map)); verify(polygons.bindToMap(mapId, map)); verify(polylines.bindToMap(mapId, map)); verify(tileOverlays.bindToMap(mapId, map)); }); testWidgets('renders initial geometry', (WidgetTester tester) async { final MapObjects mapObjects = MapObjects(circles: <Circle>{ const Circle( circleId: CircleId('circle-1'), zIndex: 1234, ), }, markers: <Marker>{ const Marker( markerId: MarkerId('marker-1'), infoWindow: InfoWindow( title: 'title for test', snippet: 'snippet for test', ), ), }, polygons: <Polygon>{ const Polygon(polygonId: PolygonId('polygon-1'), points: <LatLng>[ LatLng(43.355114, -5.851333), LatLng(43.354797, -5.851860), LatLng(43.354469, -5.851318), LatLng(43.354762, -5.850824), ]), const Polygon( polygonId: PolygonId('polygon-2-with-holes'), points: <LatLng>[ LatLng(43.355114, -5.851333), LatLng(43.354797, -5.851860), LatLng(43.354469, -5.851318), LatLng(43.354762, -5.850824), ], holes: <List<LatLng>>[ <LatLng>[ LatLng(41.354797, -6.851860), LatLng(41.354469, -6.851318), LatLng(41.354762, -6.850824), ] ], ), }, polylines: <Polyline>{ const Polyline(polylineId: PolylineId('polyline-1'), points: <LatLng>[ LatLng(43.355114, -5.851333), LatLng(43.354797, -5.851860), LatLng(43.354469, -5.851318), LatLng(43.354762, -5.850824), ]) }, tileOverlays: <TileOverlay>{ const TileOverlay(tileOverlayId: TileOverlayId('overlay-1')) }); controller = createController(mapObjects: mapObjects) ..debugSetOverrides( circles: circles, markers: markers, polygons: polygons, polylines: polylines, tileOverlays: tileOverlays, ) ..init(); verify(circles.addCircles(mapObjects.circles)); verify(markers.addMarkers(mapObjects.markers)); verify(polygons.addPolygons(mapObjects.polygons)); verify(polylines.addPolylines(mapObjects.polylines)); verify(tileOverlays.addTileOverlays(mapObjects.tileOverlays)); }); group('Initialization options', () { testWidgets('translates initial options', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( mapType: MapType.satellite, zoomControlsEnabled: true, cloudMapId: _kCloudMapId, fortyFiveDegreeImageryEnabled: false, )); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }); controller.init(); expect(capturedOptions, isNotNull); expect(capturedOptions!.mapTypeId, gmaps.MapTypeId.SATELLITE); expect(capturedOptions!.zoomControl, true); expect(capturedOptions!.mapId, _kCloudMapId); expect(capturedOptions!.gestureHandling, 'auto', reason: 'by default the map handles zoom/pan gestures internally'); expect(capturedOptions!.rotateControl, false); expect(capturedOptions!.tilt, 0); }); testWidgets('translates fortyFiveDegreeImageryEnabled option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( scrollGesturesEnabled: false, fortyFiveDegreeImageryEnabled: true, )); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }); controller.init(); expect(capturedOptions, isNotNull); expect(capturedOptions!.rotateControl, true); expect(capturedOptions!.tilt, isNull); }); testWidgets('translates webGestureHandling option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( zoomGesturesEnabled: false, webGestureHandling: WebGestureHandling.greedy, )); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }); controller.init(); expect(capturedOptions, isNotNull); expect(capturedOptions!.gestureHandling, 'greedy'); }); testWidgets('sets initial position when passed', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( initialCameraPosition: const CameraPosition( target: LatLng(43.308, -5.6910), zoom: 12, ), ) ..debugSetOverrides(createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }) ..init(); expect(capturedOptions, isNotNull); expect(capturedOptions!.zoom, 12); expect(capturedOptions!.center, isNotNull); }); testWidgets('translates style option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; const String style = ''' [{ "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; controller = createController( mapConfiguration: const MapConfiguration(style: style)); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }); controller.init(); expect(capturedOptions, isNotNull); expect(capturedOptions!.styles?.length, 1); }); testWidgets('stores style errors for later querying', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( style: '[[invalid style', zoomControlsEnabled: true)); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; return map; }); controller.init(); expect(controller.lastStyleError, isNotNull); // Style failures should not prevent other options from being set. expect(capturedOptions, isNotNull); expect(capturedOptions!.zoomControl, true); }); testWidgets('setting invalid style leaves previous style', (WidgetTester tester) async { gmaps.MapOptions? initialCapturedOptions; gmaps.MapOptions? updatedCapturedOptions; const String style = ''' [{ "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; controller = createController( mapConfiguration: const MapConfiguration(style: style)); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { initialCapturedOptions = options; return map; }, setOptions: (gmaps.MapOptions options) { updatedCapturedOptions = options; }, ); controller.init(); controller.updateMapConfiguration( const MapConfiguration(style: '[[invalid style')); expect(initialCapturedOptions, isNotNull); expect(initialCapturedOptions!.styles?.length, 1); // The styles should not have changed. expect( updatedCapturedOptions!.styles, initialCapturedOptions!.styles); }); }); group('Traffic Layer', () { testWidgets('by default is disabled', (WidgetTester tester) async { controller = createController()..init(); expect(controller.trafficLayer, isNull); }); testWidgets('initializes with traffic layer', (WidgetTester tester) async { controller = createController( mapConfiguration: const MapConfiguration( trafficEnabled: true, )) ..debugSetOverrides(createMap: (_, __) => map) ..init(); expect(controller.trafficLayer, isNotNull); }); }); }); // These are the methods that are delegated to the gmaps.GMap object, that we can mock... group('Map control methods', () { late gmaps.GMap map; setUp(() { map = gmaps.GMap( createDivElement(), gmaps.MapOptions() ..zoom = 10 ..center = gmaps.LatLng(0, 0), ); controller = createController() ..debugSetOverrides(createMap: (_, __) => map) ..init(); }); group('updateMapConfiguration', () { testWidgets('can update `options`', (WidgetTester tester) async { controller.updateMapConfiguration(const MapConfiguration( mapType: MapType.satellite, )); expect(map.mapTypeId, gmaps.MapTypeId.SATELLITE); }); testWidgets('can turn on/off traffic', (WidgetTester tester) async { expect(controller.trafficLayer, isNull); controller.updateMapConfiguration(const MapConfiguration( trafficEnabled: true, )); expect(controller.trafficLayer, isNotNull); controller.updateMapConfiguration(const MapConfiguration( trafficEnabled: false, )); expect(controller.trafficLayer, isNull); }); testWidgets('can update style', (WidgetTester tester) async { const String style = ''' [{ "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; controller .updateMapConfiguration(const MapConfiguration(style: style)); expect(controller.styles.length, 1); }); testWidgets('can update style', (WidgetTester tester) async { controller.updateMapConfiguration( const MapConfiguration(style: '[[[invalid style')); expect(controller.styles, isEmpty); expect(controller.lastStyleError, isNotNull); }); }); group('viewport getters', () { testWidgets('getVisibleRegion', (WidgetTester tester) async { final gmaps.LatLng gmCenter = map.center!; final LatLng center = LatLng(gmCenter.lat.toDouble(), gmCenter.lng.toDouble()); final LatLngBounds bounds = await controller.getVisibleRegion(); expect(bounds.contains(center), isTrue, reason: 'The computed visible region must contain the center of the created map.'); }); testWidgets('getZoomLevel', (WidgetTester tester) async { expect(await controller.getZoomLevel(), map.zoom); }); }); group('moveCamera', () { // Tested in projection_test.dart }); group('map.projection methods', () { // Tested in projection_test.dart }); }); // These are the methods that get forwarded to other controllers, so we just verify calls. group('Pass-through methods', () { testWidgets('updateCircles', (WidgetTester tester) async { final MockCirclesController mock = MockCirclesController(); controller = createController()..debugSetOverrides(circles: mock); final Set<Circle> previous = <Circle>{ const Circle(circleId: CircleId('to-be-updated')), const Circle(circleId: CircleId('to-be-removed')), }; final Set<Circle> current = <Circle>{ const Circle(circleId: CircleId('to-be-updated'), visible: false), const Circle(circleId: CircleId('to-be-added')), }; controller.updateCircles(CircleUpdates.from(previous, current)); verify(mock.removeCircles(<CircleId>{ const CircleId('to-be-removed'), })); verify(mock.addCircles(<Circle>{ const Circle(circleId: CircleId('to-be-added')), })); verify(mock.changeCircles(<Circle>{ const Circle(circleId: CircleId('to-be-updated'), visible: false), })); }); testWidgets('updateMarkers', (WidgetTester tester) async { final MockMarkersController mock = MockMarkersController(); controller = createController()..debugSetOverrides(markers: mock); final Set<Marker> previous = <Marker>{ const Marker(markerId: MarkerId('to-be-updated')), const Marker(markerId: MarkerId('to-be-removed')), }; final Set<Marker> current = <Marker>{ const Marker(markerId: MarkerId('to-be-updated'), visible: false), const Marker(markerId: MarkerId('to-be-added')), }; controller.updateMarkers(MarkerUpdates.from(previous, current)); verify(mock.removeMarkers(<MarkerId>{ const MarkerId('to-be-removed'), })); verify(mock.addMarkers(<Marker>{ const Marker(markerId: MarkerId('to-be-added')), })); verify(mock.changeMarkers(<Marker>{ const Marker(markerId: MarkerId('to-be-updated'), visible: false), })); }); testWidgets('updatePolygons', (WidgetTester tester) async { final MockPolygonsController mock = MockPolygonsController(); controller = createController()..debugSetOverrides(polygons: mock); final Set<Polygon> previous = <Polygon>{ const Polygon(polygonId: PolygonId('to-be-updated')), const Polygon(polygonId: PolygonId('to-be-removed')), }; final Set<Polygon> current = <Polygon>{ const Polygon(polygonId: PolygonId('to-be-updated'), visible: false), const Polygon(polygonId: PolygonId('to-be-added')), }; controller.updatePolygons(PolygonUpdates.from(previous, current)); verify(mock.removePolygons(<PolygonId>{ const PolygonId('to-be-removed'), })); verify(mock.addPolygons(<Polygon>{ const Polygon(polygonId: PolygonId('to-be-added')), })); verify(mock.changePolygons(<Polygon>{ const Polygon(polygonId: PolygonId('to-be-updated'), visible: false), })); }); testWidgets('updatePolylines', (WidgetTester tester) async { final MockPolylinesController mock = MockPolylinesController(); controller = createController()..debugSetOverrides(polylines: mock); final Set<Polyline> previous = <Polyline>{ const Polyline(polylineId: PolylineId('to-be-updated')), const Polyline(polylineId: PolylineId('to-be-removed')), }; final Set<Polyline> current = <Polyline>{ const Polyline( polylineId: PolylineId('to-be-updated'), visible: false, ), const Polyline(polylineId: PolylineId('to-be-added')), }; controller.updatePolylines(PolylineUpdates.from(previous, current)); verify(mock.removePolylines(<PolylineId>{ const PolylineId('to-be-removed'), })); verify(mock.addPolylines(<Polyline>{ const Polyline(polylineId: PolylineId('to-be-added')), })); verify(mock.changePolylines(<Polyline>{ const Polyline( polylineId: PolylineId('to-be-updated'), visible: false, ), })); }); testWidgets('updateTileOverlays', (WidgetTester tester) async { final MockTileOverlaysController mock = MockTileOverlaysController(); controller = createController( mapObjects: MapObjects(tileOverlays: <TileOverlay>{ const TileOverlay(tileOverlayId: TileOverlayId('to-be-updated')), const TileOverlay(tileOverlayId: TileOverlayId('to-be-removed')), })) ..debugSetOverrides(tileOverlays: mock); controller.updateTileOverlays(<TileOverlay>{ const TileOverlay( tileOverlayId: TileOverlayId('to-be-updated'), visible: false), const TileOverlay(tileOverlayId: TileOverlayId('to-be-added')), }); verify(mock.removeTileOverlays(<TileOverlayId>{ const TileOverlayId('to-be-removed'), })); verify(mock.addTileOverlays(<TileOverlay>{ const TileOverlay(tileOverlayId: TileOverlayId('to-be-added')), })); verify(mock.changeTileOverlays(<TileOverlay>{ const TileOverlay( tileOverlayId: TileOverlayId('to-be-updated'), visible: false), })); }); testWidgets('infoWindow visibility', (WidgetTester tester) async { final MockMarkersController mock = MockMarkersController(); const MarkerId markerId = MarkerId('marker-with-infowindow'); when(mock.isInfoWindowShown(markerId)).thenReturn(true); controller = createController()..debugSetOverrides(markers: mock); controller.showInfoWindow(markerId); verify(mock.showMarkerInfoWindow(markerId)); controller.hideInfoWindow(markerId); verify(mock.hideMarkerInfoWindow(markerId)); controller.isInfoWindowShown(markerId); verify(mock.isInfoWindowShown(markerId)); }); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart", "repo_id": "packages", "token_count": 12384 }
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.googlesignin; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.Task; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.googlesignin.Messages.FlutterError; import io.flutter.plugins.googlesignin.Messages.InitParams; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; public class GoogleSignInTest { @Mock Context mockContext; @Mock Resources mockResources; @Mock Activity mockActivity; @Mock BinaryMessenger mockMessenger; @Spy Messages.Result<Void> voidResult; @Spy Messages.Result<Boolean> boolResult; @Spy Messages.Result<Messages.UserData> userDataResult; @Mock GoogleSignInWrapper mockGoogleSignIn; @Mock GoogleSignInAccount account; @Mock GoogleSignInClient mockClient; @Mock Task<GoogleSignInAccount> mockSignInTask; @SuppressWarnings("deprecation") @Mock PluginRegistry.Registrar mockRegistrar; private GoogleSignInPlugin.Delegate plugin; private AutoCloseable mockCloseable; @Before public void setUp() { mockCloseable = MockitoAnnotations.openMocks(this); when(mockRegistrar.messenger()).thenReturn(mockMessenger); when(mockRegistrar.context()).thenReturn(mockContext); when(mockRegistrar.activity()).thenReturn(mockActivity); when(mockContext.getResources()).thenReturn(mockResources); plugin = new GoogleSignInPlugin.Delegate(mockRegistrar.context(), mockGoogleSignIn); plugin.setUpRegistrar(mockRegistrar); } @After public void tearDown() throws Exception { mockCloseable.close(); } @Test public void requestScopes_ResultErrorIfAccountIsNull() { when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(null); plugin.requestScopes(Collections.singletonList("requestedScope"), boolResult); ArgumentCaptor<Throwable> resultCaptor = ArgumentCaptor.forClass(Throwable.class); verify(boolResult).error(resultCaptor.capture()); FlutterError error = (FlutterError) resultCaptor.getValue(); Assert.assertEquals("sign_in_required", error.code); Assert.assertEquals("No account to grant scopes.", error.getMessage()); } @Test public void requestScopes_ResultTrueIfAlreadyGranted() { Scope requestedScope = new Scope("requestedScope"); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(true); plugin.requestScopes(Collections.singletonList("requestedScope"), boolResult); verify(boolResult).success(true); } @Test public void requestScopes_RequestsPermissionIfNotGranted() { Scope requestedScope = new Scope("requestedScope"); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.requestScopes(Collections.singletonList("requestedScope"), boolResult); verify(mockGoogleSignIn) .requestPermissions(mockActivity, 53295, account, new Scope[] {requestedScope}); } @Test public void requestScopes_ReturnsFalseIfPermissionDenied() { Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.requestScopes(Collections.singletonList("requestedScope"), boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_CANCELED, new Intent()); verify(boolResult).success(false); } @Test public void requestScopes_ReturnsTrueIfPermissionGranted() { Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.requestScopes(Collections.singletonList("requestedScope"), boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); verify(boolResult).success(true); } @Test public void requestScopes_mayBeCalledRepeatedly_ifAlreadyGranted() { List<String> requestedScopes = Collections.singletonList("requestedScope"); Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.requestScopes(requestedScopes, boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); plugin.requestScopes(requestedScopes, boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); verify(boolResult, times(2)).success(true); } @Test public void requestScopes_mayBeCalledRepeatedly_ifNotSignedIn() { List<String> requestedScopes = Collections.singletonList("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(null); plugin.requestScopes(requestedScopes, boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); plugin.requestScopes(requestedScopes, boolResult); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); ArgumentCaptor<Throwable> resultCaptor = ArgumentCaptor.forClass(Throwable.class); verify(boolResult, times(2)).error(resultCaptor.capture()); List<Throwable> errors = resultCaptor.getAllValues(); Assert.assertEquals(2, errors.size()); FlutterError error = (FlutterError) errors.get(0); Assert.assertEquals("sign_in_required", error.code); Assert.assertEquals("No account to grant scopes.", error.getMessage()); error = (FlutterError) errors.get(1); Assert.assertEquals("sign_in_required", error.code); Assert.assertEquals("No account to grant scopes.", error.getMessage()); } @Test(expected = IllegalStateException.class) public void signInThrowsWithoutActivity() { final GoogleSignInPlugin.Delegate plugin = new GoogleSignInPlugin.Delegate(mock(Context.class), mock(GoogleSignInWrapper.class)); plugin.signIn(userDataResult); } @Test public void signInSilentlyThatImmediatelyCompletesWithoutResultFinishesWithError() throws ApiException { final String clientId = "fakeClientId"; InitParams params = buildInitParams(clientId, null); initAndAssertServerClientId(params, clientId); ApiException exception = new ApiException(new Status(CommonStatusCodes.SIGN_IN_REQUIRED, "Error text")); when(mockClient.silentSignIn()).thenReturn(mockSignInTask); when(mockSignInTask.isComplete()).thenReturn(true); when(mockSignInTask.getResult(ApiException.class)).thenThrow(exception); plugin.signInSilently(userDataResult); ArgumentCaptor<Throwable> resultCaptor = ArgumentCaptor.forClass(Throwable.class); verify(userDataResult).error(resultCaptor.capture()); FlutterError error = (FlutterError) resultCaptor.getValue(); Assert.assertEquals("sign_in_required", error.code); Assert.assertEquals( "com.google.android.gms.common.api.ApiException: 4: Error text", error.getMessage()); } @Test public void init_LoadsServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; InitParams params = buildInitParams(null, null); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertServerClientId(params, serverClientId); } @Test public void init_InterpretsClientIdAsServerClientId() { final String clientId = "fakeClientId"; InitParams params = buildInitParams(clientId, null); initAndAssertServerClientId(params, clientId); } @Test public void init_ForwardsServerClientId() { final String serverClientId = "fakeServerClientId"; InitParams params = buildInitParams(null, serverClientId); initAndAssertServerClientId(params, serverClientId); } @Test public void init_IgnoresClientIdIfServerClientIdIsProvided() { final String clientId = "fakeClientId"; final String serverClientId = "fakeServerClientId"; InitParams params = buildInitParams(clientId, serverClientId); initAndAssertServerClientId(params, serverClientId); } @Test public void init_PassesForceCodeForRefreshTokenFalseWithServerClientIdParameter() { InitParams params = buildInitParams("fakeClientId", "fakeServerClientId", false); initAndAssertForceCodeForRefreshToken(params, false); } @Test public void init_PassesForceCodeForRefreshTokenTrueWithServerClientIdParameter() { InitParams params = buildInitParams("fakeClientId", "fakeServerClientId", true); initAndAssertForceCodeForRefreshToken(params, true); } @Test public void init_PassesForceCodeForRefreshTokenFalseWithServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; InitParams params = buildInitParams(null, null, false); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertForceCodeForRefreshToken(params, false); } @Test public void init_PassesForceCodeForRefreshTokenTrueWithServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; InitParams params = buildInitParams(null, null, true); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertForceCodeForRefreshToken(params, true); } public void initAndAssertServerClientId(InitParams params, String serverClientId) { ArgumentCaptor<GoogleSignInOptions> optionsCaptor = ArgumentCaptor.forClass(GoogleSignInOptions.class); when(mockGoogleSignIn.getClient(any(Context.class), optionsCaptor.capture())) .thenReturn(mockClient); plugin.init(params); Assert.assertEquals(serverClientId, optionsCaptor.getValue().getServerClientId()); } public void initAndAssertForceCodeForRefreshToken( InitParams params, boolean forceCodeForRefreshToken) { ArgumentCaptor<GoogleSignInOptions> optionsCaptor = ArgumentCaptor.forClass(GoogleSignInOptions.class); when(mockGoogleSignIn.getClient(any(Context.class), optionsCaptor.capture())) .thenReturn(mockClient); plugin.init(params); Assert.assertEquals( forceCodeForRefreshToken, optionsCaptor.getValue().isForceCodeForRefreshToken()); } private static InitParams buildInitParams(String clientId, String serverClientId) { return buildInitParams( Messages.SignInType.STANDARD, Collections.emptyList(), clientId, serverClientId, false); } private static InitParams buildInitParams( String clientId, String serverClientId, boolean forceCodeForRefreshToken) { return buildInitParams( Messages.SignInType.STANDARD, Collections.emptyList(), clientId, serverClientId, forceCodeForRefreshToken); } private static InitParams buildInitParams( Messages.SignInType signInType, List<String> scopes, String clientId, String serverClientId, boolean forceCodeForRefreshToken) { InitParams.Builder builder = new InitParams.Builder(); builder.setSignInType(signInType); builder.setScopes(scopes); if (clientId != null) { builder.setClientId(clientId); } if (serverClientId != null) { builder.setServerClientId(serverClientId); } builder.setForceCodeForRefreshToken(forceCodeForRefreshToken); return builder.build(); } }
packages/packages/google_sign_in/google_sign_in_android/android/src/test/java/io/flutter/plugins/googlesignin/GoogleSignInTest.java/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/android/src/test/java/io/flutter/plugins/googlesignin/GoogleSignInTest.java", "repo_id": "packages", "token_count": 5078 }
970