text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('BlockActionConverter', () { test('can (de)serialize BlockAction', () { final converter = BlockActionConverter(); const actions = <BlockAction>[ NavigateToArticleAction(articleId: 'articleId'), NavigateToFeedCategoryAction(category: Category.top) ]; for (final action in actions) { expect( converter.fromJson(converter.toJson(action)), equals(action), ); } }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/block_action_converter_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/block_action_converter_test.dart", "repo_id": "news_toolkit", "token_count": 245 }
869
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('SlideBlock', () { test('can be (de)serialized', () { final block = SlideBlock( caption: 'caption', description: 'description', photoCredit: 'photoCredit', imageUrl: 'imageUrl', ); expect( SlideBlock.fromJson(block.toJson()), equals(block), ); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slide_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slide_block_test.dart", "repo_id": "news_toolkit", "token_count": 209 }
870
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; Future<Response> onRequest(RequestContext context, String id) async { if (context.request.method != HttpMethod.get) { return Response(statusCode: HttpStatus.methodNotAllowed); } final queryParams = context.request.url.queryParameters; final limit = int.tryParse(queryParams['limit'] ?? '') ?? 20; final offset = int.tryParse(queryParams['offset'] ?? '') ?? 0; final relatedArticles = await context .read<NewsDataSource>() .getRelatedArticles(id: id, limit: limit, offset: offset); final response = RelatedArticlesResponse( relatedArticles: relatedArticles.blocks, totalCount: relatedArticles.totalBlocks, ); return Response.json(body: response); }
news_toolkit/flutter_news_example/api/routes/api/v1/articles/[id]/related.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/routes/api/v1/articles/[id]/related.dart", "repo_id": "news_toolkit", "token_count": 266 }
871
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:flutter_news_example_api/src/data/in_memory_news_data_source.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../routes/api/v1/search/popular.dart' as route; class _MockNewsDataSource extends Mock implements NewsDataSource {} class _MockRequestContext extends Mock implements RequestContext {} void main() { group('GET /api/v1/search/popular', () { late NewsDataSource newsDataSource; setUp(() { newsDataSource = _MockNewsDataSource(); }); test('responds with a 200 on success.', () async { final expected = PopularSearchResponse( articles: popularArticles.map((item) => item.post).toList(), topics: popularTopics, ); when(() => newsDataSource.getPopularArticles()).thenAnswer( (_) async => expected.articles, ); when( () => newsDataSource.getPopularTopics(), ).thenAnswer((_) async => expected.topics); final request = Request('GET', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.json(), completion(equals(expected.toJson()))); verify(() => newsDataSource.getPopularArticles()).called(1); verify(() => newsDataSource.getPopularTopics()).called(1); }); }); test('responds with 405 when method is not GET.', () async { final request = Request('POST', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }
news_toolkit/flutter_news_example/api/test/routes/search/popular_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/search/popular_test.dart", "repo_id": "news_toolkit", "token_count": 722 }
872
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; /// {@template sticky_ad} /// A bottom-anchored, adaptive ad widget. /// https://developers.google.com/admob/flutter/banner/anchored-adaptive /// {@endtemplate} class StickyAd extends StatefulWidget { /// {@macro sticky_ad} const StickyAd({super.key}); static const padding = EdgeInsets.symmetric( horizontal: AppSpacing.lg + AppSpacing.xs, vertical: AppSpacing.lg, ); @override State<StickyAd> createState() => _StickyAdState(); } class _StickyAdState extends State<StickyAd> { var _adLoaded = false; var _adClosed = false; @override Widget build(BuildContext context) { final deviceWidth = MediaQuery.of(context).size.width; final adWidth = (deviceWidth - StickyAd.padding.left - StickyAd.padding.right) .truncate(); return !_adClosed ? Stack( children: [ if (_adLoaded) const StickyAdCloseIconBackground(), StickyAdContainer( key: const Key('stickyAd_container'), shadowEnabled: _adLoaded, child: BannerAdContent( size: BannerAdSize.anchoredAdaptive, anchoredAdaptiveWidth: adWidth, onAdLoaded: () => setState(() => _adLoaded = true), showProgressIndicator: false, ), ), if (_adLoaded) StickyAdCloseIcon( onAdClosed: () => setState(() => _adClosed = true), ), ], ) : const SizedBox(); } } @visibleForTesting class StickyAdContainer extends StatelessWidget { const StickyAdContainer({ required this.child, required this.shadowEnabled, super.key, }); final Widget child; final bool shadowEnabled; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(top: AppSpacing.md + AppSpacing.xxs), child: DecoratedBox( decoration: BoxDecoration( color: shadowEnabled ? AppColors.white : AppColors.transparent, boxShadow: [ if (shadowEnabled) BoxShadow( color: AppColors.black.withOpacity(0.3), blurRadius: 3, spreadRadius: 1, offset: const Offset(0, 1), ), ], ), child: SafeArea( left: false, top: false, right: false, child: Padding( padding: StickyAd.padding, child: child, ), ), ), ); } } class StickyAdCloseIcon extends StatelessWidget { const StickyAdCloseIcon({ required this.onAdClosed, super.key, }); final VoidCallback onAdClosed; @override Widget build(BuildContext context) { return Positioned( right: AppSpacing.lg, child: GestureDetector( onTap: onAdClosed, child: DecoratedBox( decoration: BoxDecoration( color: AppColors.white, borderRadius: BorderRadius.circular(20), ), child: Padding( padding: const EdgeInsets.all(AppSpacing.xxs), child: Assets.icons.closeCircleFilled.svg(), ), ), ), ); } } @visibleForTesting class StickyAdCloseIconBackground extends StatelessWidget { const StickyAdCloseIconBackground({ super.key, }); @override Widget build(BuildContext context) { return Positioned( right: AppSpacing.lg, child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: AppColors.black.withOpacity(0.3), blurRadius: 3, spreadRadius: 1, offset: const Offset(0, 1), ), ], ), child: Padding( padding: const EdgeInsets.all(AppSpacing.xxs), child: Assets.icons.closeCircleFilled.svg(), ), ), ); } }
news_toolkit/flutter_news_example/lib/ads/widgets/sticky_ad.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/ads/widgets/sticky_ad.dart", "repo_id": "news_toolkit", "token_count": 1991 }
873
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'article_bloc.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ArticleState _$ArticleStateFromJson(Map<String, dynamic> json) => ArticleState( status: $enumDecode(_$ArticleStatusEnumMap, json['status']), title: json['title'] as String?, content: (json['content'] as List<dynamic>?) ?.map((e) => NewsBlock.fromJson(e as Map<String, dynamic>)) .toList() ?? const [], contentTotalCount: json['contentTotalCount'] as int?, contentSeenCount: json['contentSeenCount'] as int? ?? 0, relatedArticles: (json['relatedArticles'] as List<dynamic>?) ?.map((e) => NewsBlock.fromJson(e as Map<String, dynamic>)) .toList() ?? const [], hasMoreContent: json['hasMoreContent'] as bool? ?? true, uri: json['uri'] == null ? null : Uri.parse(json['uri'] as String), hasReachedArticleViewsLimit: json['hasReachedArticleViewsLimit'] as bool? ?? false, isPreview: json['isPreview'] as bool? ?? false, isPremium: json['isPremium'] as bool? ?? false, ); Map<String, dynamic> _$ArticleStateToJson(ArticleState instance) => <String, dynamic>{ 'status': _$ArticleStatusEnumMap[instance.status]!, 'title': instance.title, 'content': instance.content.map((e) => e.toJson()).toList(), 'contentTotalCount': instance.contentTotalCount, 'contentSeenCount': instance.contentSeenCount, 'relatedArticles': instance.relatedArticles.map((e) => e.toJson()).toList(), 'hasMoreContent': instance.hasMoreContent, 'uri': instance.uri?.toString(), 'hasReachedArticleViewsLimit': instance.hasReachedArticleViewsLimit, 'isPreview': instance.isPreview, 'isPremium': instance.isPremium, }; const _$ArticleStatusEnumMap = { ArticleStatus.initial: 'initial', ArticleStatus.loading: 'loading', ArticleStatus.populated: 'populated', ArticleStatus.failure: 'failure', ArticleStatus.shareFailure: 'shareFailure', ArticleStatus.rewardedAdWatchedFailure: 'rewardedAdWatchedFailure', };
news_toolkit/flutter_news_example/lib/article/bloc/article_bloc.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/article/bloc/article_bloc.g.dart", "repo_id": "news_toolkit", "token_count": 832 }
874
export 'bloc/categories_bloc.dart'; export 'widgets/widgets.dart';
news_toolkit/flutter_news_example/lib/categories/categories.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/categories/categories.dart", "repo_id": "news_toolkit", "token_count": 27 }
875
export 'cubit/home_cubit.dart'; export 'view/view.dart';
news_toolkit/flutter_news_example/lib/home/home.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/home/home.dart", "repo_id": "news_toolkit", "token_count": 26 }
876
import 'package:app_ui/app_ui.dart' show AppButton, AppSpacing, Assets; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:form_inputs/form_inputs.dart'; class LoginForm extends StatelessWidget { const LoginForm({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return BlocListener<AppBloc, AppState>( listener: (context, state) { if (state.status.isLoggedIn) { // Pop all routes on top of [LoginModal], then pop the modal itself. Navigator.of(context) .popUntil((route) => route.settings.name == LoginModal.name); Navigator.of(context).pop(); } }, child: BlocListener<LoginBloc, LoginState>( listener: (context, state) { if (state.status.isFailure) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar(content: Text(l10n.authenticationFailure)), ); } }, child: const _LoginContent(), ), ); } } class _LoginContent extends StatelessWidget { const _LoginContent(); @override Widget build(BuildContext context) { final theme = Theme.of(context); return LayoutBuilder( builder: (context, constraints) { return ConstrainedBox( constraints: BoxConstraints(maxHeight: constraints.maxHeight * .75), child: ListView( padding: const EdgeInsets.fromLTRB( AppSpacing.lg, AppSpacing.lg, AppSpacing.lg, AppSpacing.xxlg, ), children: [ const _LoginTitleAndCloseButton(), const SizedBox(height: AppSpacing.sm), const _LoginSubtitle(), const SizedBox(height: AppSpacing.lg), _GoogleLoginButton(), if (theme.platform == TargetPlatform.iOS) ...[ const SizedBox(height: AppSpacing.lg), _AppleLoginButton(), ], const SizedBox(height: AppSpacing.lg), _FacebookLoginButton(), const SizedBox(height: AppSpacing.lg), _TwitterLoginButton(), const SizedBox(height: AppSpacing.lg), _ContinueWithEmailLoginButton() ], ), ); }, ); } } class _LoginTitleAndCloseButton extends StatelessWidget { const _LoginTitleAndCloseButton(); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(right: AppSpacing.sm), child: Text( context.l10n.loginModalTitle, style: Theme.of(context).textTheme.displaySmall, ), ), IconButton( key: const Key('loginForm_closeModal_iconButton'), constraints: const BoxConstraints.tightFor(width: 24, height: 36), padding: EdgeInsets.zero, onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close), ), ], ); } } class _LoginSubtitle extends StatelessWidget { const _LoginSubtitle(); @override Widget build(BuildContext context) { return Text( context.l10n.loginModalSubtitle, style: Theme.of(context).textTheme.titleMedium, ); } } class _AppleLoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton.black( key: const Key('loginForm_appleLogin_appButton'), onPressed: () => context.read<LoginBloc>().add(LoginAppleSubmitted()), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.apple.svg(), const SizedBox(width: AppSpacing.lg), Padding( padding: const EdgeInsets.only(top: AppSpacing.xs), child: Assets.images.continueWithApple.svg(), ), ], ), ); } } class _GoogleLoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton.outlinedWhite( key: const Key('loginForm_googleLogin_appButton'), onPressed: () => context.read<LoginBloc>().add(LoginGoogleSubmitted()), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.google.svg(), const SizedBox(width: AppSpacing.lg), Padding( padding: const EdgeInsets.only(top: AppSpacing.xxs), child: Assets.images.continueWithGoogle.svg(), ), ], ), ); } } class _FacebookLoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton.blueDress( key: const Key('loginForm_facebookLogin_appButton'), onPressed: () => context.read<LoginBloc>().add(LoginFacebookSubmitted()), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.facebook.svg(), const SizedBox(width: AppSpacing.lg), Assets.images.continueWithFacebook.svg(), ], ), ); } } class _TwitterLoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton.crystalBlue( key: const Key('loginForm_twitterLogin_appButton'), onPressed: () => context.read<LoginBloc>().add(LoginTwitterSubmitted()), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.twitter.svg(), const SizedBox(width: AppSpacing.lg), Assets.images.continueWithTwitter.svg(), ], ), ); } } class _ContinueWithEmailLoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton.outlinedTransparentDarkAqua( key: const Key('loginForm_emailLogin_appButton'), onPressed: () => Navigator.of(context).push<void>( LoginWithEmailPage.route(), ), textStyle: Theme.of(context).textTheme.titleMedium, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Assets.icons.emailOutline.svg(), const SizedBox(width: AppSpacing.lg), Text(context.l10n.loginWithEmailButtonText), ], ), ); } }
news_toolkit/flutter_news_example/lib/login/widgets/login_form.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/widgets/login_form.dart", "repo_id": "news_toolkit", "token_count": 2967 }
877
import 'package:app_ui/app_ui.dart' show AppColors, AppSpacing; 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/home/home.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:intl/intl.dart' show toBeginningOfSentenceCase; class NavDrawerSections extends StatelessWidget { const NavDrawerSections({super.key}); @override Widget build(BuildContext context) { final categories = context.select((CategoriesBloc bloc) => bloc.state.categories) ?? []; final selectedCategory = context.select((CategoriesBloc bloc) => bloc.state.selectedCategory); return Column( children: [ const NavDrawerSectionsTitle(), ...[ for (final category in categories) NavDrawerSectionItem( key: ValueKey(category), title: toBeginningOfSentenceCase(category.name) ?? '', selected: category == selectedCategory, onTap: () { Scaffold.of(context).closeDrawer(); context.read<HomeCubit>().setTab(0); context .read<CategoriesBloc>() .add(CategorySelected(category: category)); }, ) ], ], ); } } @visibleForTesting class NavDrawerSectionsTitle extends StatelessWidget { const NavDrawerSectionsTitle({super.key}); @override Widget build(BuildContext context) { return Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg, vertical: AppSpacing.lg + AppSpacing.xxs, ), child: Text( context.l10n.navigationDrawerSectionsTitle, style: Theme.of(context).textTheme.titleMedium?.copyWith( color: AppColors.primaryContainer, ), ), ), ); } } @visibleForTesting class NavDrawerSectionItem extends StatelessWidget { const NavDrawerSectionItem({ required this.title, this.onTap, this.leading, this.selected = false, super.key, }); static const _borderRadius = 100.0; final String title; final Widget? leading; final bool selected; final VoidCallback? onTap; @override Widget build(BuildContext context) { return ListTile( dense: true, leading: leading, visualDensity: const VisualDensity( vertical: VisualDensity.minimumDensity, ), contentPadding: EdgeInsets.symmetric( horizontal: selected ? AppSpacing.xlg : AppSpacing.lg, vertical: AppSpacing.lg + AppSpacing.xxs, ), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(_borderRadius), ), ), horizontalTitleGap: AppSpacing.md, minLeadingWidth: AppSpacing.xlg, selectedTileColor: AppColors.white.withOpacity(0.08), selected: selected, onTap: onTap, title: Text( title, style: Theme.of(context).textTheme.labelLarge?.copyWith( color: selected ? AppColors.highEmphasisPrimary : AppColors.mediumEmphasisPrimary, ), ), ); } }
news_toolkit/flutter_news_example/lib/navigation/widgets/nav_drawer_sections.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/navigation/widgets/nav_drawer_sections.dart", "repo_id": "news_toolkit", "token_count": 1476 }
878
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class NotificationCategoryTile extends StatelessWidget { const NotificationCategoryTile({ required this.title, required this.trailing, this.onTap, super.key, }); final String title; final Widget? trailing; final VoidCallback? onTap; @override Widget build(BuildContext context) { return ListTile( dense: true, trailing: trailing, visualDensity: const VisualDensity( vertical: VisualDensity.minimumDensity, ), contentPadding: const EdgeInsets.symmetric( vertical: AppSpacing.lg, ), horizontalTitleGap: 0, onTap: onTap, title: Text( toBeginningOfSentenceCase(title) ?? '', style: Theme.of(context).textTheme.titleMedium, ), ); } }
news_toolkit/flutter_news_example/lib/notification_preferences/widgets/notification_category_tile.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/widgets/notification_category_tile.dart", "repo_id": "news_toolkit", "token_count": 344 }
879
export 'search_page.dart';
news_toolkit/flutter_news_example/lib/search/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/view/view.dart", "repo_id": "news_toolkit", "token_count": 10 }
880
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; class ManageSubscriptionPage extends StatelessWidget { const ManageSubscriptionPage({super.key}); static MaterialPageRoute<void> route() { return MaterialPageRoute( builder: (_) => const ManageSubscriptionPage(), ); } @override Widget build(BuildContext context) { return const ManageSubscriptionView(); } } @visibleForTesting class ManageSubscriptionView extends StatelessWidget { const ManageSubscriptionView({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return Scaffold( appBar: AppBar( leading: const AppBackButton(), ), body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: AppSpacing.lg), Text( l10n.manageSubscriptionTile, style: theme.textTheme.headlineMedium, ), const SizedBox(height: AppSpacing.lg), Text( l10n.manageSubscriptionBodyText, style: theme.textTheme.bodyLarge?.copyWith( color: AppColors.mediumEmphasisSurface, ), ), ListTile( key: const Key('manageSubscription_subscriptions'), dense: true, horizontalTitleGap: 0, leading: const Icon( Icons.open_in_new, color: AppColors.darkAqua, ), title: Text( l10n.manageSubscriptionLinkText, style: theme.textTheme.titleSmall ?.copyWith(color: AppColors.darkAqua), ), onTap: () { // No possibility to revoke subscriptions from the app. // Navigate the user to "Manage Subscriptions" page instead. Navigator.maybePop(context); }, ), ], ), ), ), ); } }
news_toolkit/flutter_news_example/lib/subscriptions/view/manage_subscription_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/view/manage_subscription_page.dart", "repo_id": "news_toolkit", "token_count": 1165 }
881
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/theme_selector/theme_selector.dart'; /// A drop down menu to select a new [ThemeMode] /// /// Requires a [ThemeModeBloc] to be provided in the widget tree /// (usually above [MaterialApp]) class ThemeSelector extends StatelessWidget { const ThemeSelector({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final themeMode = context.watch<ThemeModeBloc>().state; return DropdownButton( key: const Key('themeSelector_dropdown'), onChanged: (ThemeMode? selectedThemeMode) => context .read<ThemeModeBloc>() .add(ThemeModeChanged(selectedThemeMode)), value: themeMode, items: [ DropdownMenuItem( value: ThemeMode.system, child: Text( l10n.systemOption, key: const Key('themeSelector_system_dropdownMenuItem'), ), ), DropdownMenuItem( value: ThemeMode.light, child: Text( l10n.lightModeOption, key: const Key('themeSelector_light_dropdownMenuItem'), ), ), DropdownMenuItem( value: ThemeMode.dark, child: Text( l10n.darkModeOption, key: const Key('themeSelector_dark_dropdownMenuItem'), ), ), ], ); } }
news_toolkit/flutter_news_example/lib/theme_selector/view/theme_selector.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/theme_selector/view/theme_selector.dart", "repo_id": "news_toolkit", "token_count": 654 }
882
// ignore_for_file: prefer_const_constructors, avoid_dynamic_calls import 'package:ads_consent_client/ads_consent_client.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:mocktail/mocktail.dart'; class MockConsentInformation extends Mock implements ConsentInformation {} class MockConsentForm extends Mock implements ConsentForm {} void main() { group('AdsConsentClient', () { late ConsentInformation adsConsentInformation; late ConsentFormProvider adsConsentFormProvider; late ConsentForm adsConsentForm; setUp(() { adsConsentInformation = MockConsentInformation(); adsConsentFormProvider = (successListener, failureListener) async {}; adsConsentForm = MockConsentForm(); }); test('can be instantiated', () async { expect(AdsConsentClient.new, returnsNormally); }); group('requestConsent', () { group( 'when ConsentInformation.requestConsentInfoUpdate succeeds ' 'and ConsentInformation.isConsentFormAvailable returns true', () { setUp(() { when( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).thenAnswer( (invocation) { final successListener = invocation.positionalArguments[1]; successListener(); }, ); when(adsConsentInformation.isConsentFormAvailable) .thenAnswer((_) async => true); }); group( 'and ConsentInformation.getConsentStatus returns required ' 'and ConsentForm.show succeeds', () { setUp(() { adsConsentFormProvider = (successListener, failureListener) async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.required); successListener(adsConsentForm); }; }); test('returns true if consent status was obtained', () async { const updatedConsentStatus = ConsentStatus.obtained; when(() => adsConsentForm.show(any())).thenAnswer((invocation) { // Update consent status to obtained // when the consent form is dismissed. when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => updatedConsentStatus); final dismissedListener = invocation.positionalArguments.first; dismissedListener(null); }); final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(2); verify(() => adsConsentForm.show(any())).called(1); expect(adsConsentDetermined, isTrue); }); test('returns false if consent status was not obtained', () async { const updatedConsentStatus = ConsentStatus.unknown; when(() => adsConsentForm.show(any())).thenAnswer((invocation) { // Update consent status to unknown // when the consent form is dismissed. when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => updatedConsentStatus); final dismissedListener = invocation.positionalArguments.first; dismissedListener(null); }); final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(2); verify(() => adsConsentForm.show(any())).called(1); expect(adsConsentDetermined, isFalse); }); }); group( 'and ConsentInformation.getConsentStatus returns required ' 'and ConsentForm.show fails', () { setUp(() { adsConsentFormProvider = (successListener, failureListener) async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.required); successListener(adsConsentForm); }; when(() => adsConsentForm.show(any())).thenAnswer((invocation) { final dismissedListener = invocation.positionalArguments.first; dismissedListener(FormError(errorCode: 1, message: 'message')); }); }); test('throws a RequestConsentFailure', () async { expect( AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent, throwsA(isA<RequestConsentFailure>()), ); }); }); group( 'and ConsentInformation.getConsentStatus returns required ' 'and ConsentFormProvider fails', () { setUp(() { adsConsentFormProvider = (successListener, failureListener) async { failureListener(FormError(errorCode: 1, message: 'message')); }; }); test('throws a RequestConsentFailure', () async { expect( AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent, throwsA(isA<RequestConsentFailure>()), ); }); }); test( 'returns true ' 'when ConsentInformation.getConsentStatus returns notRequired', () async { adsConsentFormProvider = (successListener, failureListener) async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.notRequired); successListener(adsConsentForm); }; final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isTrue); }); test( 'returns true ' 'when ConsentInformation.getConsentStatus returns obtained', () async { adsConsentFormProvider = (successListener, failureListener) async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.obtained); successListener(adsConsentForm); }; final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isTrue); }); test( 'returns false ' 'when ConsentInformation.getConsentStatus returns unknown', () async { adsConsentFormProvider = (successListener, failureListener) async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.unknown); successListener(adsConsentForm); }; final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isFalse); }); }); group( 'when ConsentInformation.requestConsentInfoUpdate succeeds ' 'and ConsentInformation.isConsentFormAvailable returns false', () { setUp(() { when( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).thenAnswer( (invocation) { final successListener = invocation.positionalArguments[1]; successListener(); }, ); when(adsConsentInformation.isConsentFormAvailable) .thenAnswer((_) async => false); }); test( 'returns true ' 'when ConsentInformation.getConsentStatus returns notRequired', () async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.notRequired); final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isTrue); }); test( 'returns true ' 'when ConsentInformation.getConsentStatus returns obtained', () async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.obtained); final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isTrue); }); test( 'returns false ' 'when ConsentInformation.getConsentStatus returns unknown', () async { when(adsConsentInformation.getConsentStatus) .thenAnswer((_) async => ConsentStatus.unknown); final adsConsentDetermined = await AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent(); verify( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).called(1); verify(adsConsentInformation.isConsentFormAvailable).called(1); verify(adsConsentInformation.getConsentStatus).called(1); expect(adsConsentDetermined, isFalse); }); }); group('when ConsentInformation.requestConsentInfoUpdate fails', () { setUp(() { when( () => adsConsentInformation.requestConsentInfoUpdate( ConsentRequestParameters(), any(), any(), ), ).thenAnswer( (invocation) { final failureListener = invocation.positionalArguments.last; failureListener(FormError(errorCode: 1, message: 'message')); }, ); }); test('throws a RequestConsentFailure', () async { expect( AdsConsentClient( adsConsentInformation: adsConsentInformation, adsConsentFormProvider: adsConsentFormProvider, ).requestConsent, throwsA(isA<RequestConsentFailure>()), ); }); }); }); }); }
news_toolkit/flutter_news_example/packages/ads_consent_client/test/src/ads_consent_client_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/ads_consent_client/test/src/ads_consent_client_test.dart", "repo_id": "news_toolkit", "token_count": 6169 }
883
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class TypographyPage extends StatelessWidget { const TypographyPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const TypographyPage()); } @override Widget build(BuildContext context) { final uiTextStyleList = [ _TextItem(name: 'Display 2', style: UITextStyle.display2), _TextItem(name: 'Display 3', style: UITextStyle.display3), _TextItem(name: 'Headline 1', style: UITextStyle.headline1), _TextItem(name: 'Headline 2', style: UITextStyle.headline2), _TextItem(name: 'Headline 3', style: UITextStyle.headline3), _TextItem(name: 'Headline 4', style: UITextStyle.headline4), _TextItem(name: 'Headline 5', style: UITextStyle.headline5), _TextItem(name: 'Headline 6', style: UITextStyle.headline6), _TextItem(name: 'Subtitle 1', style: UITextStyle.subtitle1), _TextItem(name: 'Subtitle 2', style: UITextStyle.subtitle2), _TextItem(name: 'Body Text 1', style: UITextStyle.bodyText1), _TextItem(name: 'Body Text 2', style: UITextStyle.bodyText2), _TextItem(name: 'Caption', style: UITextStyle.caption), _TextItem(name: 'Button', style: UITextStyle.button), _TextItem(name: 'Overline', style: UITextStyle.overline), _TextItem(name: 'Label Small', style: UITextStyle.labelSmall), ]; final contentTextStyleList = [ _TextItem(name: 'Display 1', style: ContentTextStyle.display1), _TextItem(name: 'Display 2', style: ContentTextStyle.display2), _TextItem(name: 'Display 3', style: ContentTextStyle.display3), _TextItem(name: 'Headline 1', style: ContentTextStyle.headline1), _TextItem(name: 'Headline 2', style: ContentTextStyle.headline2), _TextItem(name: 'Headline 3', style: ContentTextStyle.headline3), _TextItem(name: 'Headline 4', style: ContentTextStyle.headline4), _TextItem(name: 'Headline 5', style: ContentTextStyle.headline5), _TextItem(name: 'Headline 6', style: ContentTextStyle.headline6), _TextItem(name: 'Subtitle 1', style: ContentTextStyle.subtitle1), _TextItem(name: 'Subtitle 2', style: ContentTextStyle.subtitle2), _TextItem(name: 'Body Text 1', style: ContentTextStyle.bodyText1), _TextItem(name: 'Body Text 2', style: ContentTextStyle.bodyText2), _TextItem(name: 'Caption', style: ContentTextStyle.caption), _TextItem(name: 'Button', style: ContentTextStyle.button), _TextItem(name: 'Overline', style: ContentTextStyle.overline), _TextItem(name: 'Label Small', style: ContentTextStyle.labelSmall), ]; return Scaffold( appBar: AppBar(title: const Text('Typography')), body: ListView( children: [ const Center(child: Text('UI Typography')), const SizedBox(height: 16), ...uiTextStyleList, const SizedBox(height: 32), const Center(child: Text('Content Typography')), const SizedBox(height: 16), ...contentTextStyleList, ], ), ); } } class _TextItem extends StatelessWidget { const _TextItem({required this.name, required this.style}); final String name; final TextStyle style; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.sm, vertical: AppSpacing.lg, ), child: Text(name, style: style), ); } }
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/typography/typography_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/typography/typography_page.dart", "repo_id": "news_toolkit", "token_count": 1370 }
884
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template app_email_text_field} /// An email text field component. /// {@endtemplate} class AppEmailTextField extends StatelessWidget { /// {@macro app_email_text_field} const AppEmailTextField({ super.key, this.controller, this.hintText, this.suffix, this.readOnly, this.onChanged, }); /// Controls the text being edited. final TextEditingController? controller; /// Text that suggests what sort of input the field accepts. final String? hintText; /// A widget that appears after the editable part of the text field. final Widget? suffix; /// Called when the user inserts or deletes texts in the text field. final ValueChanged<String>? onChanged; /// Whether the text field should be read-only. /// Defaults to false. final bool? readOnly; @override Widget build(BuildContext context) { return AppTextField( controller: controller, hintText: hintText, keyboardType: TextInputType.emailAddress, autoFillHints: const [AutofillHints.email], autocorrect: false, prefix: const Padding( padding: EdgeInsets.only( left: AppSpacing.sm, right: AppSpacing.sm, ), child: Icon( Icons.email_outlined, color: AppColors.mediumEmphasisSurface, size: 24, ), ), readOnly: readOnly ?? false, onChanged: onChanged, suffix: suffix, ); } }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_email_text_field.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_email_text_field.dart", "repo_id": "news_toolkit", "token_count": 569 }
885
// 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('AppSwitch', () { testWidgets( 'renders onText ' 'when enabled', (tester) async { await tester.pumpApp( AppSwitch( value: true, onText: 'On', onChanged: (_) {}, ), ); expect(find.text('On'), findsOneWidget); }); testWidgets( 'renders offText ' 'when disabled', (tester) async { await tester.pumpApp( AppSwitch( value: false, offText: 'Off', onChanged: (_) {}, ), ); expect(find.text('Off'), findsOneWidget); }); testWidgets('renders Switch', (tester) async { await tester.pumpApp( AppSwitch( value: true, onChanged: (_) {}, ), ); expect( find.byWidgetPredicate( (widget) => widget is Switch && widget.value == true, ), findsOneWidget, ); }); testWidgets('calls onChanged when tapped', (tester) async { var tapped = false; await tester.pumpApp( AppSwitch( value: true, onChanged: (_) => tapped = true, ), ); await tester.tap(find.byType(Switch)); await tester.pumpAndSettle(); expect(tapped, isTrue); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_switch_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_switch_test.dart", "repo_id": "news_toolkit", "token_count": 733 }
886
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
887
# token_storage [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Token storage for the authentication client. [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/authentication_client/token_storage/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/token_storage/README.md", "repo_id": "news_toolkit", "token_count": 166 }
888
name: email_launcher description: A package to open an external email app on Android and iOS version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: android_intent_plus: ^4.0.1 flutter: sdk: flutter platform: ^3.0.2 plugin_platform_interface: ^2.1.3 url_launcher: ^6.1.5 url_launcher_platform_interface: ^2.1.1 dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/email_launcher/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/email_launcher/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 198 }
889
name: in_app_purchase_repository description: A repository that manages user purchase. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: authentication_client: path: ../authentication_client/authentication_client equatable: ^2.0.3 flutter: sdk: flutter flutter_news_example_api: path: ../../api in_app_purchase: ^3.0.6 dev_dependencies: coverage: ^1.3.2 flutter_test: sdk: flutter mocktail: ^1.0.2 test: ^1.21.4 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/in_app_purchase_repository/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/in_app_purchase_repository/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 221 }
890
export 'assets.gen.dart';
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/generated/generated.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/generated/generated.dart", "repo_id": "news_toolkit", "token_count": 10 }
891
import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; /// {@template section_header} /// A reusable section header news block widget. /// {@endtemplate} class SectionHeader extends StatelessWidget { /// {@macro section_header} const SectionHeader({required this.block, this.onPressed, super.key}); /// The associated [SectionHeaderBlock] instance. final SectionHeaderBlock block; /// An optional callback which is invoked when the action is triggered. /// A [Uri] from the associated [BlockAction] is provided to the callback. final BlockActionCallback? onPressed; @override Widget build(BuildContext context) { final theme = Theme.of(context); final title = Text(block.title, style: theme.textTheme.displaySmall); final action = block.action; final trailing = action != null ? IconButton( icon: const Icon(Icons.chevron_right), onPressed: () => onPressed?.call(action), ) : null; return ListTile( title: title, trailing: trailing, visualDensity: const VisualDensity( vertical: VisualDensity.minimumDensity, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/section_header.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/section_header.dart", "repo_id": "news_toolkit", "token_count": 421 }
892
import 'package:flutter/material.dart'; import 'package:news_blocks_ui/src/generated/generated.dart'; import 'package:video_player/video_player.dart'; /// Signature for [VideoPlayerController] builder. typedef VideoPlayerControllerBuilder = VideoPlayerController Function( Uri videoUrl, ); /// {@template inline_video} /// A reusable video widget displayed inline with the content. /// {@endtemplate} class InlineVideo extends StatefulWidget { /// {@macro inline_video} const InlineVideo({ required this.videoUrl, required this.progressIndicator, this.videoPlayerControllerBuilder = VideoPlayerController.networkUrl, super.key, }); /// The aspect ratio of this video. static const _aspectRatio = 3 / 2; /// The url of this video. final String videoUrl; /// Widget displayed while the target [videoUrl] is loading. final Widget progressIndicator; /// The builder of [VideoPlayerController] used in this video. final VideoPlayerControllerBuilder videoPlayerControllerBuilder; @override State<InlineVideo> createState() => _InlineVideoState(); } class _InlineVideoState extends State<InlineVideo> { late VideoPlayerController _controller; bool _isPlaying = false; @override void initState() { super.initState(); _controller = widget.videoPlayerControllerBuilder( Uri.parse(widget.videoUrl), ) ..addListener(_onVideoUpdated) ..initialize().then((_) { // Ensure the first frame of the video is shown // after the video is initialized. if (mounted) setState(() {}); }); } @override void dispose() { super.dispose(); _controller ..removeListener(_onVideoUpdated) ..dispose(); } void _onVideoUpdated() { if (!mounted || _isPlaying == _controller.value.isPlaying) { return; } setState(() { _isPlaying = _controller.value.isPlaying; }); } @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: InlineVideo._aspectRatio, child: _controller.value.isInitialized ? GestureDetector( key: const Key('inlineVideo_gestureDetector'), onTap: _isPlaying ? _controller.pause : _controller.play, child: ClipRRect( child: Stack( children: [ SizedBox.expand( child: FittedBox( fit: BoxFit.cover, child: SizedBox( width: _controller.value.size.width, height: _controller.value.size.height, child: VideoPlayer(_controller), ), ), ), Center( child: Visibility( visible: !_isPlaying, child: Assets.icons.playIcon.svg(), ), ), ], ), ), ) : widget.progressIndicator, ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/inline_video.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/inline_video.dart", "repo_id": "news_toolkit", "token_count": 1356 }
893
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; extension AppContentThemedTester on WidgetTester { Future<void> pumpContentThemedApp(Widget widgetUnderTest) async { await pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ContentThemeOverrideBuilder( builder: (context) => widgetUnderTest, ), ), ), ), ); await pump(); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/pump_content_themed_app.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/pump_content_themed_app.dart", "repo_id": "news_toolkit", "token_count": 227 }
894
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('PostContentPremiumCategory', () { testWidgets('renders premium text in uppercase', (tester) async { final testPostContentPremiumCategory = PostContentPremiumCategory( premiumText: 'premiumText', isVideoContent: false, ); await tester.pumpContentThemedApp(testPostContentPremiumCategory); expect( find.text(testPostContentPremiumCategory.premiumText.toUpperCase()), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_premium_category_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_premium_category_test.dart", "repo_id": "news_toolkit", "token_count": 258 }
895
name: news_repository description: A repository that exposes news data. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: equatable: ^2.0.3 flutter_news_example_api: path: ../../api dev_dependencies: coverage: ^1.2.0 mocktail: ^1.0.2 test: ^1.21.4 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/news_repository/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_repository/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 148 }
896
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/purchase_client/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/purchase_client/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
897
import 'package:shared_preferences/shared_preferences.dart'; import 'package:storage/storage.dart'; /// {@template persistent_storage} /// Storage that saves data in the device's persistent memory. /// {@endtemplate} class PersistentStorage implements Storage { /// {@macro persistent_storage} const PersistentStorage({ required SharedPreferences sharedPreferences, }) : _sharedPreferences = sharedPreferences; final SharedPreferences _sharedPreferences; /// Returns value for the provided [key] from storage. /// Returns `null` if no value is found for the given [key]. /// /// Throws a [StorageException] if the read fails. @override Future<String?> read({required String key}) async { try { return _sharedPreferences.getString(key); } catch (error, stackTrace) { Error.throwWithStackTrace(StorageException(error), stackTrace); } } /// Writes the provided [key], [value] pair into storage. /// /// Throws a [StorageException] if the write fails. @override Future<void> write({required String key, required String value}) async { try { await _sharedPreferences.setString(key, value); } catch (error, stackTrace) { Error.throwWithStackTrace(StorageException(error), stackTrace); } } /// Removes the value for the provided [key] from storage. /// /// Throws a [StorageException] if the delete fails. @override Future<void> delete({required String key}) async { try { await _sharedPreferences.remove(key); } catch (error, stackTrace) { Error.throwWithStackTrace(StorageException(error), stackTrace); } } /// Removes all key, value pairs from storage. /// /// Throws a [StorageException] if the clear fails. @override Future<void> clear() async { try { await _sharedPreferences.clear(); } catch (error, stackTrace) { Error.throwWithStackTrace(StorageException(error), stackTrace); } } }
news_toolkit/flutter_news_example/packages/storage/persistent_storage/lib/src/persistent_storage.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/lib/src/persistent_storage.dart", "repo_id": "news_toolkit", "token_count": 623 }
898
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/user_repository/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/user_repository/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
899
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/ads/ads.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('StickyAd', () { testWidgets( 'renders StickyAdContainer ' 'with anchoredAdaptive BannerAdContent', (tester) async { await tester.pumpApp(StickyAd()); expect( find.descendant( of: find.byType(StickyAdContainer), matching: find.byWidgetPredicate( (widget) => widget is BannerAdContent && widget.size == BannerAdSize.anchoredAdaptive && widget.showProgressIndicator == false, ), ), findsOneWidget, ); }); testWidgets( 'renders StickyAdCloseIconBackground and StickyAdCloseIcon ' 'when ad is loaded', (tester) async { await tester.pumpApp(StickyAd()); expect(find.byType(StickyAdCloseIconBackground), findsNothing); expect(find.byType(StickyAdCloseIcon), findsNothing); final bannerAdContent = tester.widget<BannerAdContent>(find.byType(BannerAdContent)); bannerAdContent.onAdLoaded?.call(); await tester.pump(); expect(find.byType(StickyAdCloseIconBackground), findsOneWidget); expect(find.byType(StickyAdCloseIcon), findsOneWidget); }); testWidgets('hides ad when closed icon is tapped', (tester) async { await tester.pumpApp(StickyAd()); final bannerAdContent = tester.widget<BannerAdContent>(find.byType(BannerAdContent)); bannerAdContent.onAdLoaded?.call(); await tester.pump(); await tester.ensureVisible(find.byType(StickyAdCloseIcon)); await tester.tap(find.byType(StickyAdCloseIcon)); await tester.pump(); expect(find.byType(BannerAdContent), findsNothing); expect(find.byType(StickyAdCloseIconBackground), findsNothing); expect(find.byType(StickyAdCloseIcon), findsNothing); }); }); }
news_toolkit/flutter_news_example/test/ads/widgets/sticky_ad_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/ads/widgets/sticky_ad_test.dart", "repo_id": "news_toolkit", "token_count": 875 }
900
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart' hide Image, Spacer; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_news_example/newsletter/newsletter.dart'; import 'package:flutter_news_example/slideshow/slideshow.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 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'package:visibility_detector/visibility_detector.dart'; import '../../helpers/helpers.dart'; import '../helpers/helpers.dart'; void main() { initMockHydratedStorage(); void setUpVideoPlayerPlatform() { final fakeVideoPlayerPlatform = FakeVideoPlayerPlatform(); VideoPlayerPlatform.instance = fakeVideoPlayerPlatform; } group('ArticleContentItem', () { testWidgets( 'renders DividerHorizontal ' 'for DividerHorizontalBlock', (tester) async { const block = DividerHorizontalBlock(); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is DividerHorizontal && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders Spacer ' 'for SpacerBlock', (tester) async { const block = SpacerBlock(spacing: Spacing.large); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is Spacer && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders Image ' 'for ImageBlock', (tester) async { const block = ImageBlock(imageUrl: 'imageUrl'); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is Image && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders TextCaption ' 'with colorValues from ArticleThemeColors ' 'for TextCaptionBlock', (tester) async { const block = TextCaptionBlock( text: 'text', color: TextCaptionColor.normal, ); late ArticleThemeColors colors; await tester.pumpApp( ArticleThemeOverride( isVideoArticle: false, child: Builder( builder: (context) { colors = Theme.of(context).extension<ArticleThemeColors>()!; return ArticleContentItem(block: block); }, ), ), ); expect( find.byWidgetPredicate( (widget) => widget is TextCaption && widget.block == block && widget.colorValues[TextCaptionColor.normal] == colors.captionNormal && widget.colorValues[TextCaptionColor.light] == colors.captionLight, ), findsOneWidget, ); }); testWidgets( 'renders TextHeadline ' 'for TextHeadlineBlock', (tester) async { const block = TextHeadlineBlock(text: 'text'); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is TextHeadline && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders TextLeadParagraph ' 'for TextLeadParagraphBlock', (tester) async { const block = TextLeadParagraphBlock(text: 'text'); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is TextLeadParagraph && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders TextParagraph ' 'for TextParagraphBlock', (tester) async { const block = TextParagraphBlock(text: 'text'); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is TextParagraph && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders Video ' 'for VideoBlock', (tester) async { setUpVideoPlayerPlatform(); const block = VideoBlock(videoUrl: 'videoUrl'); await tester.pumpApp(ArticleContentItem(block: block)); expect( find.byWidgetPredicate( (widget) => widget is Video && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders ArticleIntroduction ' 'for ArticleIntroductionBlock', (tester) async { final block = ArticleIntroductionBlock( category: PostCategory.technology, author: 'author', publishedAt: DateTime(2022, 3, 9), imageUrl: 'imageUrl', title: 'title', ); await tester.pumpApp( ListView( children: [ ArticleContentItem(block: block), ], ), ); expect( find.byWidgetPredicate( (widget) => widget is ArticleIntroduction && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders VideoIntroduction ' 'for VideoIntroductionBlock', (tester) async { setUpVideoPlayerPlatform(); final block = VideoIntroductionBlock( category: PostCategory.technology, title: 'title', videoUrl: 'videoUrl', ); await tester.pumpApp( ListView( children: [ ArticleContentItem(block: block), ], ), ); expect( find.byWidgetPredicate( (widget) => widget is VideoIntroduction && widget.block == block, ), findsOneWidget, ); }); testWidgets( 'renders BannerAd ' 'for BannerAdBlock', (tester) async { final block = BannerAdBlock(size: BannerAdSize.normal); await tester.pumpApp(ArticleContentItem(block: block)); expect(find.byType(BannerAd), findsOneWidget); }); testWidgets( 'renders Newsletter ' 'for NewsletterBlock', (tester) async { VisibilityDetectorController.instance.updateInterval = Duration.zero; final block = NewsletterBlock(); await tester.pumpApp(ArticleContentItem(block: block)); expect(find.byType(Newsletter), findsOneWidget); }); testWidgets( 'renders Html ' 'for HtmlBlock', (tester) async { final block = HtmlBlock(content: '<p>Lorem</p>'); await tester.pumpApp(ArticleContentItem(block: block)); expect(find.byType(Html), findsOneWidget); }); testWidgets( 'renders SlideshowIntroduction ' 'for SlideshowIntroductionBlock', (tester) async { final block = SlideshowIntroductionBlock( title: 'title', coverImageUrl: 'coverImageUrl', action: NavigateToSlideshowAction( slideshow: SlideshowBlock( slides: [], title: 'title', ), articleId: 'articleId', ), ); await tester.pumpApp( ListView( children: [ ArticleContentItem(block: block), ], ), ); await tester.ensureVisible(find.byType(SlideshowIntroduction)); await tester.tap(find.byType(SlideshowIntroduction)); await tester.pumpAndSettle(); expect( find.byType(SlideshowPage), findsOneWidget, ); }); }); testWidgets( 'renders SizedBox ' 'for unsupported block', (tester) async { final block = UnknownBlock(); await tester.pumpApp(ArticleContentItem(block: block)); expect(find.byType(SizedBox), findsOneWidget); }); testWidgets( 'renders TrendingStory ' 'for TrendingStoryBlock', (tester) async { final content = PostSmallBlock( id: 'id', category: PostCategory.health, author: 'author', publishedAt: DateTime(2022, 3, 11), imageUrl: 'imageUrl', title: 'title', ); final block = TrendingStoryBlock(content: content); await tester.pumpApp(ArticleContentItem(block: block)); expect(find.byType(TrendingStory), findsOneWidget); }); }
news_toolkit/flutter_news_example/test/article/widgets/article_content_item_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_content_item_test.dart", "repo_id": "news_toolkit", "token_count": 3575 }
901
// ignore_for_file: prefer_const_constructors // ignore_for_file: prefer_const_literals_to_create_immutables import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_news_example/network_error/network_error.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks/news_blocks.dart'; import '../../helpers/helpers.dart'; class MockFeedBloc extends MockBloc<FeedEvent, FeedState> implements FeedBloc {} class MockNavigatorObserver extends Mock implements NavigatorObserver {} const networkErrorButtonText = 'Try Again'; void main() { late FeedBloc feedBloc; const category = Category.top; final feed = <Category, List<NewsBlock>>{ Category.top: [ DividerHorizontalBlock(), SpacerBlock(spacing: Spacing.medium), ] }; setUp(() { feedBloc = MockFeedBloc(); when(() => feedBloc.state).thenReturn( FeedState(feed: feed, status: FeedStatus.populated), ); registerFallbackValue(FeedRefreshRequested(category: Category.business)); }); group('CategoryFeed', () { group('when FeedStatus is failure and feed is populated', () { setUpAll(() { registerFallbackValue(Category.top); }); setUp(() { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState(feed: feed, status: FeedStatus.failure), ]), ); }); testWidgets('shows NetworkErrorAlert', (tester) async { await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect( find.byType(NetworkError), findsOneWidget, ); }); testWidgets('requests feed refresh on NetworkErrorAlert press', (tester) async { await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); await tester.ensureVisible(find.text(networkErrorButtonText)); await tester.tap(find.textContaining(networkErrorButtonText)); verify(() => feedBloc.add(any(that: isA<FeedRefreshRequested>()))) .called(1); }); testWidgets('renders a SelectionArea', (tester) async { await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect(find.byType(SelectionArea), findsOneWidget); }); testWidgets('shows CategoryFeedItem for each feed block', (tester) async { final categoryFeed = feed[category]!; await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect( find.byType(CategoryFeedItem), findsNWidgets(categoryFeed.length), ); for (final block in categoryFeed) { expect( find.byWidgetPredicate( (widget) => widget is CategoryFeedItem && widget.block == block, ), findsOneWidget, ); } }); }); group('when FeedStatus is failure and feed is unpopulated', () { setUpAll(() { registerFallbackValue(Category.top); registerFallbackValue(NetworkError.route()); }); setUp(() { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState(feed: {}, status: FeedStatus.failure), ]), ); }); testWidgets('pushes NetworkErrorAlert on Scaffold', (tester) async { final navigatorObserver = MockNavigatorObserver(); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), navigatorObserver: navigatorObserver, ); verify(() => navigatorObserver.didPush(any(), any())); expect( find.ancestor( of: find.byType(NetworkError), matching: find.byType(Scaffold), ), findsOneWidget, ); }); testWidgets('requests feed refresh on NetworkErrorAlert press', (tester) async { final navigatorObserver = MockNavigatorObserver(); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), navigatorObserver: navigatorObserver, ); verify(() => navigatorObserver.didPush(any(), any())); await tester.ensureVisible(find.text(networkErrorButtonText)); await tester.pump(Duration(seconds: 1)); await tester.tap(find.textContaining(networkErrorButtonText)); verify(() => feedBloc.add(any(that: isA<FeedRefreshRequested>()))) .called(1); verify(() => navigatorObserver.didPop(any(), any())); }); }); group('when FeedStatus is populated', () { setUp(() { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState(status: FeedStatus.populated, feed: feed), ]), ); }); testWidgets('shows CategoryFeedItem for each feed block', (tester) async { final categoryFeed = feed[category]!; await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect( find.byType(CategoryFeedItem), findsNWidgets(categoryFeed.length), ); for (final block in categoryFeed) { expect( find.byWidgetPredicate( (widget) => widget is CategoryFeedItem && widget.block == block, ), findsOneWidget, ); } }); testWidgets('refreshes on pull to refresh', (tester) async { await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); await tester.fling( find.byType(CategoryFeed), const Offset(0, 300), 1000, ); await tester.pump(); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); verify( () => feedBloc.add(any(that: isA<FeedRefreshRequested>())), ).called(1); }); }); group('CategoryFeedLoaderItem', () { final hasMoreNews = <Category, bool>{ Category.top: true, }; group('is shown', () { testWidgets('when FeedStatus is initial', (tester) async { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), ]), ); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect(find.byType(CategoryFeedLoaderItem), findsOneWidget); }); testWidgets('when FeedStatus is loading', (tester) async { whenListen( feedBloc, Stream.fromIterable([ FeedState(status: FeedStatus.loading), ]), ); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect(find.byType(CategoryFeedLoaderItem), findsOneWidget); }); testWidgets( 'when FeedStatus is populated and ' 'hasMoreNews is true', (tester) async { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState( status: FeedStatus.populated, feed: feed, hasMoreNews: hasMoreNews, ) ]), ); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect(find.byType(CategoryFeedLoaderItem), findsOneWidget); }); }); testWidgets( 'is not shown ' 'when FeedStatus is populated and ' 'hasMoreNews is false', (tester) async { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState( status: FeedStatus.populated, feed: feed, hasMoreNews: { category: false, }, ) ]), ); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); expect(find.byType(CategoryFeedLoaderItem), findsNothing); }); testWidgets('adds FeedRequested to FeedBloc', (tester) async { whenListen( feedBloc, Stream.fromIterable([ FeedState.initial(), FeedState( status: FeedStatus.populated, feed: feed, hasMoreNews: hasMoreNews, ) ]), ); await tester.pumpApp( BlocProvider.value( value: feedBloc, child: CategoryFeed(category: category), ), ); verify( () => feedBloc.add(FeedRequested(category: category)), ).called(1); }); }); }); }
news_toolkit/flutter_news_example/test/feed/widgets/category_feed_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/feed/widgets/category_feed_test.dart", "repo_id": "news_toolkit", "token_count": 4848 }
902
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import '../../helpers/helpers.dart'; void main() { const closeIcon = Key('loginWithEmailPage_closeIcon'); group('LoginWithEmailPage', () { test('has a route', () { expect(LoginWithEmailPage.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('renders LoginWithEmailForm', (tester) async { await tester.pumpApp(const LoginWithEmailPage()); expect(find.byType(LoginWithEmailForm), findsOneWidget); }); group('navigates', () { testWidgets('back when left cross icon is pressed', (tester) async { final navigator = MockNavigator(); when(navigator.pop).thenAnswer((_) async {}); await tester.pumpApp( const LoginWithEmailPage(), navigator: navigator, ); await tester.tap(find.byKey(closeIcon)); await tester.pumpAndSettle(); verify(navigator.pop).called(1); }); testWidgets('back when leading button is pressed', (tester) async { final navigator = MockNavigator(); when(navigator.pop).thenAnswer((_) async {}); await tester.pumpApp( const LoginWithEmailPage(), navigator: navigator, ); await tester.tap(find.byType(AppBackButton)); await tester.pumpAndSettle(); verify(navigator.pop).called(1); }); }); }); }
news_toolkit/flutter_news_example/test/login/view/login_with_email_page_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/login/view/login_with_email_page_test.dart", "repo_id": "news_toolkit", "token_count": 637 }
903
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.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'; class MockNotificationsRepository extends Mock implements NotificationsRepository {} class MockNewsRepository extends Mock implements NewsRepository {} void main() { final initialState = NotificationPreferencesState.initial(); final notificationsRepository = MockNotificationsRepository(); final newsRepository = MockNewsRepository(); group('NotificationPreferencesBloc', () { group('on CategoriesPreferenceToggled ', () { blocTest<NotificationPreferencesBloc, NotificationPreferencesState>( 'emits [loading, success, loading, success] ' 'with updated selectedCategories ' 'when toggled category twice ', setUp: () => when( () => notificationsRepository.setCategoriesPreferences(any()), ).thenAnswer((_) async {}), build: () => NotificationPreferencesBloc( newsRepository: newsRepository, notificationsRepository: notificationsRepository, ), seed: () => initialState, act: (bloc) => bloc ..add(CategoriesPreferenceToggled(category: Category.business)) ..add(CategoriesPreferenceToggled(category: Category.business)), expect: () => <NotificationPreferencesState>[ initialState.copyWith( status: NotificationPreferencesStatus.loading, ), initialState.copyWith( selectedCategories: {Category.business}, status: NotificationPreferencesStatus.success, ), initialState.copyWith( selectedCategories: {Category.business}, status: NotificationPreferencesStatus.loading, ), initialState.copyWith( selectedCategories: {}, status: NotificationPreferencesStatus.success, ), ], ); blocTest<NotificationPreferencesBloc, NotificationPreferencesState>( 'emits [loading, failed] ' 'when toggled category ' 'and setCategoriesPreferences throws', setUp: () => when( () => notificationsRepository.setCategoriesPreferences(any()), ).thenThrow(Exception()), build: () => NotificationPreferencesBloc( newsRepository: newsRepository, notificationsRepository: notificationsRepository, ), seed: () => initialState, act: (bloc) => bloc..add(CategoriesPreferenceToggled(category: Category.business)), expect: () => <NotificationPreferencesState>[ initialState.copyWith( status: NotificationPreferencesStatus.loading, ), initialState.copyWith( status: NotificationPreferencesStatus.failure, ), ], ); }); group('on InitialCategoriesPreferencesRequested ', () { blocTest<NotificationPreferencesBloc, NotificationPreferencesState>( 'emits [loading, success] ' 'with updated selectedCategories and categories ', setUp: () { when( notificationsRepository.fetchCategoriesPreferences, ).thenAnswer((_) async => {Category.business}); when(newsRepository.getCategories).thenAnswer( (_) async => CategoriesResponse( categories: const [ Category.business, Category.entertainment, ], ), ); }, build: () => NotificationPreferencesBloc( newsRepository: newsRepository, notificationsRepository: notificationsRepository, ), seed: () => initialState, act: (bloc) => bloc..add(InitialCategoriesPreferencesRequested()), expect: () => <NotificationPreferencesState>[ initialState.copyWith( status: NotificationPreferencesStatus.loading, ), NotificationPreferencesState( categories: const { Category.business, Category.entertainment, }, selectedCategories: const {Category.business}, status: NotificationPreferencesStatus.success, ), ], ); blocTest<NotificationPreferencesBloc, NotificationPreferencesState>( 'emits [loading, failed] ' 'when fetchCategoriesPreferences throws', setUp: () => when( notificationsRepository.fetchCategoriesPreferences, ).thenThrow(Exception()), build: () => NotificationPreferencesBloc( newsRepository: newsRepository, notificationsRepository: notificationsRepository, ), seed: () => initialState, act: (bloc) => bloc..add(InitialCategoriesPreferencesRequested()), expect: () => <NotificationPreferencesState>[ initialState.copyWith( status: NotificationPreferencesStatus.loading, ), initialState.copyWith( status: NotificationPreferencesStatus.failure, ), ], ); }); }); }
news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 2167 }
904
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/search/search.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('SearchTextField', () { testWidgets('changes controller.value when text input changes', (tester) async { final controller = TextEditingController(); await tester.pumpApp( SearchTextField( controller: controller, ), ); await tester.enterText(find.byType(AppTextField), 'text'); expect(controller.value.text, equals('text')); }); testWidgets('clears controller on IconButton pressed', (tester) async { final controller = TextEditingController(text: 'text'); await tester.pumpApp( SearchTextField( controller: controller, ), ); await tester.tap(find.byType(IconButton)); expect(controller.value.text, equals('')); }); }); }
news_toolkit/flutter_news_example/test/search/widgets/search_text_field_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/search/widgets/search_text_field_test.dart", "repo_id": "news_toolkit", "token_count": 394 }
905
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:authentication_client/authentication_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_news_example/user_profile/user_profile.dart'; import 'package:flutter_news_example_api/client.dart' hide User; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:notifications_repository/notifications_repository.dart'; import 'package:user_repository/user_repository.dart'; class MockUserRepository extends Mock implements UserRepository {} class MockNotificationsRepository extends Mock implements NotificationsRepository {} class MockAuthenticationClient extends Mock implements AuthenticationClient {} void main() { group('UserProfileBloc', () { late UserRepository userRepository; late NotificationsRepository notificationsRepository; const user1 = User(id: '1', subscriptionPlan: SubscriptionPlan.none); const user2 = User(id: '2', subscriptionPlan: SubscriptionPlan.none); late StreamController<User> userController; setUp(() { userRepository = MockUserRepository(); userController = StreamController<User>(); notificationsRepository = MockNotificationsRepository(); when(() => userRepository.user).thenAnswer((_) => userController.stream); }); test('initial state is UserProfileState.initial', () { expect( UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ).state, equals(UserProfileState.initial()), ); }); group('on user changes', () { blocTest<UserProfileBloc, UserProfileState>( 'emits populated user ' 'when user is added to user stream', build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (_) => userController ..add(user1) ..add(user2), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( user: user1, status: UserProfileStatus.userUpdated, ), UserProfileState.initial().copyWith( user: user2, status: UserProfileStatus.userUpdated, ), ], ); blocTest<UserProfileBloc, UserProfileState>( 'adds error ' 'when user stream throws an error', build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (_) => userController.addError(Exception()), expect: () => <UserProfileState>[], errors: () => [isA<Exception>()], ); blocTest<UserProfileBloc, UserProfileState>( 'emits populated user ' 'when user is added to user stream after it throws an error', build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (_) { userController ..addError(Exception()) ..add(user1); }, expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( user: user1, status: UserProfileStatus.userUpdated, ), ], ); }); group('on FetchNotificationsEnabled', () { blocTest<UserProfileBloc, UserProfileState>( 'emits ' '[fetchingNotificationsEnabled, fetchingNotificationsEnabledSucceeded] ' 'when fetchNotificationsEnabled succeeds', setUp: () => when(notificationsRepository.fetchNotificationsEnabled) .thenAnswer((_) async => true), build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (bloc) => bloc.add(FetchNotificationsEnabled()), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( status: UserProfileStatus.fetchingNotificationsEnabled, ), UserProfileState.initial().copyWith( status: UserProfileStatus.fetchingNotificationsEnabledSucceeded, notificationsEnabled: true, ), ], ); blocTest<UserProfileBloc, UserProfileState>( 'emits ' '[fetchingNotificationsEnabled, fetchingNotificationsEnabledFailed] ' 'when fetchNotificationsEnabled fails', setUp: () => when(notificationsRepository.fetchNotificationsEnabled) .thenThrow(Exception()), build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (bloc) => bloc.add(FetchNotificationsEnabled()), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( status: UserProfileStatus.fetchingNotificationsEnabled, ), UserProfileState.initial().copyWith( status: UserProfileStatus.fetchingNotificationsEnabledFailed, ), ], ); }); group('on ToggleNotifications', () { setUp(() { when( () => notificationsRepository.toggleNotifications( enable: any(named: 'enable'), ), ).thenAnswer((_) async {}); }); blocTest<UserProfileBloc, UserProfileState>( 'emits ' '[togglingNotifications, togglingNotificationsSucceeded] ' 'when notifications are enabled ' 'and toggleNotifications succeeds', seed: () => UserProfileState.initial().copyWith( notificationsEnabled: true, ), build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (bloc) => bloc.add(ToggleNotifications()), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotifications, notificationsEnabled: false, ), UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotificationsSucceeded, notificationsEnabled: false, ), ], verify: (bloc) => verify( () => notificationsRepository.toggleNotifications(enable: false), ).called(1), ); blocTest<UserProfileBloc, UserProfileState>( 'emits ' '[togglingNotifications, togglingNotificationsSucceeded] ' 'when notifications are disabled ' 'and toggleNotifications succeeds', seed: () => UserProfileState.initial().copyWith( notificationsEnabled: false, ), build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (bloc) => bloc.add(ToggleNotifications()), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotifications, notificationsEnabled: true, ), UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotificationsSucceeded, notificationsEnabled: true, ), ], verify: (bloc) => verify( () => notificationsRepository.toggleNotifications(enable: true), ).called(1), ); blocTest<UserProfileBloc, UserProfileState>( 'emits ' '[togglingNotifications, togglingNotificationsFailed] ' 'when toggleNotifications fails', setUp: () => when( () => notificationsRepository.toggleNotifications( enable: any(named: 'enable'), ), ).thenThrow(Exception()), build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), act: (bloc) => bloc.add(ToggleNotifications()), expect: () => <UserProfileState>[ UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotifications, notificationsEnabled: true, ), UserProfileState.initial().copyWith( status: UserProfileStatus.togglingNotificationsFailed, notificationsEnabled: false, ), ], ); }); blocTest<UserProfileBloc, UserProfileState>( 'closes subscriptions', build: () => UserProfileBloc( userRepository: userRepository, notificationsRepository: notificationsRepository, ), tearDown: () { expect(userController.hasListener, isFalse); }, ); }); }
news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 3640 }
906
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="facebook_app_id">{{flavors.facebook_app_id}}</string> <string name="facebook_client_token">{{flavors.facebook_client_token}}</string> <string name="twitter_redirect_uri_scheme">{{project_name.paramCase()}}</string> <string name="flavor_deep_link_domain">{{flavors.deep_link_domain}}</string> <string name="admob_app_id">{{flavors.android_ads_app_id}}</string> </resources>
news_toolkit/tool/generator/static/strings.xml/0
{ "file_path": "news_toolkit/tool/generator/static/strings.xml", "repo_id": "news_toolkit", "token_count": 171 }
907
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -e # Ensure that the pods repos are up to date, since analyze will not check for # the latest versions of pods, so can use stale Flutter or FlutterMacOS pods # for analysis otherwise. pod repo update --verbose
packages/.ci/scripts/update_pods.sh/0
{ "file_path": "packages/.ci/scripts/update_pods.sh", "repo_id": "packages", "token_count": 104 }
908
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: create all_packages app script: .ci/scripts/create_all_packages_app.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: build all_packages for macOS debug script: .ci/scripts/build_all_packages_app.sh args: ["macos", "debug"] - name: build all_packages for macOS release script: .ci/scripts/build_all_packages_app.sh args: ["macos", "release"]
packages/.ci/targets/macos_build_all_packages.yaml/0
{ "file_path": "packages/.ci/targets/macos_build_all_packages.yaml", "repo_id": "packages", "token_count": 194 }
909
# This custom rule set only exists to allow opting out of the repository # default of enabling unawaited_futures. Please do NOT add more changes # here without consulting with #hackers-ecosystem on Discord. include: ../../analysis_options.yaml linter: rules: # Matches flutter/flutter, which disables this rule due to false positives. unawaited_futures: false
packages/packages/animations/analysis_options.yaml/0
{ "file_path": "packages/packages/animations/analysis_options.yaml", "repo_id": "packages", "token_count": 106 }
910
// Copyright 2013 The Flutter 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 [FadeScaleTransition]. class FadeScaleTransitionDemo extends StatefulWidget { /// Creates the demo page for [FadeScaleTransition]. const FadeScaleTransitionDemo({super.key}); @override State<FadeScaleTransitionDemo> createState() => _FadeScaleTransitionDemoState(); } class _FadeScaleTransitionDemoState extends State<FadeScaleTransitionDemo> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { _controller = AnimationController( value: 0.0, duration: const Duration(milliseconds: 150), reverseDuration: const Duration(milliseconds: 75), vsync: this, )..addStatusListener((AnimationStatus status) { setState(() { // setState needs to be called to trigger a rebuild because // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based // the latest value of [_controller.status]. }); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } bool get _isAnimationRunningForwardsOrComplete { switch (_controller.status) { case AnimationStatus.forward: case AnimationStatus.completed: return true; case AnimationStatus.reverse: case AnimationStatus.dismissed: return false; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Fade')), floatingActionButton: AnimatedBuilder( animation: _controller, builder: (BuildContext context, Widget? child) { return FadeScaleTransition( animation: _controller, child: child, ); }, child: Visibility( visible: _controller.status != AnimationStatus.dismissed, child: FloatingActionButton( child: const Icon(Icons.add), onPressed: () {}, ), ), ), bottomNavigationBar: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Divider(height: 0.0), Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (BuildContext context) { return _ExampleAlertDialog(); }, ); }, child: const Text('SHOW MODAL'), ), const SizedBox(width: 10), ElevatedButton( onPressed: () { if (_isAnimationRunningForwardsOrComplete) { _controller.reverse(); } else { _controller.forward(); } }, child: _isAnimationRunningForwardsOrComplete ? const Text('HIDE FAB') : const Text('SHOW FAB'), ), ], ), ), ], ), ); } } class _ExampleAlertDialog extends StatelessWidget { @override Widget build(BuildContext context) { return AlertDialog( content: const Text('Alert Dialog'), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('CANCEL'), ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('DISCARD'), ), ], ); } }
packages/packages/animations/example/lib/fade_scale_transition.dart/0
{ "file_path": "packages/packages/animations/example/lib/fade_scale_transition.dart", "repo_id": "packages", "token_count": 1922 }
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:flutter/material.dart'; /// Determines which type of shared axis transition is used. enum SharedAxisTransitionType { /// Creates a shared axis vertical (y-axis) page transition. vertical, /// Creates a shared axis horizontal (x-axis) page transition. horizontal, /// Creates a shared axis scaled (z-axis) page transition. scaled, } /// Used by [PageTransitionsTheme] to define a page route transition animation /// in which outgoing and incoming elements share a fade transition. /// /// The shared axis pattern provides the transition animation between UI elements /// that have a spatial or navigational relationship. For example, /// transitioning from one page of a sign up page to the next one. /// /// The following example shows how the SharedAxisPageTransitionsBuilder can /// be used in a [PageTransitionsTheme] to change the default transitions /// of [MaterialPageRoute]s. /// /// ```dart /// MaterialApp( /// theme: ThemeData( /// pageTransitionsTheme: PageTransitionsTheme( /// builders: { /// TargetPlatform.android: SharedAxisPageTransitionsBuilder( /// transitionType: SharedAxisTransitionType.horizontal, /// ), /// TargetPlatform.iOS: SharedAxisPageTransitionsBuilder( /// transitionType: SharedAxisTransitionType.horizontal, /// ), /// }, /// ), /// ), /// routes: { /// '/': (BuildContext context) { /// return Container( /// color: Colors.red, /// child: Center( /// child: ElevatedButton( /// child: Text('Push route'), /// onPressed: () { /// Navigator.of(context).pushNamed('/a'); /// }, /// ), /// ), /// ); /// }, /// '/a' : (BuildContext context) { /// return Container( /// color: Colors.blue, /// child: Center( /// child: ElevatedButton( /// child: Text('Pop route'), /// onPressed: () { /// Navigator.of(context).pop(); /// }, /// ), /// ), /// ); /// }, /// }, /// ); /// ``` class SharedAxisPageTransitionsBuilder extends PageTransitionsBuilder { /// Construct a [SharedAxisPageTransitionsBuilder]. const SharedAxisPageTransitionsBuilder({ required this.transitionType, this.fillColor, }); /// Determines which [SharedAxisTransitionType] to build. final SharedAxisTransitionType transitionType; /// The color to use for the background color during the transition. /// /// This defaults to the [Theme]'s [ThemeData.canvasColor]. final Color? fillColor; @override Widget buildTransitions<T>( PageRoute<T>? route, BuildContext? context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { return SharedAxisTransition( animation: animation, secondaryAnimation: secondaryAnimation, transitionType: transitionType, fillColor: fillColor, child: child, ); } } /// Defines a transition in which outgoing and incoming elements share a fade /// transition. /// /// The shared axis pattern provides the transition animation between UI elements /// that have a spatial or navigational relationship. For example, /// transitioning from one page of a sign up page to the next one. /// /// Consider using [SharedAxisTransition] within a /// [PageTransitionsTheme] if you want to apply this kind of transition to /// [MaterialPageRoute] transitions within a Navigator (see /// [SharedAxisPageTransitionsBuilder] for example code). /// /// This transition can also be used directly in a /// [PageTransitionSwitcher.transitionBuilder] to transition /// from one widget to another as seen in the following example: /// /// ```dart /// int _selectedIndex = 0; /// /// final List<Color> _colors = [Colors.white, Colors.red, Colors.yellow]; /// /// @override /// Widget build(BuildContext context) { /// return Scaffold( /// appBar: AppBar( /// title: const Text('Page Transition Example'), /// ), /// body: PageTransitionSwitcher( /// // reverse: true, // uncomment to see transition in reverse /// transitionBuilder: ( /// Widget child, /// Animation<double> primaryAnimation, /// Animation<double> secondaryAnimation, /// ) { /// return SharedAxisTransition( /// animation: primaryAnimation, /// secondaryAnimation: secondaryAnimation, /// transitionType: SharedAxisTransitionType.horizontal, /// child: child, /// ); /// }, /// child: Container( /// key: ValueKey<int>(_selectedIndex), /// color: _colors[_selectedIndex], /// child: Center( /// child: FlutterLogo(size: 300), /// ) /// ), /// ), /// bottomNavigationBar: BottomNavigationBar( /// items: const <BottomNavigationBarItem>[ /// BottomNavigationBarItem( /// icon: Icon(Icons.home), /// title: Text('White'), /// ), /// BottomNavigationBarItem( /// icon: Icon(Icons.business), /// title: Text('Red'), /// ), /// BottomNavigationBarItem( /// icon: Icon(Icons.school), /// title: Text('Yellow'), /// ), /// ], /// currentIndex: _selectedIndex, /// onTap: (int index) { /// setState(() { /// _selectedIndex = index; /// }); /// }, /// ), /// ); /// } /// ``` class SharedAxisTransition extends StatelessWidget { /// Creates a [SharedAxisTransition]. /// /// The [animation] and [secondaryAnimation] argument are required and must /// not be null. const SharedAxisTransition({ super.key, required this.animation, required this.secondaryAnimation, required this.transitionType, this.fillColor, this.child, }); /// The animation that drives the [child]'s entrance and exit. /// /// See also: /// /// * [TransitionRoute.animate], which is the value given to this property /// when it is used as a page transition. final Animation<double> animation; /// The animation that transitions [child] when new content is pushed on top /// of it. /// /// See also: /// /// * [TransitionRoute.secondaryAnimation], which is the value given to this /// property when the it is used as a page transition. final Animation<double> secondaryAnimation; /// Determines which type of shared axis transition is used. /// /// See also: /// /// * [SharedAxisTransitionType], which defines and describes all shared /// axis transition types. final SharedAxisTransitionType transitionType; /// The color to use for the background color during the transition. /// /// This defaults to the [Theme]'s [ThemeData.canvasColor]. final Color? fillColor; /// The widget below this widget in the tree. /// /// This widget will transition in and out as driven by [animation] and /// [secondaryAnimation]. final Widget? child; @override Widget build(BuildContext context) { final Color color = fillColor ?? Theme.of(context).canvasColor; return DualTransitionBuilder( animation: animation, forwardBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return _EnterTransition( animation: animation, transitionType: transitionType, child: child, ); }, reverseBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return _ExitTransition( animation: animation, transitionType: transitionType, reverse: true, fillColor: color, child: child, ); }, child: DualTransitionBuilder( animation: ReverseAnimation(secondaryAnimation), forwardBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return _EnterTransition( animation: animation, transitionType: transitionType, reverse: true, child: child, ); }, reverseBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return _ExitTransition( animation: animation, transitionType: transitionType, fillColor: color, child: child, ); }, child: child, ), ); } } class _EnterTransition extends StatelessWidget { const _EnterTransition({ required this.animation, required this.transitionType, this.reverse = false, this.child, }); final Animation<double> animation; final SharedAxisTransitionType transitionType; final Widget? child; final bool reverse; static final Animatable<double> _fadeInTransition = CurveTween( curve: Easing.legacyDecelerate, ).chain(CurveTween(curve: const Interval(0.3, 1.0))); static final Animatable<double> _scaleDownTransition = Tween<double>( begin: 1.10, end: 1.00, ).chain(CurveTween(curve: Easing.legacy)); static final Animatable<double> _scaleUpTransition = Tween<double>( begin: 0.80, end: 1.00, ).chain(CurveTween(curve: Easing.legacy)); @override Widget build(BuildContext context) { switch (transitionType) { case SharedAxisTransitionType.horizontal: final Animatable<Offset> slideInTransition = Tween<Offset>( begin: Offset(!reverse ? 30.0 : -30.0, 0.0), end: Offset.zero, ).chain(CurveTween(curve: Easing.legacy)); return FadeTransition( opacity: _fadeInTransition.animate(animation), child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { return Transform.translate( offset: slideInTransition.evaluate(animation), child: child, ); }, child: child, ), ); case SharedAxisTransitionType.vertical: final Animatable<Offset> slideInTransition = Tween<Offset>( begin: Offset(0.0, !reverse ? 30.0 : -30.0), end: Offset.zero, ).chain(CurveTween(curve: Easing.legacy)); return FadeTransition( opacity: _fadeInTransition.animate(animation), child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { return Transform.translate( offset: slideInTransition.evaluate(animation), child: child, ); }, child: child, ), ); case SharedAxisTransitionType.scaled: return FadeTransition( opacity: _fadeInTransition.animate(animation), child: ScaleTransition( scale: (!reverse ? _scaleUpTransition : _scaleDownTransition) .animate(animation), child: child, ), ); } } } class _ExitTransition extends StatelessWidget { const _ExitTransition({ required this.animation, required this.transitionType, this.reverse = false, required this.fillColor, this.child, }); final Animation<double> animation; final SharedAxisTransitionType transitionType; final bool reverse; final Color fillColor; final Widget? child; static final Animatable<double> _fadeOutTransition = _FlippedCurveTween( curve: Easing.legacyAccelerate, ).chain(CurveTween(curve: const Interval(0.0, 0.3))); static final Animatable<double> _scaleUpTransition = Tween<double>( begin: 1.00, end: 1.10, ).chain(CurveTween(curve: Easing.legacy)); static final Animatable<double> _scaleDownTransition = Tween<double>( begin: 1.00, end: 0.80, ).chain(CurveTween(curve: Easing.legacy)); @override Widget build(BuildContext context) { switch (transitionType) { case SharedAxisTransitionType.horizontal: final Animatable<Offset> slideOutTransition = Tween<Offset>( begin: Offset.zero, end: Offset(!reverse ? -30.0 : 30.0, 0.0), ).chain(CurveTween(curve: Easing.legacy)); return FadeTransition( opacity: _fadeOutTransition.animate(animation), child: ColoredBox( color: fillColor, child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { return Transform.translate( offset: slideOutTransition.evaluate(animation), child: child, ); }, child: child, ), ), ); case SharedAxisTransitionType.vertical: final Animatable<Offset> slideOutTransition = Tween<Offset>( begin: Offset.zero, end: Offset(0.0, !reverse ? -30.0 : 30.0), ).chain(CurveTween(curve: Easing.legacy)); return FadeTransition( opacity: _fadeOutTransition.animate(animation), child: ColoredBox( color: fillColor, child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { return Transform.translate( offset: slideOutTransition.evaluate(animation), child: child, ); }, child: child, ), ), ); case SharedAxisTransitionType.scaled: return FadeTransition( opacity: _fadeOutTransition.animate(animation), child: ColoredBox( color: fillColor, child: ScaleTransition( scale: (!reverse ? _scaleUpTransition : _scaleDownTransition) .animate(animation), child: child, ), ), ); } } } /// Enables creating a flipped [CurveTween]. /// /// This creates a [CurveTween] that evaluates to a result that flips the /// tween vertically. /// /// This tween sequence assumes that the evaluated result has to be a double /// between 0.0 and 1.0. class _FlippedCurveTween extends CurveTween { /// Creates a vertically flipped [CurveTween]. _FlippedCurveTween({ required super.curve, }); @override double transform(double t) => 1.0 - super.transform(t); }
packages/packages/animations/lib/src/shared_axis_transition.dart/0
{ "file_path": "packages/packages/animations/lib/src/shared_axis_transition.dart", "repo_id": "packages", "token_count": 5944 }
912
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>camera_example</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSApplicationCategoryType</key> <string></string> <key>LSRequiresIPhoneOS</key> <true/> <key>NSCameraUsageDescription</key> <string>Can I use the camera please? Only for demo purpose of the app</string> <key>NSMicrophoneUsageDescription</key> <string>Only for demo purpose of the app</string> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>arm64</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>CADisableMinimumFrameDurationOnPhone</key> <true/> <key>UIApplicationSupportsIndirectInputEvents</key> <true/> </dict> </plist>
packages/packages/camera/camera/example/ios/Runner/Info.plist/0
{ "file_path": "packages/packages/camera/camera/example/ios/Runner/Info.plist", "repo_id": "packages", "token_count": 735 }
913
name: camera description: A Flutter plugin for controlling the camera. Supports previewing the camera feed, capturing images and video, and streaming image buffers to Dart. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 version: 0.10.5+9 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: default_package: camera_android ios: default_package: camera_avfoundation web: default_package: camera_web dependencies: camera_android: ^0.10.7 camera_avfoundation: ^0.9.13 camera_platform_interface: ^2.5.0 camera_web: ^0.3.1 flutter: sdk: flutter flutter_plugin_android_lifecycle: ^2.0.2 dev_dependencies: flutter_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 topics: - camera
packages/packages/camera/camera/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera/pubspec.yaml", "repo_id": "packages", "token_count": 381 }
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. package io.flutter.plugins.camera.features; import android.app.Activity; import androidx.annotation.NonNull; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DartMessenger; import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature; import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature; import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature; import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature; import io.flutter.plugins.camera.features.flash.FlashFeature; import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature; import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature; import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionPreset; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * These are all of our available features in the camera. Used in the Camera to access all features * in a simpler way. */ public class CameraFeatures { private static final String AUTO_FOCUS = "AUTO_FOCUS"; private static final String EXPOSURE_LOCK = "EXPOSURE_LOCK"; private static final String EXPOSURE_OFFSET = "EXPOSURE_OFFSET"; private static final String EXPOSURE_POINT = "EXPOSURE_POINT"; private static final String FLASH = "FLASH"; private static final String FOCUS_POINT = "FOCUS_POINT"; private static final String FPS_RANGE = "FPS_RANGE"; private static final String NOISE_REDUCTION = "NOISE_REDUCTION"; private static final String REGION_BOUNDARIES = "REGION_BOUNDARIES"; private static final String RESOLUTION = "RESOLUTION"; private static final String SENSOR_ORIENTATION = "SENSOR_ORIENTATION"; private static final String ZOOM_LEVEL = "ZOOM_LEVEL"; @NonNull public static CameraFeatures init( @NonNull CameraFeatureFactory cameraFeatureFactory, @NonNull CameraProperties cameraProperties, @NonNull Activity activity, @NonNull DartMessenger dartMessenger, @NonNull ResolutionPreset resolutionPreset) { CameraFeatures cameraFeatures = new CameraFeatures(); cameraFeatures.setAutoFocus( cameraFeatureFactory.createAutoFocusFeature(cameraProperties, false)); cameraFeatures.setExposureLock( cameraFeatureFactory.createExposureLockFeature(cameraProperties)); cameraFeatures.setExposureOffset( cameraFeatureFactory.createExposureOffsetFeature(cameraProperties)); SensorOrientationFeature sensorOrientationFeature = cameraFeatureFactory.createSensorOrientationFeature( cameraProperties, activity, dartMessenger); cameraFeatures.setSensorOrientation(sensorOrientationFeature); cameraFeatures.setExposurePoint( cameraFeatureFactory.createExposurePointFeature( cameraProperties, sensorOrientationFeature)); cameraFeatures.setFlash(cameraFeatureFactory.createFlashFeature(cameraProperties)); cameraFeatures.setFocusPoint( cameraFeatureFactory.createFocusPointFeature(cameraProperties, sensorOrientationFeature)); cameraFeatures.setFpsRange(cameraFeatureFactory.createFpsRangeFeature(cameraProperties)); cameraFeatures.setNoiseReduction( cameraFeatureFactory.createNoiseReductionFeature(cameraProperties)); cameraFeatures.setResolution( cameraFeatureFactory.createResolutionFeature( cameraProperties, resolutionPreset, cameraProperties.getCameraName())); cameraFeatures.setZoomLevel(cameraFeatureFactory.createZoomLevelFeature(cameraProperties)); return cameraFeatures; } private final Map<String, CameraFeature<?>> featureMap = new HashMap<>(); /** * Gets a collection of all features that have been set. * * @return A collection of all features that have been set. */ @NonNull public Collection<CameraFeature<?>> getAllFeatures() { return this.featureMap.values(); } /** * Gets the auto focus feature if it has been set. * * @return the auto focus feature. */ @NonNull public AutoFocusFeature getAutoFocus() { return (AutoFocusFeature) featureMap.get(AUTO_FOCUS); } /** * Sets the instance of the auto focus feature. * * @param autoFocus the {@link AutoFocusFeature} instance to set. */ public void setAutoFocus(@NonNull AutoFocusFeature autoFocus) { this.featureMap.put(AUTO_FOCUS, autoFocus); } /** * Gets the exposure lock feature if it has been set. * * @return the exposure lock feature. */ @NonNull public ExposureLockFeature getExposureLock() { return (ExposureLockFeature) featureMap.get(EXPOSURE_LOCK); } /** * Sets the instance of the exposure lock feature. * * @param exposureLock the {@link ExposureLockFeature} instance to set. */ public void setExposureLock(@NonNull ExposureLockFeature exposureLock) { this.featureMap.put(EXPOSURE_LOCK, exposureLock); } /** * Gets the exposure offset feature if it has been set. * * @return the exposure offset feature. */ @NonNull public ExposureOffsetFeature getExposureOffset() { return (ExposureOffsetFeature) Objects.requireNonNull(featureMap.get(EXPOSURE_OFFSET)); } /** * Sets the instance of the exposure offset feature. * * @param exposureOffset the {@link ExposureOffsetFeature} instance to set. */ public void setExposureOffset(@NonNull ExposureOffsetFeature exposureOffset) { this.featureMap.put(EXPOSURE_OFFSET, exposureOffset); } /** * Gets the exposure point feature if it has been set. * * @return the exposure point feature. */ @NonNull public ExposurePointFeature getExposurePoint() { return (ExposurePointFeature) Objects.requireNonNull(featureMap.get(EXPOSURE_POINT)); } /** * Sets the instance of the exposure point feature. * * @param exposurePoint the {@link ExposurePointFeature} instance to set. */ public void setExposurePoint(@NonNull ExposurePointFeature exposurePoint) { this.featureMap.put(EXPOSURE_POINT, exposurePoint); } /** * Gets the flash feature if it has been set. * * @return the flash feature. */ @NonNull public FlashFeature getFlash() { return (FlashFeature) Objects.requireNonNull(featureMap.get(FLASH)); } /** * Sets the instance of the flash feature. * * @param flash the {@link FlashFeature} instance to set. */ public void setFlash(@NonNull FlashFeature flash) { this.featureMap.put(FLASH, flash); } /** * Gets the focus point feature if it has been set. * * @return the focus point feature. */ @NonNull public FocusPointFeature getFocusPoint() { return (FocusPointFeature) Objects.requireNonNull(featureMap.get(FOCUS_POINT)); } /** * Sets the instance of the focus point feature. * * @param focusPoint the {@link FocusPointFeature} instance to set. */ public void setFocusPoint(@NonNull FocusPointFeature focusPoint) { this.featureMap.put(FOCUS_POINT, focusPoint); } /** * Gets the fps range feature if it has been set. * * @return the fps range feature. */ @NonNull public FpsRangeFeature getFpsRange() { return (FpsRangeFeature) Objects.requireNonNull(featureMap.get(FPS_RANGE)); } /** * Sets the instance of the fps range feature. * * @param fpsRange the {@link FpsRangeFeature} instance to set. */ public void setFpsRange(@NonNull FpsRangeFeature fpsRange) { this.featureMap.put(FPS_RANGE, fpsRange); } /** * Gets the noise reduction feature if it has been set. * * @return the noise reduction feature. */ @NonNull public NoiseReductionFeature getNoiseReduction() { return (NoiseReductionFeature) Objects.requireNonNull(featureMap.get(NOISE_REDUCTION)); } /** * Sets the instance of the noise reduction feature. * * @param noiseReduction the {@link NoiseReductionFeature} instance to set. */ public void setNoiseReduction(@NonNull NoiseReductionFeature noiseReduction) { this.featureMap.put(NOISE_REDUCTION, noiseReduction); } /** * Gets the resolution feature if it has been set. * * @return the resolution feature. */ @NonNull public ResolutionFeature getResolution() { return (ResolutionFeature) Objects.requireNonNull(featureMap.get(RESOLUTION)); } /** * Sets the instance of the resolution feature. * * @param resolution the {@link ResolutionFeature} instance to set. */ public void setResolution(@NonNull ResolutionFeature resolution) { this.featureMap.put(RESOLUTION, resolution); } /** * Gets the sensor orientation feature if it has been set. * * @return the sensor orientation feature. */ @NonNull public SensorOrientationFeature getSensorOrientation() { return (SensorOrientationFeature) Objects.requireNonNull(featureMap.get(SENSOR_ORIENTATION)); } /** * Sets the instance of the sensor orientation feature. * * @param sensorOrientation the {@link SensorOrientationFeature} instance to set. */ public void setSensorOrientation(@NonNull SensorOrientationFeature sensorOrientation) { this.featureMap.put(SENSOR_ORIENTATION, sensorOrientation); } /** * Gets the zoom level feature if it has been set. * * @return the zoom level feature. */ @NonNull public ZoomLevelFeature getZoomLevel() { return (ZoomLevelFeature) Objects.requireNonNull(featureMap.get(ZOOM_LEVEL)); } /** * Sets the instance of the zoom level feature. * * @param zoomLevel the {@link ZoomLevelFeature} instance to set. */ public void setZoomLevel(@NonNull ZoomLevelFeature zoomLevel) { this.featureMap.put(ZOOM_LEVEL, zoomLevel); } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatures.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatures.java", "repo_id": "packages", "token_count": 3188 }
915
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=false
packages/packages/camera/camera_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/camera/camera_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
916
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.camera.core.CameraControl; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraControlFlutterApi; public class CameraControlFlutterApiImpl extends CameraControlFlutterApi { private final @NonNull InstanceManager instanceManager; public CameraControlFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } /** * Creates a {@link CameraControl} instance in Dart. {@code reply} is not used so it can be empty. */ void create(CameraControl cameraControl, Reply<Void> reply) { if (!instanceManager.containsInstance(cameraControl)) { create(instanceManager.addHostCreatedInstance(cameraControl), reply); } } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java", "repo_id": "packages", "token_count": 319 }
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 android.util.Range; import androidx.annotation.NonNull; import androidx.camera.core.ExposureState; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureCompensationRange; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureStateFlutterApi; public class ExposureStateFlutterApiImpl extends ExposureStateFlutterApi { private final InstanceManager instanceManager; public ExposureStateFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } /** * Creates a {@link ExposureState} on the Dart side with its exposure compensation range that can * be used to set the exposure compensation index and its exposure compensation step, the smallest * step by which the exposure compensation can be changed. */ void create(@NonNull ExposureState exposureState, @NonNull Reply<Void> reply) { if (instanceManager.containsInstance(exposureState)) { return; } final Range<Integer> exposureCompensationRangeFromState = exposureState.getExposureCompensationRange(); ExposureCompensationRange exposureCompensationRange = new ExposureCompensationRange.Builder() .setMinCompensation(exposureCompensationRangeFromState.getLower().longValue()) .setMaxCompensation(exposureCompensationRangeFromState.getUpper().longValue()) .build(); final Double exposureCompensationStep = exposureState.getExposureCompensationStep().doubleValue(); create( instanceManager.addHostCreatedInstance(exposureState), exposureCompensationRange, exposureCompensationStep, reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java", "repo_id": "packages", "token_count": 609 }
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.lifecycle.Observer; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverHostApi; import java.util.Objects; /** * Host API implementation for {@link Observer}. * * <p>This class may handle instantiating and adding native object instances that are attached to a * Dart instance or handle method calls on the associated native class or an instance of the class. */ public class ObserverHostApiImpl implements ObserverHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private final ObserverProxy observerProxy; /** Proxy for constructor of {@link Observer}. */ @VisibleForTesting public static class ObserverProxy { /** Creates an instance of {@link Observer}. */ @NonNull public <T> ObserverImpl<T> create( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { return new ObserverImpl<T>(binaryMessenger, instanceManager); } } /** Implementation of {@link Observer} that passes arguments of callback methods to Dart. */ public static class ObserverImpl<T> implements Observer<T> { private ObserverFlutterApiWrapper observerFlutterApiWrapper; /** * Constructs an instance of {@link Observer} that passes arguments of callbacks methods to * Dart. */ public ObserverImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(); observerFlutterApiWrapper = new ObserverFlutterApiWrapper(binaryMessenger, instanceManager); } /** Method called when the data in observance is changed to {@code value}. */ @Override public void onChanged(T value) { observerFlutterApiWrapper.onChanged(this, value, reply -> {}); } /** Flutter API used to send messages back to Dart. */ @VisibleForTesting void setApi(@NonNull ObserverFlutterApiWrapper api) { this.observerFlutterApiWrapper = api; } } /** * Constructs a {@link ObserverHostApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public ObserverHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this(binaryMessenger, instanceManager, new ObserverProxy()); } /** * Constructs a {@link ObserverHostApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects * @param proxy proxy for constructor of {@link Observer} */ @VisibleForTesting ObserverHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull ObserverProxy observerProxy) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.observerProxy = observerProxy; } /** Creates an {@link Observer} instance with the specified observer. */ @Override public void create(@NonNull Long identifier) { instanceManager.addDartCreatedInstance( observerProxy.create(binaryMessenger, instanceManager), identifier); } private Observer<?> getObserverInstance(@NonNull Long identifier) { return Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java", "repo_id": "packages", "token_count": 1102 }
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 android.app.Activity; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesHostApi; import java.io.File; import java.io.IOException; public class SystemServicesHostApiImpl implements SystemServicesHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; @Nullable private Context context; @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); @VisibleForTesting public @NonNull SystemServicesFlutterApiImpl systemServicesFlutterApi; private Activity activity; private PermissionsRegistry permissionsRegistry; public SystemServicesHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull Context context) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.context = context; this.systemServicesFlutterApi = new SystemServicesFlutterApiImpl(binaryMessenger); } /** Sets the context, which is used to get the cache directory. */ public void setContext(@NonNull Context context) { this.context = context; } public void setActivity(@NonNull Activity activity) { this.activity = activity; } public void setPermissionsRegistry(@Nullable PermissionsRegistry permissionsRegistry) { this.permissionsRegistry = permissionsRegistry; } /** * Requests camera permissions using an instance of a {@link CameraPermissionsManager}. * * <p>Will result with {@code null} if permissions were approved or there were no errors; * otherwise, it will result with the error data explaining what went wrong. */ @Override public void requestCameraPermissions( @NonNull Boolean enableAudio, @NonNull Result<CameraPermissionsErrorData> result) { if (activity == null) { throw new IllegalStateException("Activity must be set to request camera permissions."); } CameraPermissionsManager cameraPermissionsManager = cameraXProxy.createCameraPermissionsManager(); cameraPermissionsManager.requestPermissions( activity, permissionsRegistry, enableAudio, (String errorCode, String description) -> { if (errorCode == null) { result.success(null); } else { // If permissions are ongoing or denied, error data will be sent to be handled. CameraPermissionsErrorData errorData = new CameraPermissionsErrorData.Builder() .setErrorCode(errorCode) .setDescription(description) .build(); result.success(errorData); } }); } /** Returns a path to be used to create a temp file in the current cache directory. */ @Override @NonNull public String getTempFilePath(@NonNull String prefix, @NonNull String suffix) { if (context == null) { throw new IllegalStateException("Context must be set to create a temporary file."); } try { File path = File.createTempFile(prefix, suffix, context.getCacheDir()); return path.toString(); } catch (IOException | SecurityException e) { throw new GeneratedCameraXLibrary.FlutterError( "getTempFilePath_failure", "SystemServicesHostApiImpl.getTempFilePath encountered an exception: " + e.toString(), null); } } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java", "repo_id": "packages", "token_count": 1307 }
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 static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.provider.Settings; import android.view.Display; import android.view.Surface; import android.view.WindowManager; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; public class DeviceOrientationManagerTest { private Activity mockActivity; private DeviceOrientationChangeCallback mockDeviceOrientationChangeCallback; private WindowManager mockWindowManager; private Display mockDisplay; private DeviceOrientationManager deviceOrientationManager; @Before @SuppressWarnings("deprecation") public void before() { mockActivity = mock(Activity.class); mockDisplay = mock(Display.class); mockWindowManager = mock(WindowManager.class); mockDeviceOrientationChangeCallback = mock(DeviceOrientationChangeCallback.class); when(mockActivity.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowManager); when(mockWindowManager.getDefaultDisplay()).thenReturn(mockDisplay); deviceOrientationManager = new DeviceOrientationManager(mockActivity, false, 0, mockDeviceOrientationChangeCallback); } @Test public void handleUIOrientationChange_shouldSendMessageWhenSensorAccessIsAllowed() { try (MockedStatic<Settings.System> mockedSystem = mockStatic(Settings.System.class)) { mockedSystem .when( () -> Settings.System.getInt(any(), eq(Settings.System.ACCELEROMETER_ROTATION), eq(0))) .thenReturn(0); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); deviceOrientationManager.handleUIOrientationChange(); } verify(mockDeviceOrientationChangeCallback, times(1)) .onChange(DeviceOrientation.LANDSCAPE_LEFT); } @Test public void handleOrientationChange_shouldSendMessageWhenOrientationIsUpdated() { DeviceOrientation previousOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientation newOrientation = DeviceOrientation.LANDSCAPE_LEFT; DeviceOrientationManager.handleOrientationChange( newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); verify(mockDeviceOrientationChangeCallback, times(1)).onChange(newOrientation); } @Test public void handleOrientationChange_shouldNotSendMessageWhenOrientationIsNotUpdated() { DeviceOrientation previousOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientation newOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientationManager.handleOrientationChange( newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); verify(mockDeviceOrientationChangeCallback, never()).onChange(any()); } @Test public void getUIOrientation() { // Orientation portrait and rotation of 0 should translate to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); DeviceOrientation uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); // Orientation portrait and rotation of 90 should translate to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_90); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); // Orientation portrait and rotation of 180 should translate to "PORTRAIT_DOWN". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_180); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_DOWN, uiOrientation); // Orientation portrait and rotation of 270 should translate to "PORTRAIT_DOWN". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_270); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_DOWN, uiOrientation); // Orientation landscape and rotation of 0 should translate to "LANDSCAPE_LEFT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_LEFT, uiOrientation); // Orientation landscape and rotation of 90 should translate to "LANDSCAPE_LEFT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_90); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_LEFT, uiOrientation); // Orientation landscape and rotation of 180 should translate to "LANDSCAPE_RIGHT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_180); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_RIGHT, uiOrientation); // Orientation landscape and rotation of 270 should translate to "LANDSCAPE_RIGHT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_270); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_RIGHT, uiOrientation); // Orientation undefined should default to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_UNDEFINED, Surface.ROTATION_0); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); } private void setUpUIOrientationMocks(int orientation, int rotation) { Resources mockResources = mock(Resources.class); Configuration mockConfiguration = mock(Configuration.class); when(mockDisplay.getRotation()).thenReturn(rotation); mockConfiguration.orientation = orientation; when(mockActivity.getResources()).thenReturn(mockResources); when(mockResources.getConfiguration()).thenReturn(mockConfiguration); } @Test public void getDefaultRotation_returnsExpectedValue() { final int expectedRotation = 90; when(mockDisplay.getRotation()).thenReturn(expectedRotation); final int defaultRotation = deviceOrientationManager.getDefaultRotation(); assertEquals(defaultRotation, expectedRotation); } @Test public void getDisplayTest() { Display display = deviceOrientationManager.getDisplay(); assertEquals(mockDisplay, display); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java", "repo_id": "packages", "token_count": 2355 }
921
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:meta/meta.dart' show immutable; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camera_control.dart'; import 'camerax_library.g.dart'; import 'capture_request_options.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'system_services.dart'; /// Class that provides ability to interoperate with android.hardware.camera2 /// APIs and apply options to its specific controls like capture request /// options. /// /// See https://developer.android.com/reference/androidx/camera/camera2/interop/Camera2CameraControl#from(androidx.camera.core.CameraControl). @immutable class Camera2CameraControl extends JavaObject { /// Creates a [Camera2CameraControl]. Camera2CameraControl( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.cameraControl}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _Camera2CameraControlHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); _api.createFromInstances(this, cameraControl); } /// Constructs a [Camera2CameraControl] that is not automatically attached to a /// native object. Camera2CameraControl.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.cameraControl}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _Camera2CameraControlHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } late final _Camera2CameraControlHostApiImpl _api; /// The [CameraControl] info that this instance is based on. /// /// Note that options specified with this [Camera2CameraControl] instance will /// have higher priority than [cameraControl]. final CameraControl cameraControl; /// Updates capture session with options that the specified /// [CaptureRequestOptions] contains. /// /// Options will be merged with existing options, and if conflicting with what /// was previously set, these options will override those pre-existing. Once /// merged, these values will be submitted with every repeating and single /// capture request issued by CameraX. Future<void> addCaptureRequestOptions( CaptureRequestOptions captureRequestOptions) { return _api.addCaptureRequestOptionsFromInstances( this, captureRequestOptions); } } /// Host API implementation of [Camera2CameraControl]. class _Camera2CameraControlHostApiImpl extends Camera2CameraControlHostApi { /// Constructs a [_Camera2CameraControlHostApiImpl]. /// /// 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]. _Camera2CameraControlHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// 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; /// Creates a [Camera2CameraControl] instance derived from the specified /// [CameraControl] instance. Future<void> createFromInstances( Camera2CameraControl instance, CameraControl cameraControl, ) { return create( instanceManager.addDartCreatedInstance( instance, onCopy: (Camera2CameraControl original) => Camera2CameraControl.detached( cameraControl: original.cameraControl, binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), ), instanceManager.getIdentifier(cameraControl)!, ); } /// Updates capture session corresponding to the specified /// [Camera2CameraControl] instance with options that the specified /// [CaptureRequestOptions] contains. Future<void> addCaptureRequestOptionsFromInstances( Camera2CameraControl instance, CaptureRequestOptions captureRequestOptions, ) async { try { return addCaptureRequestOptions( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(captureRequestOptions)!, ); } on PlatformException catch (e) { SystemServices.cameraErrorStreamController.add(e.message ?? 'The camera was unable to set new capture request options due to new options being unavailable or the camera being closed.'); } } }
packages/packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart", "repo_id": "packages", "token_count": 1576 }
922
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart' show BinaryMessenger; import 'package:meta/meta.dart' show immutable, protected; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'plane_proxy.dart'; /// Representation of a single complete image buffer. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageProxy. @immutable class ImageProxy extends JavaObject { /// Constructs a [ImageProxy] that is not automatically attached to a native object. ImageProxy.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.format, required this.height, required this.width}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _ImageProxyHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } /// The image format. final int format; /// The image height. final int height; /// The image width. final int width; late final _ImageProxyHostApiImpl _api; /// Returns the list of color planes of image data. Future<List<PlaneProxy>> getPlanes() => _api.getPlanesFromInstances(this); /// Closes the underlying image. Future<void> close() => _api.closeFromInstances(this); } /// Host API implementation of [ImageProxy]. class _ImageProxyHostApiImpl extends ImageProxyHostApi { /// Constructor for [_ImageProxyHostApiImpl]. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an `InstanceManager` is being created. _ImageProxyHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); final BinaryMessenger? binaryMessenger; final InstanceManager instanceManager; /// Returns the list of color planes of the image data represnted by the /// [instance]. Future<List<PlaneProxy>> getPlanesFromInstances( ImageProxy instance, ) async { final List<int?> planesAsObjects = await getPlanes( instanceManager.getIdentifier(instance)!, ); return planesAsObjects.map((int? planeIdentifier) { return instanceManager .getInstanceWithWeakReference<PlaneProxy>(planeIdentifier!)!; }).toList(); } /// Closes the underlying image of the [instance]. Future<void> closeFromInstances( ImageProxy instance, ) { return close( instanceManager.getIdentifier(instance)!, ); } } /// Flutter API implementation for [ImageProxy]. /// /// 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 ImageProxyFlutterApiImpl implements ImageProxyFlutterApi { /// Constructs a [ImageProxyFlutterApiImpl]. /// /// 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]. ImageProxyFlutterApiImpl({ 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, int format, int height, int width, ) { _instanceManager.addHostCreatedInstance( ImageProxy.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, format: format, height: height, width: width, ), identifier, onCopy: (ImageProxy original) => ImageProxy.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, format: original.format, height: original.height, width: original.width), ); } }
packages/packages/camera/camera_android_camerax/lib/src/image_proxy.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/image_proxy.dart", "repo_id": "packages", "token_count": 1482 }
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 'dart:async'; import 'package:camera_platform_interface/camera_platform_interface.dart' show CameraException; import 'package:flutter/services.dart'; import 'camerax_library.g.dart'; // Ignoring lint indicating this class only contains static members // as this class is a wrapper for various Android system services. // ignore_for_file: avoid_classes_with_only_static_members /// Utility class that offers access to Android system services needed for /// camera usage and other informational streams. class SystemServices { /// Stream that emits the errors caused by camera usage on the native side. static final StreamController<String> cameraErrorStreamController = StreamController<String>.broadcast(); /// Requests permission to access the camera and audio if specified. static Future<void> requestCameraPermissions(bool enableAudio, {BinaryMessenger? binaryMessenger}) { final SystemServicesHostApiImpl api = SystemServicesHostApiImpl(binaryMessenger: binaryMessenger); return api.sendCameraPermissionsRequest(enableAudio); } /// Returns a file path which was used to create a temporary file. /// Prefix is a part of the file name, and suffix is the file extension. /// /// The file and path constraints are determined by the implementation of /// File.createTempFile(prefix, suffix, cacheDir), on the android side, where /// where cacheDir is the cache directory identified by the current application /// context using context.getCacheDir(). /// /// Ex: getTempFilePath('prefix', 'suffix') would return a string of the form /// '<cachePath>/prefix3213453.suffix', where the numbers after prefix and /// before suffix are determined by the call to File.createTempFile and /// therefore random. static Future<String> getTempFilePath(String prefix, String suffix, {BinaryMessenger? binaryMessenger}) { final SystemServicesHostApi api = SystemServicesHostApi(binaryMessenger: binaryMessenger); return api.getTempFilePath(prefix, suffix); } } /// Host API implementation of [SystemServices]. class SystemServicesHostApiImpl extends SystemServicesHostApi { /// Constructs an [SystemServicesHostApiImpl]. /// /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, /// which routes to the host platform. SystemServicesHostApiImpl({this.binaryMessenger}) : super(binaryMessenger: binaryMessenger); /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? binaryMessenger; /// Requests permission to access the camera and audio if specified. /// /// Will complete normally if permissions are successfully granted; otherwise, /// will throw a [CameraException]. Future<void> sendCameraPermissionsRequest(bool enableAudio) async { final CameraPermissionsErrorData? error = await requestCameraPermissions(enableAudio); if (error != null) { throw CameraException( error.errorCode, error.description, ); } } } /// Flutter API implementation of [SystemServices]. class SystemServicesFlutterApiImpl implements SystemServicesFlutterApi { /// Constructs an [SystemServicesFlutterApiImpl]. SystemServicesFlutterApiImpl(); /// Callback method for any errors caused by camera usage on the Java side. @override void onCameraError(String errorDescription) { SystemServices.cameraErrorStreamController.add(errorDescription); } }
packages/packages/camera/camera_android_camerax/lib/src/system_services.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/system_services.dart", "repo_id": "packages", "token_count": 1004 }
924
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_android_camerax/src/camera_info.dart'; import 'package:camera_android_camerax/src/camera_state.dart'; import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/exposure_state.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/live_data.dart'; import 'package:camera_android_camerax/src/zoom_state.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'camera_info_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[ TestCameraInfoHostApi, TestInstanceManagerHostApi ], customMocks: <MockSpec<Object>>[ MockSpec<LiveData<CameraState>>(as: #MockLiveCameraState), MockSpec<LiveData<ZoomState>>(as: #MockLiveZoomState), ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('CameraInfo', () { tearDown(() => TestCameraInfoHostApi.setup(null)); test( 'getSensorRotationDegrees makes call to retrieve expected sensor rotation', () async { final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); TestCameraInfoHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final CameraInfo cameraInfo = CameraInfo.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( cameraInfo, 0, onCopy: (_) => CameraInfo.detached(), ); when(mockApi.getSensorRotationDegrees( instanceManager.getIdentifier(cameraInfo))) .thenReturn(90); expect(await cameraInfo.getSensorRotationDegrees(), equals(90)); verify(mockApi.getSensorRotationDegrees(0)); }); test('getCameraState makes call to retrieve live camera state', () async { final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); TestCameraInfoHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final CameraInfo cameraInfo = CameraInfo.detached( instanceManager: instanceManager, ); const int cameraIdentifier = 55; final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); const int liveCameraStateIdentifier = 73; instanceManager.addHostCreatedInstance( cameraInfo, cameraIdentifier, onCopy: (_) => CameraInfo.detached(), ); instanceManager.addHostCreatedInstance( mockLiveCameraState, liveCameraStateIdentifier, onCopy: (_) => MockLiveCameraState(), ); when(mockApi.getCameraState(cameraIdentifier)) .thenReturn(liveCameraStateIdentifier); expect(await cameraInfo.getCameraState(), equals(mockLiveCameraState)); verify(mockApi.getCameraState(cameraIdentifier)); }); test('getExposureState makes call to retrieve expected ExposureState', () async { final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); TestCameraInfoHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final CameraInfo cameraInfo = CameraInfo.detached( instanceManager: instanceManager, ); const int cameraInfoIdentifier = 4; final ExposureState exposureState = ExposureState.detached( exposureCompensationRange: ExposureCompensationRange(maxCompensation: 0, minCompensation: 1), exposureCompensationStep: 4, instanceManager: instanceManager, ); const int exposureStateIdentifier = 45; instanceManager.addHostCreatedInstance( cameraInfo, cameraInfoIdentifier, onCopy: (_) => CameraInfo.detached(), ); instanceManager.addHostCreatedInstance( exposureState, exposureStateIdentifier, onCopy: (_) => ExposureState.detached( exposureCompensationRange: ExposureCompensationRange( maxCompensation: 0, minCompensation: 1), exposureCompensationStep: 4), ); when(mockApi.getExposureState(cameraInfoIdentifier)) .thenReturn(exposureStateIdentifier); expect(await cameraInfo.getExposureState(), equals(exposureState)); verify(mockApi.getExposureState(cameraInfoIdentifier)); }); test('getZoomState makes call to retrieve expected ZoomState', () async { final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); TestCameraInfoHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final CameraInfo cameraInfo = CameraInfo.detached( instanceManager: instanceManager, ); const int cameraInfoIdentifier = 2; final MockLiveZoomState mockLiveZoomState = MockLiveZoomState(); const int mockLiveZoomStateIdentifier = 55; instanceManager.addHostCreatedInstance( cameraInfo, cameraInfoIdentifier, onCopy: (_) => CameraInfo.detached(), ); instanceManager.addHostCreatedInstance( mockLiveZoomState, mockLiveZoomStateIdentifier, onCopy: (_) => MockLiveZoomState()); when(mockApi.getZoomState(cameraInfoIdentifier)) .thenReturn(mockLiveZoomStateIdentifier); expect(await cameraInfo.getZoomState(), equals(mockLiveZoomState)); verify(mockApi.getZoomState(cameraInfoIdentifier)); }); test('flutterApi create makes call to create expected instance type', () { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final CameraInfoFlutterApi flutterApi = CameraInfoFlutterApiImpl( instanceManager: instanceManager, ); flutterApi.create(0); expect( instanceManager.getInstanceWithWeakReference(0), isA<CameraInfo>()); }); }); }
packages/packages/camera/camera_android_camerax/test/camera_info_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/camera_info_test.dart", "repo_id": "packages", "token_count": 2393 }
925
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/fallback_strategy.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'fallback_strategy_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[TestFallbackStrategyHostApi, TestInstanceManagerHostApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('FallbackStrategy', () { tearDown(() { TestFallbackStrategyHostApi.setup(null); TestInstanceManagerHostApi.setup(null); }); test('detached constructor does not call create on the Java side', () async { final MockTestFallbackStrategyHostApi mockApi = MockTestFallbackStrategyHostApi(); TestFallbackStrategyHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); FallbackStrategy.detached( quality: VideoQuality.UHD, fallbackRule: VideoResolutionFallbackRule.higherQualityThan, instanceManager: instanceManager, ); verifyNever(mockApi.create( argThat(isA<int>()), argThat(isA<VideoQuality>()), argThat(isA<VideoResolutionFallbackRule>()), )); }); test('constructor calls create on the Java side', () { final MockTestFallbackStrategyHostApi mockApi = MockTestFallbackStrategyHostApi(); TestFallbackStrategyHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const VideoQuality quality = VideoQuality.HD; const VideoResolutionFallbackRule fallbackRule = VideoResolutionFallbackRule.lowerQualityThan; final FallbackStrategy instance = FallbackStrategy( quality: quality, fallbackRule: fallbackRule, instanceManager: instanceManager, ); verify(mockApi.create( instanceManager.getIdentifier(instance), quality, fallbackRule, )); }); }); }
packages/packages/camera/camera_android_camerax/test/fallback_strategy_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/fallback_strategy_test.dart", "repo_id": "packages", "token_count": 937 }
926
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/metering_point_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i6; import 'package:camera_android_camerax/src/camera_info.dart' as _i5; import 'package:camera_android_camerax/src/camera_state.dart' as _i7; import 'package:camera_android_camerax/src/exposure_state.dart' as _i3; import 'package:camera_android_camerax/src/live_data.dart' as _i2; import 'package:camera_android_camerax/src/zoom_state.dart' as _i8; 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 _FakeLiveData_0<T extends Object> extends _i1.SmartFake implements _i2.LiveData<T> { _FakeLiveData_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeExposureState_1 extends _i1.SmartFake implements _i3.ExposureState { _FakeExposureState_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// 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, ); } /// A class which mocks [TestMeteringPointHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestMeteringPointHostApi extends _i1.Mock implements _i4.TestMeteringPointHostApi { MockTestMeteringPointHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, double? x, double? y, double? size, int? cameraInfoId, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, x, y, size, cameraInfoId, ], ), returnValueForMissingStub: null, ); @override double getDefaultPointSize() => (super.noSuchMethod( Invocation.method( #getDefaultPointSize, [], ), returnValue: 0.0, ) as double); } /// A class which mocks [CameraInfo]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCameraInfo extends _i1.Mock implements _i5.CameraInfo { MockCameraInfo() { _i1.throwOnMissingStub(this); } @override _i6.Future<int> getSensorRotationDegrees() => (super.noSuchMethod( Invocation.method( #getSensorRotationDegrees, [], ), returnValue: _i6.Future<int>.value(0), ) as _i6.Future<int>); @override _i6.Future<_i2.LiveData<_i7.CameraState>> getCameraState() => (super.noSuchMethod( Invocation.method( #getCameraState, [], ), returnValue: _i6.Future<_i2.LiveData<_i7.CameraState>>.value( _FakeLiveData_0<_i7.CameraState>( this, Invocation.method( #getCameraState, [], ), )), ) as _i6.Future<_i2.LiveData<_i7.CameraState>>); @override _i6.Future<_i3.ExposureState> getExposureState() => (super.noSuchMethod( Invocation.method( #getExposureState, [], ), returnValue: _i6.Future<_i3.ExposureState>.value(_FakeExposureState_1( this, Invocation.method( #getExposureState, [], ), )), ) as _i6.Future<_i3.ExposureState>); @override _i6.Future<_i2.LiveData<_i8.ZoomState>> getZoomState() => (super.noSuchMethod( Invocation.method( #getZoomState, [], ), returnValue: _i6.Future<_i2.LiveData<_i8.ZoomState>>.value( _FakeLiveData_0<_i8.ZoomState>( this, Invocation.method( #getZoomState, [], ), )), ) as _i6.Future<_i2.LiveData<_i8.ZoomState>>); }
packages/packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart", "repo_id": "packages", "token_count": 2206 }
927
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/recording_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestRecordingHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestRecordingHostApi extends _i1.Mock implements _i2.TestRecordingHostApi { MockTestRecordingHostApi() { _i1.throwOnMissingStub(this); } @override void close(int? identifier) => super.noSuchMethod( Invocation.method( #close, [identifier], ), returnValueForMissingStub: null, ); @override void pause(int? identifier) => super.noSuchMethod( Invocation.method( #pause, [identifier], ), returnValueForMissingStub: null, ); @override void resume(int? identifier) => super.noSuchMethod( Invocation.method( #resume, [identifier], ), returnValueForMissingStub: null, ); @override void stop(int? identifier) => super.noSuchMethod( Invocation.method( #stop, [identifier], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/camera/camera_android_camerax/test/recording_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/recording_test.mocks.dart", "repo_id": "packages", "token_count": 950 }
928
name: camera_example description: Demonstrates how to use the camera plugin. publish_to: none environment: sdk: ^3.2.3 flutter: ">=3.16.6" dependencies: camera_avfoundation: # When depending on this package from a real application you should use: # camera_avfoundation: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ camera_platform_interface: ^2.7.0 flutter: sdk: flutter path_provider: ^2.0.0 video_player: ^2.7.0 dev_dependencies: build_runner: ^2.1.10 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/camera/camera_avfoundation/example/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera_avfoundation/example/pubspec.yaml", "repo_id": "packages", "token_count": 289 }
929
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.3.2+4 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 0.3.2+3 * Migrates to `dart:ui_web` APIs. * Updates minimum supported SDK version to Flutter 3.13.0/Dart 3.1.0. ## 0.3.2+2 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.3.2+1 * Updates README to improve example of `Image` creation. ## 0.3.2 * Changes `availableCameras` to not ask for the microphone permission. ## 0.3.1+4 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.3.1+3 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.3.1+2 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 0.3.1+1 * Updates code for stricter lint checks. ## 0.3.1 * Updates to latest camera platform interface, and fails if user attempts to use streaming with recording (since streaming is currently unsupported on web). ## 0.3.0+1 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). ## 0.3.0 * **BREAKING CHANGE**: Renames error code `cameraPermission` to `CameraAccessDenied` to be consistent with other platforms. ## 0.2.1+6 * Minor fixes for new analysis options. ## 0.2.1+5 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.2.1+4 * Migrates from `ui.hash*` to `Object.hash*`. * Updates minimum Flutter version for changes in 0.2.1+3. ## 0.2.1+3 * Internal code cleanup for stricter analysis options. ## 0.2.1+2 * Fixes cameraNotReadable error that prevented access to the camera on some Android devices when initializing a camera. * Implemented support for new Dart SDKs with an async requestFullscreen API. ## 0.2.1+1 * Update usage documentation. ## 0.2.1 * Add video recording functionality. * Fix cameraNotReadable error that prevented access to the camera on some Android devices. ## 0.2.0 * Initial release, adapted from the Flutter [I/O Photobooth](https://photobooth.flutter.dev/) project.
packages/packages/camera/camera_web/CHANGELOG.md/0
{ "file_path": "packages/packages/camera/camera_web/CHANGELOG.md", "repo_id": "packages", "token_count": 801 }
930
name: camera_web_integration_tests publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: camera_platform_interface: ^2.1.0 camera_web: path: ../ flutter: sdk: flutter dev_dependencies: async: ^2.5.0 cross_file: ^0.3.1 flutter_test: sdk: flutter integration_test: sdk: flutter mocktail: 0.3.0
packages/packages/camera/camera_web/example/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera_web/example/pubspec.yaml", "repo_id": "packages", "token_count": 164 }
931
name: camera_web description: A Flutter plugin for getting information about and controlling the camera on Web. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 version: 0.3.2+4 environment: sdk: ">=3.1.0 <4.0.0" flutter: ">=3.13.0" flutter: plugin: implements: camera platforms: web: pluginClass: CameraPlugin fileName: camera_web.dart dependencies: camera_platform_interface: ^2.3.1 flutter: sdk: flutter flutter_web_plugins: sdk: flutter stream_transform: ^2.0.0 dev_dependencies: flutter_test: sdk: flutter topics: - camera
packages/packages/camera/camera_web/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera_web/pubspec.yaml", "repo_id": "packages", "token_count": 302 }
932
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:web/web.dart'; /// Create anchor element with download attribute HTMLAnchorElement createAnchorElement(String href, String? suggestedName) => (document.createElement('a') as HTMLAnchorElement) ..href = href ..download = suggestedName ?? 'download'; /// Add an element to a container and click it void addElementToContainerAndClick(Element container, HTMLElement element) { // Add the element and click it // All previous elements will be removed before adding the new one container.appendChild(element); element.click(); } /// Initializes a DOM container where elements can be injected. Element ensureInitialized(String id) { Element? target = document.querySelector('#$id'); if (target == null) { final Element targetElement = document.createElement('flt-x-file')..id = id; document.body!.appendChild(targetElement); target = targetElement; } return target; } /// Determines if the browser is Safari from its vendor string. /// (This is the same check used in flutter/engine) bool isSafari() { return window.navigator.vendor == 'Apple Computer, Inc.'; }
packages/packages/cross_file/lib/src/web_helpers/web_helpers.dart/0
{ "file_path": "packages/packages/cross_file/lib/src/web_helpers/web_helpers.dart", "repo_id": "packages", "token_count": 364 }
933
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.0.1+1 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. * Aligns Dart and Flutter SDK constraints. * Updates minimum Flutter version to 3.0. ## 0.0.1 * Initial release
packages/packages/dynamic_layouts/CHANGELOG.md/0
{ "file_path": "packages/packages/dynamic_layouts/CHANGELOG.md", "repo_id": "packages", "token_count": 106 }
934
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'staggered_layout_example.dart'; import 'wrap_layout_example.dart'; void main() { runApp(const MyApp()); } /// Main example class MyApp extends StatelessWidget { /// Main example constructor. const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } /// The home page class MyHomePage extends StatelessWidget { /// The home page constructor. const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Demo App'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => Navigator.push( context, MaterialPageRoute<void>( builder: (BuildContext context) => const WrapExample(), ), ), child: const Text('Wrap Demo'), ), const SizedBox(height: 20), ElevatedButton( onPressed: () => Navigator.push( context, MaterialPageRoute<void>( builder: (BuildContext context) => const StaggeredExample(), ), ), child: const Text('Staggered Demo'), ), ], ), ), ); } }
packages/packages/dynamic_layouts/example/lib/main.dart/0
{ "file_path": "packages/packages/dynamic_layouts/example/lib/main.dart", "repo_id": "packages", "token_count": 800 }
935
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'render_dynamic_grid.dart'; import 'staggered_layout.dart'; import 'wrap_layout.dart'; /// A scrollable grid of widgets, capable of dynamically positioning tiles based /// on different aspects of the children's size when laid out with loose /// constraints. /// /// Three [SliverGridDelegate]s support wrapping or staggering the dynamically /// sized children of the grid. Staggering children can use /// [SliverGridDelegateWithFixedCrossAxisCount] or /// [SliverGridDelegateWithMaxCrossAxisExtent], while wrapping uses its own /// [SliverGridDelegateWithWrapping]. /// /// {@macro dynamicLayouts.garbageCollection} /// /// The following example shows how to use the [DynamicGridView.wrap] /// constructor. /// /// ```dart /// DynamicGridView.wrap( /// mainAxisSpacing: 10, /// crossAxisSpacing: 20, /// children: [ /// Container( /// height: 100, /// width: 200, /// color: Colors.amberAccent[100], /// child: const Center(child: Text('Item 1') /// ), /// ), /// Container( /// height: 50, /// width: 70, /// color: Colors.blue[100], /// child: const Center(child: Text('Item 2'), /// ), /// ), /// Container( /// height: 82, /// width: 300, /// color: Colors.pink[100], /// child: const Center(child: Text('Item 3'), /// ), /// ), /// Container( /// color: Colors.green[100], /// child: const Center(child: Text('Item 3'), /// ), /// ), /// ], /// ), /// ``` /// /// This sample code shows how to use the [DynamicGridView.staggered] /// constructor with a [maxCrossAxisExtent]: /// /// ```dart /// DynamicGridView.staggered( /// maxCrossAxisExtent: 100, /// crossAxisSpacing: 2, /// mainAxisSpacing: 2, /// children: List.generate( /// 50, /// (int index) => Container( /// height: index % 3 * 50 + 20, /// color: Colors.amber[index % 9 * 100], /// child: Center(child: Text("Index $index")), /// ), /// ), /// ); /// ``` class DynamicGridView extends GridView { /// Creates a scrollable, 2D array of widgets with a custom /// [SliverGridDelegate]. DynamicGridView({ super.key, super.scrollDirection, super.reverse, required super.gridDelegate, // This creates a SliverChildListDelegate in the super class. super.children = const <Widget>[], }); /// Creates a scrollable, 2D array of widgets that are created on demand. DynamicGridView.builder({ super.key, super.scrollDirection, super.reverse, required super.gridDelegate, // This creates a SliverChildBuilderDelegate in the super class. required super.itemBuilder, super.itemCount, }) : super.builder(); /// Creates a scrollable, 2D array of widgets with tiles where each tile can /// have its own size. /// /// Uses a [SliverGridDelegateWithWrapping] as the [gridDelegate]. /// /// The following example shows how to use the DynamicGridView.wrap constructor. /// /// ```dart /// DynamicGridView.wrap( /// mainAxisSpacing: 10, /// crossAxisSpacing: 20, /// children: [ /// Container( /// height: 100, /// width: 200, /// color: Colors.amberAccent[100], /// child: const Center(child: Text('Item 1') /// ), /// ), /// Container( /// height: 50, /// width: 70, /// color: Colors.blue[100], /// child: const Center(child: Text('Item 2'), /// ), /// ), /// Container( /// height: 82, /// width: 300, /// color: Colors.pink[100], /// child: const Center(child: Text('Item 3'), /// ), /// ), /// Container( /// color: Colors.green[100], /// child: const Center(child: Text('Item 3'), /// ), /// ), /// ], /// ), /// ``` /// /// See also: /// /// * [SliverGridDelegateWithWrapping] to see a more detailed explanation of /// how the wrapping works. DynamicGridView.wrap({ super.key, super.scrollDirection, super.reverse, double mainAxisSpacing = 0.0, double crossAxisSpacing = 0.0, double childCrossAxisExtent = double.infinity, double childMainAxisExtent = double.infinity, super.children = const <Widget>[], }) : super( gridDelegate: SliverGridDelegateWithWrapping( mainAxisSpacing: mainAxisSpacing, crossAxisSpacing: crossAxisSpacing, childCrossAxisExtent: childCrossAxisExtent, childMainAxisExtent: childMainAxisExtent, ), ); /// Creates a scrollable, 2D array of widgets where each tile's main axis /// extent will be determined by the child's corresponding finite size and /// the cross axis extent will be fixed, generating a staggered layout. /// /// Either a [crossAxisCount] or a [maxCrossAxisExtent] must be provided. /// The constructor will then use a /// [DynamicSliverGridDelegateWithFixedCrossAxisCount] or a /// [DynamicSliverGridDelegateWithMaxCrossAxisExtent] as its [gridDelegate], /// respectively. /// /// This sample code shows how to use the constructor with a /// [maxCrossAxisExtent] and a simple layout: /// /// ```dart /// DynamicGridView.staggered( /// maxCrossAxisExtent: 100, /// crossAxisSpacing: 2, /// mainAxisSpacing: 2, /// children: List.generate( /// 50, /// (int index) => Container( /// height: index % 3 * 50 + 20, /// color: Colors.amber[index % 9 * 100], /// child: Center(child: Text("Index $index")), /// ), /// ), /// ); /// ``` DynamicGridView.staggered({ super.key, super.scrollDirection, super.reverse, int? crossAxisCount, double? maxCrossAxisExtent, double mainAxisSpacing = 0.0, double crossAxisSpacing = 0.0, super.children = const <Widget>[], }) : assert(crossAxisCount != null || maxCrossAxisExtent != null), assert(crossAxisCount == null || maxCrossAxisExtent == null), super( gridDelegate: crossAxisCount != null ? DynamicSliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: crossAxisCount, mainAxisSpacing: mainAxisSpacing, crossAxisSpacing: crossAxisSpacing, ) : DynamicSliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: maxCrossAxisExtent!, mainAxisSpacing: mainAxisSpacing, crossAxisSpacing: crossAxisSpacing, ), ); @override Widget buildChildLayout(BuildContext context) { return DynamicSliverGrid( delegate: childrenDelegate, gridDelegate: gridDelegate, ); } } /// A sliver that places multiple box children in a two dimensional arrangement. class DynamicSliverGrid extends SliverMultiBoxAdaptorWidget { /// Creates a sliver that places multiple box children in a two dimensional /// arrangement. const DynamicSliverGrid({ super.key, required super.delegate, required this.gridDelegate, }); /// The delegate that manages the size and position of the children. final SliverGridDelegate gridDelegate; @override RenderDynamicSliverGrid createRenderObject(BuildContext context) { final SliverMultiBoxAdaptorElement element = context as SliverMultiBoxAdaptorElement; return RenderDynamicSliverGrid( childManager: element, gridDelegate: gridDelegate); } @override void updateRenderObject( BuildContext context, RenderDynamicSliverGrid renderObject, ) { renderObject.gridDelegate = gridDelegate; } }
packages/packages/dynamic_layouts/lib/src/dynamic_grid.dart/0
{ "file_path": "packages/packages/dynamic_layouts/lib/src/dynamic_grid.dart", "repo_id": "packages", "token_count": 3148 }
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. package androidx.test.espresso.flutter.api; import android.view.View; import androidx.test.espresso.UiController; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Represents a Flutter widget action. * * <p>This interface is part of Espresso-Flutter testing framework. Users should usually expect no * return value for an action and use the {@code WidgetAction} for customizing an action on a * Flutter widget. * * @param <R> The type of the action result. */ public interface FlutterAction<R> { /** Performs an action on the given Flutter widget and gets its return value. */ Future<R> perform( @Nullable WidgetMatcher targetWidget, @Nonnull View flutterView, @Nonnull FlutterTestingProtocol flutterTestingProtocol, @Nonnull UiController androidUiController); }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/FlutterAction.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/FlutterAction.java", "repo_id": "packages", "token_count": 308 }
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. package androidx.test.espresso.flutter.internal.jsonrpc; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import static com.google.common.util.concurrent.Futures.immediateFuture; import android.util.Log; import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcRequest; import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcResponse; import com.google.common.collect.Maps; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import java.net.ConnectException; import java.net.URI; import java.util.concurrent.ConcurrentMap; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; /** * A client that can be used to talk to a WebSocket-based JSON-RPC server. * * <p>One {@code JsonRpcClient} instance is not supposed to be shared between multiple threads. * Always create a new instance of {@code JsonRpcClient} for connecting to a new JSON-RPC URI, but * try to reuse the {@link OkHttpClient} instance, which is thread-safe and maintains a thread pool * in handling requests and responses. */ public class JsonRpcClient { private static final String TAG = JsonRpcClient.class.getSimpleName(); private static final int NORMAL_CLOSURE_STATUS = 1000; private final URI webSocketUri; private final ConcurrentMap<String, SettableFuture<JsonRpcResponse>> responseFutures; private WebSocket webSocketConn; /** {@code client} can be shared between multiple {@code JsonRpcClient}s. */ public JsonRpcClient(OkHttpClient client, URI webSocketUri) { this.webSocketUri = checkNotNull(webSocketUri, "WebSocket URL can't be null."); responseFutures = Maps.newConcurrentMap(); connect(checkNotNull(client, "OkHttpClient can't be null."), webSocketUri); } private void connect(OkHttpClient client, URI webSocketUri) { Request request = new Request.Builder().url(webSocketUri.toString()).build(); WebSocketListener webSocketListener = new WebSocketListenerImpl(); webSocketConn = client.newWebSocket(request, webSocketListener); } /** Closes the web socket connection. Non-blocking, and will return immediately. */ public void disconnect() { if (webSocketConn != null) { webSocketConn.close(NORMAL_CLOSURE_STATUS, "Client request closing. All requests handled."); } } /** * Sends a JSON-RPC request and returns a {@link ListenableFuture} with which the client could * wait on response. If the {@code request} is a JSON-RPC notification, this method returns * immediately with a {@code null} response. * * @param request the JSON-RPC request to be sent. * @return a {@code ListenableFuture} representing pending completion of the request, or yields an * {@code ExecutionException}, which wraps a {@code ConnectException} if failed to send the * request. */ public ListenableFuture<JsonRpcResponse> request(JsonRpcRequest request) { checkNotNull(request, "JSON-RPC request shouldn't be null."); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d( TAG, String.format("JSON-RPC Request sent to uri %s: %s.", webSocketUri, request.toJson())); } if (webSocketConn == null) { ConnectException e = new ConnectException("WebSocket connection was not initiated correctly."); return immediateFailedFuture(e); } synchronized (responseFutures) { // Holding the lock of responseFutures for send-and-add operations, so that we could make sure // to add its ListenableFuture to the responseFutures map before the thread of // {@code WebSocketListenerImpl#onMessage} method queries the map. boolean succeeded = webSocketConn.send(request.toJson()); if (!succeeded) { ConnectException e = new ConnectException("Failed to send request: " + request); return immediateFailedFuture(e); } if (isNullOrEmpty(request.getId())) { // Request id is null or empty. This is a notification request, so returns immediately. return immediateFuture(null); } else { SettableFuture<JsonRpcResponse> responseFuture = SettableFuture.create(); responseFutures.put(request.getId(), responseFuture); return responseFuture; } } } /** A callback listener that handles incoming web socket messages. */ private class WebSocketListenerImpl extends WebSocketListener { @Override public void onMessage(WebSocket webSocket, String response) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, String.format("JSON-RPC response received: %s.", response)); } JsonRpcResponse responseObj = JsonRpcResponse.fromJson(response); synchronized (responseFutures) { if (isNullOrEmpty(responseObj.getId()) || !responseFutures.containsKey(responseObj.getId())) { Log.w( TAG, String.format( "Received a message with empty or unknown ID: %s. Drop the message.", responseObj.getId())); return; } SettableFuture<JsonRpcResponse> responseFuture = responseFutures.remove(responseObj.getId()); responseFuture.set(responseObj); } } @Override public void onClosing(WebSocket webSocket, int code, String reason) { Log.d( TAG, String.format( "Server requested connection close with code %d, reason: %s", code, reason)); webSocket.close(NORMAL_CLOSURE_STATUS, "Server requested closing connection."); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { Log.w(TAG, String.format("Failed to deliver message with error: %s.", t.getMessage())); throw new RuntimeException("WebSocket request failure.", t); } } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java", "repo_id": "packages", "token_count": 2122 }
938
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.internal.protocol.impl; import static com.google.common.base.Preconditions.checkNotNull; import androidx.test.espresso.flutter.api.SyntheticAction; import com.google.gson.Gson; import com.google.gson.annotations.Expose; /** * Represents an action that waits until the specified conditions have been met in the Flutter app. */ final class WaitForConditionAction extends SyntheticAction { private static final Gson gson = new Gson(); @Expose private final String conditionName = "CombinedCondition"; @Expose private final String conditions; /** * Creates with the given wait conditions. * * @param waitConditions the conditions that this action shall wait for. Cannot be null. */ public WaitForConditionAction(WaitCondition... waitConditions) { super("waitForCondition"); conditions = gson.toJson(checkNotNull(waitConditions)); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WaitForConditionAction.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WaitForConditionAction.java", "repo_id": "packages", "token_count": 305 }
939
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/file_selector/file_selector/example/android/gradle.properties/0
{ "file_path": "packages/packages/file_selector/file_selector/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
940
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector/file_selector.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; /// Screen that shows an example of openFile class OpenTextPage extends StatelessWidget { /// Default Constructor const OpenTextPage({super.key}); Future<void> _openTextFile(BuildContext context) async { const XTypeGroup typeGroup = XTypeGroup( label: 'text', extensions: <String>['txt', 'json'], ); // This demonstrates using an initial directory for the prompt, which should // only be done in cases where the application can likely predict where the // file would be. In most cases, this parameter should not be provided. final String? initialDirectory = kIsWeb ? null : (await getApplicationDocumentsDirectory()).path; final XFile? file = await openFile( acceptedTypeGroups: <XTypeGroup>[typeGroup], initialDirectory: initialDirectory, ); if (file == null) { // Operation was canceled by the user. return; } final String fileName = file.name; final String fileContent = await file.readAsString(); if (context.mounted) { await showDialog<void>( context: context, builder: (BuildContext context) => TextDisplay(fileName, fileContent), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Open a text file'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, ), child: const Text('Press to open a text file (json, txt)'), onPressed: () => _openTextFile(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog class TextDisplay extends StatelessWidget { /// Default Constructor const TextDisplay(this.fileName, this.fileContent, {super.key}); /// File's name final String fileName; /// File to display final String fileContent; @override Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), content: Scrollbar( child: SingleChildScrollView( child: Text(fileContent), ), ), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () => Navigator.pop(context), ), ], ); } }
packages/packages/file_selector/file_selector/example/lib/open_text_page.dart/0
{ "file_path": "packages/packages/file_selector/file_selector/example/lib/open_text_page.dart", "repo_id": "packages", "token_count": 1081 }
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 'dart:typed_data'; import 'package:file_selector_android/src/file_selector_android.dart'; import 'package:file_selector_android/src/file_selector_api.g.dart'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'file_selector_android_test.mocks.dart'; @GenerateMocks(<Type>[FileSelectorApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); late FileSelectorAndroid plugin; late MockFileSelectorApi mockApi; setUp(() { mockApi = MockFileSelectorApi(); plugin = FileSelectorAndroid(api: mockApi); }); test('registered instance', () { FileSelectorAndroid.registerWith(); expect(FileSelectorPlatform.instance, isA<FileSelectorAndroid>()); }); group('openFile', () { test('passes the accepted type groups correctly', () async { when( mockApi.openFile( 'some/path/', argThat( isA<FileTypes>().having( (FileTypes types) => types.mimeTypes, 'mimeTypes', <String>['text/plain', 'image/jpg'], ).having( (FileTypes types) => types.extensions, 'extensions', <String>['txt', 'jpg'], ), ), ), ).thenAnswer( (_) => Future<FileResponse?>.value( FileResponse( path: 'some/path.txt', size: 30, bytes: Uint8List(0), name: 'name', mimeType: 'text/plain', ), ), ); const XTypeGroup group = XTypeGroup( extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup group2 = XTypeGroup( extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); final XFile? file = await plugin.openFile( acceptedTypeGroups: <XTypeGroup>[group, group2], initialDirectory: 'some/path/', ); expect(file?.path, 'some/path.txt'); expect(file?.mimeType, 'text/plain'); expect(await file?.length(), 30); expect(await file?.readAsBytes(), Uint8List(0)); }); }); group('openFiles', () { test('passes the accepted type groups correctly', () async { when( mockApi.openFiles( 'some/path/', argThat( isA<FileTypes>().having( (FileTypes types) => types.mimeTypes, 'mimeTypes', <String>['text/plain', 'image/jpg'], ).having( (FileTypes types) => types.extensions, 'extensions', <String>['txt', 'jpg'], ), ), ), ).thenAnswer( (_) => Future<List<FileResponse>>.value( <FileResponse>[ FileResponse( path: 'some/path.txt', size: 30, bytes: Uint8List(0), name: 'name', mimeType: 'text/plain', ), FileResponse( path: 'other/dir.jpg', size: 40, bytes: Uint8List(0), mimeType: 'image/jpg', ), ], ), ); const XTypeGroup group = XTypeGroup( extensions: <String>['txt'], mimeTypes: <String>['text/plain'], ); const XTypeGroup group2 = XTypeGroup( extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], ); final List<XFile> files = await plugin.openFiles( acceptedTypeGroups: <XTypeGroup>[group, group2], initialDirectory: 'some/path/', ); expect(files[0].path, 'some/path.txt'); expect(files[0].mimeType, 'text/plain'); expect(await files[0].length(), 30); expect(await files[0].readAsBytes(), Uint8List(0)); expect(files[1].path, 'other/dir.jpg'); expect(files[1].mimeType, 'image/jpg'); expect(await files[1].length(), 40); expect(await files[1].readAsBytes(), Uint8List(0)); }); }); test('getDirectoryPath', () async { when(mockApi.getDirectoryPath('some/path')) .thenAnswer((_) => Future<String?>.value('some/path/chosen/')); final String? path = await plugin.getDirectoryPath( initialDirectory: 'some/path', ); expect(path, 'some/path/chosen/'); }); }
packages/packages/file_selector/file_selector_android/test/file_selector_android_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_android/test/file_selector_android_test.dart", "repo_id": "packages", "token_count": 2169 }
942
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.9.2+1 * 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.2 * Adds `getSaveLocation` and deprecates `getSavePath`. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.9.1+3 * Sets a cmake_policy compatibility version to fix build warnings. ## 0.9.1+2 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.9.1+1 * 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.1 * Adds `getDirectoryPaths` implementation. ## 0.9.0+1 * Changes XTypeGroup initialization from final to const. * Updates minimum Flutter version to 2.10. ## 0.9.0 * Moves source to flutter/plugins. ## 0.0.3 * Adds Dart implementation for in-package method channel. ## 0.0.2+1 * Updates README ## 0.0.2 * Updates SDK constraint to signal compatibility with null safety. ## 0.0.1 * Initial Linux implementation of `file_selector`.
packages/packages/file_selector/file_selector_linux/CHANGELOG.md/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/CHANGELOG.md", "repo_id": "packages", "token_count": 409 }
943
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../../file_selector_platform_interface.dart'; import '../method_channel/method_channel_file_selector.dart'; /// The interface that implementations of file_selector must implement. /// /// Platform implementations should extend this class rather than implement it as `file_selector` /// does not consider newly added methods to be breaking changes. Extending this class /// (using `extends`) ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by newly added /// [FileSelectorPlatform] methods. abstract class FileSelectorPlatform extends PlatformInterface { /// Constructs a FileSelectorPlatform. FileSelectorPlatform() : super(token: _token); static final Object _token = Object(); static FileSelectorPlatform _instance = MethodChannelFileSelector(); /// The default instance of [FileSelectorPlatform] to use. /// /// Defaults to [MethodChannelFileSelector]. static FileSelectorPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [FileSelectorPlatform] when they register themselves. static set instance(FileSelectorPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// Opens a file dialog for loading files and returns a file path. /// /// Returns `null` if the user cancels the operation. // TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to // duplicate this to add a parameter. Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) { throw UnimplementedError('openFile() has not been implemented.'); } /// Opens a file dialog for loading files and returns a list of file paths. /// /// Returns an empty list if the user cancels the operation. // TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to // duplicate this to add a parameter. Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) { throw UnimplementedError('openFiles() has not been implemented.'); } /// Opens a file dialog for saving files and returns a file path at which to /// save. /// /// Returns `null` if the user cancels the operation. // TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to // duplicate this to add a parameter. @Deprecated('Use getSaveLocation instead') Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) { throw UnimplementedError('getSavePath() has not been implemented.'); } /// Opens a file dialog for saving files and returns a file location at which /// to save. /// /// Returns `null` if the user cancels the operation. Future<FileSaveLocation?> getSaveLocation({ List<XTypeGroup>? acceptedTypeGroups, SaveDialogOptions options = const SaveDialogOptions(), }) async { final String? path = await getSavePath( acceptedTypeGroups: acceptedTypeGroups, initialDirectory: options.initialDirectory, suggestedName: options.suggestedName, confirmButtonText: options.confirmButtonText, ); return path == null ? null : FileSaveLocation(path); } /// Opens a file dialog for loading directories and returns a directory path. /// /// Returns `null` if the user cancels the operation. // TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to // duplicate this to add a parameter. Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) { throw UnimplementedError('getDirectoryPath() has not been implemented.'); } /// Opens a file dialog for loading directories and returns multiple directory /// paths. /// /// Returns an empty list if the user cancels the operation. // TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to // duplicate this to add a parameter. Future<List<String>> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, }) { throw UnimplementedError('getDirectoryPaths() has not been implemented.'); } }
packages/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart", "repo_id": "packages", "token_count": 1279 }
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 'dart:typed_data'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_web/file_selector_web.dart'; import 'package:file_selector_web/src/dom_helper.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:web/web.dart'; void main() { group('FileSelectorWeb', () { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('openFile', () { testWidgets('works', (WidgetTester _) async { final XFile mockFile = createXFile('1001', 'identity.png'); final MockDomHelper mockDomHelper = MockDomHelper( files: <XFile>[mockFile], expectAccept: '.jpg,.jpeg,image/png,image/*'); final FileSelectorWeb plugin = FileSelectorWeb(domHelper: mockDomHelper); const XTypeGroup typeGroup = XTypeGroup( label: 'images', extensions: <String>['jpg', 'jpeg'], mimeTypes: <String>['image/png'], webWildCards: <String>['image/*'], ); final XFile? file = await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); expect(file, isNotNull); expect(file!.name, mockFile.name); expect(await file.length(), 4); expect(await file.readAsString(), '1001'); expect(await file.lastModified(), isNotNull); }); testWidgets('returns null when getFiles returns an empty list', (WidgetTester _) async { // Simulate returning an empty list of files from the DomHelper... final MockDomHelper mockDomHelper = MockDomHelper( files: <XFile>[], ); final FileSelectorWeb plugin = FileSelectorWeb(domHelper: mockDomHelper); final XFile? file = await plugin.openFile(); expect(file, isNull); }); }); group('openFiles', () { testWidgets('works', (WidgetTester _) async { final XFile mockFile1 = createXFile('123456', 'file1.txt'); final XFile mockFile2 = createXFile('', 'file2.txt'); final MockDomHelper mockDomHelper = MockDomHelper( files: <XFile>[mockFile1, mockFile2], expectAccept: '.txt', expectMultiple: true); final FileSelectorWeb plugin = FileSelectorWeb(domHelper: mockDomHelper); const XTypeGroup typeGroup = XTypeGroup( label: 'files', extensions: <String>['.txt'], ); final List<XFile> files = await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]); expect(files.length, 2); expect(files[0].name, mockFile1.name); expect(await files[0].length(), 6); expect(await files[0].readAsString(), '123456'); expect(await files[0].lastModified(), isNotNull); expect(files[1].name, mockFile2.name); expect(await files[1].length(), 0); expect(await files[1].readAsString(), ''); expect(await files[1].lastModified(), isNotNull); }); }); group('getSavePath', () { testWidgets('returns non-null', (WidgetTester _) async { final FileSelectorWeb plugin = FileSelectorWeb(); final Future<String?> savePath = plugin.getSavePath(); expect(await savePath, isNotNull); }); }); }); } class MockDomHelper implements DomHelper { MockDomHelper({ List<XFile> files = const <XFile>[], String expectAccept = '', bool expectMultiple = false, }) : _files = files, _expectedAccept = expectAccept, _expectedMultiple = expectMultiple; final List<XFile> _files; final String _expectedAccept; final bool _expectedMultiple; @override Future<List<XFile>> getFiles({ String accept = '', bool multiple = false, HTMLInputElement? input, }) { expect(accept, _expectedAccept, reason: 'Expected "accept" value does not match.'); expect(multiple, _expectedMultiple, reason: 'Expected "multiple" value does not match.'); return Future<List<XFile>>.value(_files); } } XFile createXFile(String content, String name) { final Uint8List data = Uint8List.fromList(content.codeUnits); return XFile.fromData(data, name: name, lastModified: DateTime.now()); }
packages/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart", "repo_id": "packages", "token_count": 1791 }
945
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', cppOptions: CppOptions(namespace: 'file_selector_windows'), cppHeaderOut: 'windows/messages.g.h', cppSourceOut: 'windows/messages.g.cpp', copyrightHeader: 'pigeons/copyright.txt', )) class TypeGroup { TypeGroup(this.label, {required this.extensions}); String label; // TODO(stuartmorgan): Make the generic type non-nullable once supported. // https://github.com/flutter/flutter/issues/97848 // The C++ code treats all of it as non-nullable. List<String?> extensions; } class SelectionOptions { SelectionOptions({ this.allowMultiple = false, this.selectFolders = false, this.allowedTypes = const <TypeGroup?>[], }); bool allowMultiple; bool selectFolders; // TODO(stuartmorgan): Make the generic type non-nullable once supported. // https://github.com/flutter/flutter/issues/97848 // The C++ code treats the values as non-nullable. List<TypeGroup?> allowedTypes; } /// The result from an open or save dialog. class FileDialogResult { FileDialogResult({required this.paths, this.typeGroupIndex}); /// The selected paths. /// /// Empty if the dialog was canceled. // TODO(stuartmorgan): Make the generic type non-nullable once supported. // https://github.com/flutter/flutter/issues/97848 // The Dart code treats the values as non-nullable. List<String?> paths; /// The type group index (into the list provided in [SelectionOptions]) of /// the group that was selected when the dialog was confirmed. /// /// Null if no type groups were provided, or the dialog was canceled. int? typeGroupIndex; } @HostApi(dartHostTestHandler: 'TestFileSelectorApi') abstract class FileSelectorApi { FileDialogResult showOpenDialog( SelectionOptions options, String? initialDirectory, String? confirmButtonText, ); FileDialogResult showSaveDialog( SelectionOptions options, String? initialDirectory, String? suggestedName, String? confirmButtonText, ); }
packages/packages/file_selector/file_selector_windows/pigeons/messages.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/pigeons/messages.dart", "repo_id": "packages", "token_count": 717 }
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. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_ #include <shobjidl.h> #include <string> namespace file_selector_windows { // Converts the given UTF-16 string to UTF-8. std::string Utf8FromUtf16(std::wstring_view utf16_string); // Converts the given UTF-8 string to UTF-16. std::wstring Utf16FromUtf8(std::string_view utf8_string); } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_
packages/packages/file_selector/file_selector_windows/windows/string_utils.h/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/windows/string_utils.h", "repo_id": "packages", "token_count": 252 }
947
# Examples There are several examples listed in this directory: You can run the following commands in the example directory to see the appropriate demos: `flutter run` to see a more fully fledged functional usage of the AdaptiveLayout suite and some AdaptiveScaffold static methods. `flutter run lib/adaptive_layout_demo.dart` to see a simple usage of AdaptiveLayout. `flutter run lib/adaptive_scaffold_demo.dart` to see a simple usage of AdaptiveScaffold.
packages/packages/flutter_adaptive_scaffold/example/README.md/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/README.md", "repo_id": "packages", "token_count": 124 }
948
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/flutter_adaptive_scaffold/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
949
# Image utilities for Flutter ## NetworkImageWithRetry Use `NetworkImageWithRetry` instead of `Image.network` to load images from the network with a retry mechanism. Example: <?code-excerpt "example/lib/readme_excerpts.dart (NetworkImageWithRetry)"?> ```dart const Image avatar = Image( image: NetworkImageWithRetry('http://example.com/avatars/123.jpg'), ); ``` The retry mechanism may be customized by supplying a custom `FetchStrategy` function. `FetchStrategyBuilder` is a utility class that helps building fetch strategy functions. ## Features and bugs Please file feature requests and bugs at https://github.com/flutter/flutter/issues.
packages/packages/flutter_image/README.md/0
{ "file_path": "packages/packages/flutter_image/README.md", "repo_id": "packages", "token_count": 190 }
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/widgets.dart'; import 'package:flutter_image/flutter_image.dart'; /// Demonstrates loading an image for the README. Image networkImageWithRetry() { // #docregion NetworkImageWithRetry const Image avatar = Image( image: NetworkImageWithRetry('http://example.com/avatars/123.jpg'), ); // #enddocregion NetworkImageWithRetry return avatar; }
packages/packages/flutter_image/example/lib/readme_excerpts.dart/0
{ "file_path": "packages/packages/flutter_image/example/lib/readme_excerpts.dart", "repo_id": "packages", "token_count": 161 }
951
## 0.6.22 * Introduces a new `MarkdownElementBuilder.isBlockElement()` method to specify if custom element is a block. ## 0.6.21+1 * Adds `onSelectionChanged` to the constructors of `Markdown` and `MarkdownBody`. ## 0.6.21 * Fixes support for `WidgetSpan` in `Text.rich` elements inside `MarkdownElementBuilder`. ## 0.6.20+1 * Updates minimum supported SDK version to Flutter 3.19. ## 0.6.20 * Adds `textScaler` to `MarkdownStyleSheet`, and deprecates `textScaleFactor`. * Clients using `textScaleFactor: someFactor` should replace it with `TextScaler.linear(someFactor)` to preserve behavior. * Removes use of deprecated Flutter framework `textScaleFactor` methods. * Updates minimum supported SDK version to Flutter 3.16. ## 0.6.19 * Replaces `RichText` with `Text.rich` so the widget can work with `SelectionArea` when `selectable` is set to false. ## 0.6.18+3 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes lint warnings. ## 0.6.18+2 * Removes leading whitespace from list items. ## 0.6.18+1 * Fixes a typo in README. ## 0.6.18 * Adds support for `footnote`. ## 0.6.17+4 * Fixes an issue where a code block would overlap its container decoration. ## 0.6.17+3 * Fixes an incorrect note about SDK versions in the 0.6.17+2 CHANGELOG.md entry. ## 0.6.17+2 * Adds pub topics to package metadata. ## 0.6.17+1 * Deletes deprecated splash screen meta-data element. * Updates README to improve examples of using Markdown. ## 0.6.17 * Introduces a new `MarkdownElementBuilder.visitElementAfterWithContext()` method passing the widget `BuildContext` and the parent text's `TextStyle`. ## 0.6.16 * Adds `tableVerticalAlignment` property to allow aligning table cells vertically. ## 0.6.15+1 * Fixes 'The Scrollbar's ScrollController has no ScrollPosition attached' exception when scrolling scrollable code blocks. * Fixes stale ignore: prefer_const_constructors. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.6.15 * Fixes unawaited_futures violations. * Updates minimum Flutter version to 3.3. * Aligns Dart and Flutter SDK constraints. * Replace `describeEnum` with the `name` getter. * Supports custom rendering of tags without children. ## 0.6.14 * Require `markdown: ^7.0.0` ## 0.6.13+1 * Adjusts code to account for nullability change in Flutter SDK. * Updates the example to specify the import for `DropdownMenu`. ## 0.6.13 * Support changes in the latest `package:markdown`. ## 0.6.12 * Markdown Lists now take into account `fitContent` instead of always expanding to the maximum horizontally ([flutter/flutter#108976](https://github.com/flutter/flutter/issues/108976)). ## 0.6.11 * Deprecates and removes use of `TaskListSyntax` as new markdown package supports checkboxes natively. Consider using `OrderedListWithCheckBoxSyntax` or `UnorderedListWithCheckBoxSyntax` as a replacement. * Changes `_buildCheckbox()` to inspect state of checkbox input element by existence of `'checked'` attribute. ## 0.6.10+6 * Removes print logged when not handling hr for alignment. * Removes print logged when not handling li for alignment. ## 0.6.10+5 * Fixes lint warnings. ## 0.6.10+4 * Updates text theme parameters to avoid deprecation issues. ## 0.6.10+3 * Fixes shrinkWrap not taken into account with single child ([flutter/flutter#105299](https://github.com/flutter/flutter/issues/105299)). ## 0.6.10+2 * Migrates from `ui.hash*` to `Object.hash*`. ## 0.6.10+1 * Updates Linux example to remove unneeded library dependencies that could cause build failures. * Updates for non-nullable bindings. ## 0.6.10 * Update `markdown` dependency ## 0.6.9+1 * Remove build status badge from `README.md` ## 0.6.9 * Leading spaces in a paragraph and in list items are now ignored according to [GFM #192](https://github.github.com/gfm/#example-192) and [GFM #236](https://github.github.com/gfm/#example-236). ## 0.6.8 * Added option paddingBuilders ## 0.6.7 * Fix `unnecessary_import` lint errors. * Added option pPadding * Added options h1Padding - h6Padding ## 0.6.6 * Soft line break ## 0.6.5 * Fix unique Keys for RichText blocks ## 0.6.4 * Fix merging of spans when first span is not a TextSpan ## 0.6.3 * Fixed `onTap`, now the changed hyperlinks are reflected even with keeping the same link name unchanged. ## 0.6.2 * Updated metadata for new source location * Style changes to conform to flutter/packages analyzer settings ## 0.6.1 * Added builder option bulletBuilder ## 0.6.0 * Null safety release * Added stylesheet option listBulletPadding * Fixed blockquote inline styling * Added onTapText handler for selectable text ## 0.6.0-nullsafety.2 * Dependencies updated for null safety ## 0.6.0-nullsafety.1 * Fix null safety on web * Image test mocks fixed for null safety ## 0.6.0-nullsafety.0 * Initial null safety migration. ## 0.5.2 * Added `MarkdownListItemCrossAxisAlignment` to allow for intrinsic height measurements of lists. ## 0.5.1 * Fix user defined builders ## 0.5.0 * BREAKING CHANGE: `MarkdownTapLinkCallback` now has three parameters, not one, exposing more information about a tapped link. * Note for upgraders, the old single parameter `href` is now the second parameter to match the specification. * Android example upgraded * Test coverage updated to match GitHub Flavoured Markdown and CommonMark * Handle links with empty descriptions * Handle empty rows in tables ## 0.4.4 * Fix handling of newline character in blockquote * Add new example demo * Use the start attribute in ordered list to set the first number * Revert changes made in PR #235 (which broke newline handling) ## 0.4.3 * Fix merging of `MarkdownStyleSheets` * Fix `MarkdownStyleSheet` textScaleFactor to use default value of 1.0, if not provided, instead using the textScaleFactor of the nearest MediaQuery ## 0.4.2 * Fix parsing of image caption & alt attributes * Fix baseline alignment in lists * Support `LineBreakSyntax` ## 0.4.1 * Downgrade Flutter minimum from 1.17.1 to 1.17.0 for Pub ## 0.4.0 * Updated for Flutter 1.17 * Ignore newlines in paragraphs * Improve handling of horizontal rules ## 0.3.5 * Fix hardcoded colors and improve Darktheme * Fix text alignment when formatting is involved ## 0.3.4 * Add support for text paragraphs and blockquotes. ## 0.3.3 * Add the ability to control the scroll position of the `MarkdownWidget`. ## 0.3.2 * Uplift `package:markdown` dependency version to enable deleting HTML unescape URI workaround * Explictly state that Flutter 1.10.7 is the minimum supported Flutter version in the library `pubspec.yaml`. ## 0.3.1 * Expose `tableColumnWidth` * Add `MarkdownStyleSheet.fromCupertinoTheme` * Fix `MarkdownStyleSheet.blockquote` * Flutter for web support * Add physic and shrinkWrap to Markdown widget * Add MarkdownBody.fitContent * Support select text to copy * Fix list bullet alignment * HTML unescape URIs (temporary workaround for [dart-lang/markdown #272](https://github.com/dart-lang/markdown/issues/272)) * Rebuilt `example/android` and `example/ios` directories **Note:** this version has an implicit minimum supported version of Flutter 1.10.7. See [flutter/flutter_markdown issue #156](https://github.com/flutter/flutter_markdown/issues/156) for more detail. ## 0.3.0 * Support GitHub flavoured Markdown * Support strikethrough * Convert TextSpan to use new InlineSpan API ## 0.2.0 * Updated environment sdk constraints to make the package Dart 2 compatible. As a result, usage of this version and higher requires a Dart 2 SDK. ## 0.1.6 * Updated `markdown` dependency. ## 0.1.5 * Add `mockito` as a dev dependency. Eliminate use of `package:http`, which is no longer part of Flutter. ## 0.1.4 * Add `li` style to bullets ## 0.1.3 * Add `path` and `http` as declared dependencies in `pubspec.yaml` ## 0.1.2 * Add support for horizontal rules. * Fix the `onTap` callback on images nested in hyperlinks ## 0.1.1 * Add support for local file paths in image links. Make sure to set the `imageDirectory` property to specify the base directory containing the image files. ## 0.1.0 * Roll the dependency on `markdown` to 1.0.0 * Add a test and example for image links * Fix the `onTap` callback on hyperlinks ## 0.0.9 * First published version
packages/packages/flutter_markdown/CHANGELOG.md/0
{ "file_path": "packages/packages/flutter_markdown/CHANGELOG.md", "repo_id": "packages", "token_count": 2569 }
952
#include "Generated.xcconfig"
packages/packages/flutter_markdown/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/flutter_markdown/example/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
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'; // ignore_for_file: public_member_api_docs class DropdownMenu<T> extends StatelessWidget { DropdownMenu({ super.key, required this.items, required this.initialValue, required this.label, this.labelStyle, Color? background, EdgeInsetsGeometry? padding, Color? menuItemBackground, EdgeInsetsGeometry? menuItemMargin, this.onChanged, }) : assert( items.isNotEmpty, 'The items map must contain at least one entry'), background = background ?? Colors.black12, padding = padding ?? const EdgeInsets.symmetric(horizontal: 12, vertical: 8), menuItemBackground = menuItemBackground ?? Colors.white, menuItemMargin = menuItemMargin ?? const EdgeInsets.only(left: 4); final Map<String, T> items; final T initialValue; final String label; final TextStyle? labelStyle; final ValueChanged<T?>? onChanged; final Color background; final EdgeInsetsGeometry padding; final Color menuItemBackground; final EdgeInsetsGeometry menuItemMargin; @override Widget build(BuildContext context) { return Container( color: background, padding: padding, child: Row( children: <Widget>[ Text( label, style: labelStyle ?? Theme.of(context).textTheme.titleMedium, ), Container( color: menuItemBackground, margin: menuItemMargin, child: DropdownButton<T>( isDense: true, value: initialValue, items: <DropdownMenuItem<T>>[ for (final String item in items.keys) DropdownMenuItem<T>( value: items[item], child: Container( padding: const EdgeInsets.only(left: 4), child: Text(item), ), ), ], onChanged: (T? value) => onChanged!(value), ), ), ], ), ); } }
packages/packages/flutter_markdown/example/lib/shared/dropdown_menu.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/shared/dropdown_menu.dart", "repo_id": "packages", "token_count": 980 }
954
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// Defines which [TextStyle] objects to use for which Markdown elements. class MarkdownStyleSheet { /// Creates an explicit mapping of [TextStyle] objects to Markdown elements. MarkdownStyleSheet({ this.a, this.p, this.pPadding, this.code, this.h1, this.h1Padding, this.h2, this.h2Padding, this.h3, this.h3Padding, this.h4, this.h4Padding, this.h5, this.h5Padding, this.h6, this.h6Padding, this.em, this.strong, this.del, this.blockquote, this.img, this.checkbox, this.blockSpacing, this.listIndent, this.listBullet, this.listBulletPadding, this.tableHead, this.tableBody, this.tableHeadAlign, this.tableBorder, this.tableColumnWidth, this.tableCellsPadding, this.tableCellsDecoration, this.tableVerticalAlignment = TableCellVerticalAlignment.middle, this.blockquotePadding, this.blockquoteDecoration, this.codeblockPadding, this.codeblockDecoration, this.horizontalRuleDecoration, this.textAlign = WrapAlignment.start, this.h1Align = WrapAlignment.start, this.h2Align = WrapAlignment.start, this.h3Align = WrapAlignment.start, this.h4Align = WrapAlignment.start, this.h5Align = WrapAlignment.start, this.h6Align = WrapAlignment.start, this.unorderedListAlign = WrapAlignment.start, this.orderedListAlign = WrapAlignment.start, this.blockquoteAlign = WrapAlignment.start, this.codeblockAlign = WrapAlignment.start, @Deprecated('Use textScaler instead.') this.textScaleFactor, TextScaler? textScaler, }) : assert( textScaler == null || textScaleFactor == null, 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', ), textScaler = textScaler ?? // Internally, only textScaler is used, so convert the scale factor // to a linear scaler. (textScaleFactor == null ? null : TextScaler.linear(textScaleFactor)), _styles = <String, TextStyle?>{ 'a': a, 'p': p, 'li': p, 'code': code, 'pre': p, 'h1': h1, 'h2': h2, 'h3': h3, 'h4': h4, 'h5': h5, 'h6': h6, 'em': em, 'strong': strong, 'del': del, 'blockquote': blockquote, 'img': img, 'table': p, 'th': tableHead, 'tr': tableBody, 'td': tableBody, }; /// Creates a [MarkdownStyleSheet] from the [TextStyle]s in the provided [ThemeData]. factory MarkdownStyleSheet.fromTheme(ThemeData theme) { assert(theme.textTheme.bodyMedium?.fontSize != null); return MarkdownStyleSheet( a: const TextStyle(color: Colors.blue), p: theme.textTheme.bodyMedium, pPadding: EdgeInsets.zero, code: theme.textTheme.bodyMedium!.copyWith( backgroundColor: theme.cardTheme.color ?? theme.cardColor, fontFamily: 'monospace', fontSize: theme.textTheme.bodyMedium!.fontSize! * 0.85, ), h1: theme.textTheme.headlineSmall, h1Padding: EdgeInsets.zero, h2: theme.textTheme.titleLarge, h2Padding: EdgeInsets.zero, h3: theme.textTheme.titleMedium, h3Padding: EdgeInsets.zero, h4: theme.textTheme.bodyLarge, h4Padding: EdgeInsets.zero, h5: theme.textTheme.bodyLarge, h5Padding: EdgeInsets.zero, h6: theme.textTheme.bodyLarge, h6Padding: EdgeInsets.zero, em: const TextStyle(fontStyle: FontStyle.italic), strong: const TextStyle(fontWeight: FontWeight.bold), del: const TextStyle(decoration: TextDecoration.lineThrough), blockquote: theme.textTheme.bodyMedium, img: theme.textTheme.bodyMedium, checkbox: theme.textTheme.bodyMedium!.copyWith( color: theme.primaryColor, ), blockSpacing: 8.0, listIndent: 24.0, listBullet: theme.textTheme.bodyMedium, listBulletPadding: const EdgeInsets.only(right: 4), tableHead: const TextStyle(fontWeight: FontWeight.w600), tableBody: theme.textTheme.bodyMedium, tableHeadAlign: TextAlign.center, tableBorder: TableBorder.all( color: theme.dividerColor, ), tableColumnWidth: const FlexColumnWidth(), tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8), tableCellsDecoration: const BoxDecoration(), blockquotePadding: const EdgeInsets.all(8.0), blockquoteDecoration: BoxDecoration( color: Colors.blue.shade100, borderRadius: BorderRadius.circular(2.0), ), codeblockPadding: const EdgeInsets.all(8.0), codeblockDecoration: BoxDecoration( color: theme.cardTheme.color ?? theme.cardColor, borderRadius: BorderRadius.circular(2.0), ), horizontalRuleDecoration: BoxDecoration( border: Border( top: BorderSide( width: 5.0, color: theme.dividerColor, ), ), ), ); } /// Creates a [MarkdownStyleSheet] from the [TextStyle]s in the provided [CupertinoThemeData]. factory MarkdownStyleSheet.fromCupertinoTheme(CupertinoThemeData theme) { assert(theme.textTheme.textStyle.fontSize != null); return MarkdownStyleSheet( a: theme.textTheme.textStyle.copyWith( color: theme.brightness == Brightness.dark ? CupertinoColors.link.darkColor : CupertinoColors.link.color, ), p: theme.textTheme.textStyle, pPadding: EdgeInsets.zero, code: theme.textTheme.textStyle.copyWith( backgroundColor: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey6.darkColor : CupertinoColors.systemGrey6.color, fontFamily: 'monospace', fontSize: theme.textTheme.textStyle.fontSize! * 0.85, ), h1: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, fontSize: theme.textTheme.textStyle.fontSize! + 10, ), h1Padding: EdgeInsets.zero, h2: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, fontSize: theme.textTheme.textStyle.fontSize! + 8, ), h2Padding: EdgeInsets.zero, h3: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, fontSize: theme.textTheme.textStyle.fontSize! + 6, ), h3Padding: EdgeInsets.zero, h4: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, fontSize: theme.textTheme.textStyle.fontSize! + 4, ), h4Padding: EdgeInsets.zero, h5: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, fontSize: theme.textTheme.textStyle.fontSize! + 2, ), h5Padding: EdgeInsets.zero, h6: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w500, ), h6Padding: EdgeInsets.zero, em: theme.textTheme.textStyle.copyWith( fontStyle: FontStyle.italic, ), strong: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.bold, ), del: theme.textTheme.textStyle.copyWith( decoration: TextDecoration.lineThrough, ), blockquote: theme.textTheme.textStyle, img: theme.textTheme.textStyle, checkbox: theme.textTheme.textStyle.copyWith( color: theme.primaryColor, ), blockSpacing: 8, listIndent: 24, listBullet: theme.textTheme.textStyle, listBulletPadding: const EdgeInsets.only(right: 4), tableHead: theme.textTheme.textStyle.copyWith( fontWeight: FontWeight.w600, ), tableBody: theme.textTheme.textStyle, tableHeadAlign: TextAlign.center, tableBorder: TableBorder.all(color: CupertinoColors.separator, width: 0), tableColumnWidth: const FlexColumnWidth(), tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8), tableCellsDecoration: BoxDecoration( color: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey6.darkColor : CupertinoColors.systemGrey6.color, ), blockquotePadding: const EdgeInsets.all(16), blockquoteDecoration: BoxDecoration( color: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey6.darkColor : CupertinoColors.systemGrey6.color, border: Border( left: BorderSide( color: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey4.darkColor : CupertinoColors.systemGrey4.color, width: 4, ), ), ), codeblockPadding: const EdgeInsets.all(8), codeblockDecoration: BoxDecoration( color: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey6.darkColor : CupertinoColors.systemGrey6.color, ), horizontalRuleDecoration: BoxDecoration( border: Border( top: BorderSide( color: theme.brightness == Brightness.dark ? CupertinoColors.systemGrey4.darkColor : CupertinoColors.systemGrey4.color, ), ), ), ); } /// Creates a [MarkdownStyle] from the [TextStyle]s in the provided [ThemeData]. /// /// This constructor uses larger fonts for the headings than in /// [MarkdownStyle.fromTheme]. factory MarkdownStyleSheet.largeFromTheme(ThemeData theme) { return MarkdownStyleSheet( a: const TextStyle(color: Colors.blue), p: theme.textTheme.bodyMedium, pPadding: EdgeInsets.zero, code: theme.textTheme.bodyMedium!.copyWith( backgroundColor: theme.cardTheme.color ?? theme.cardColor, fontFamily: 'monospace', fontSize: theme.textTheme.bodyMedium!.fontSize! * 0.85, ), h1: theme.textTheme.displayMedium, h1Padding: EdgeInsets.zero, h2: theme.textTheme.displaySmall, h2Padding: EdgeInsets.zero, h3: theme.textTheme.headlineMedium, h3Padding: EdgeInsets.zero, h4: theme.textTheme.headlineSmall, h4Padding: EdgeInsets.zero, h5: theme.textTheme.titleLarge, h5Padding: EdgeInsets.zero, h6: theme.textTheme.titleMedium, h6Padding: EdgeInsets.zero, em: const TextStyle(fontStyle: FontStyle.italic), strong: const TextStyle(fontWeight: FontWeight.bold), del: const TextStyle(decoration: TextDecoration.lineThrough), blockquote: theme.textTheme.bodyMedium, img: theme.textTheme.bodyMedium, checkbox: theme.textTheme.bodyMedium!.copyWith( color: theme.primaryColor, ), blockSpacing: 8.0, listIndent: 24.0, listBullet: theme.textTheme.bodyMedium, listBulletPadding: const EdgeInsets.only(right: 4), tableHead: const TextStyle(fontWeight: FontWeight.w600), tableBody: theme.textTheme.bodyMedium, tableHeadAlign: TextAlign.center, tableBorder: TableBorder.all( color: theme.dividerColor, ), tableColumnWidth: const FlexColumnWidth(), tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8), tableCellsDecoration: const BoxDecoration(), blockquotePadding: const EdgeInsets.all(8.0), blockquoteDecoration: BoxDecoration( color: Colors.blue.shade100, borderRadius: BorderRadius.circular(2.0), ), codeblockPadding: const EdgeInsets.all(8.0), codeblockDecoration: BoxDecoration( color: theme.cardTheme.color ?? theme.cardColor, borderRadius: BorderRadius.circular(2.0), ), horizontalRuleDecoration: BoxDecoration( border: Border( top: BorderSide( width: 5.0, color: theme.dividerColor, ), ), ), ); } /// Creates a [MarkdownStyleSheet] based on the current style, with the /// provided parameters overridden. MarkdownStyleSheet copyWith({ TextStyle? a, TextStyle? p, EdgeInsets? pPadding, TextStyle? code, TextStyle? h1, EdgeInsets? h1Padding, TextStyle? h2, EdgeInsets? h2Padding, TextStyle? h3, EdgeInsets? h3Padding, TextStyle? h4, EdgeInsets? h4Padding, TextStyle? h5, EdgeInsets? h5Padding, TextStyle? h6, EdgeInsets? h6Padding, TextStyle? em, TextStyle? strong, TextStyle? del, TextStyle? blockquote, TextStyle? img, TextStyle? checkbox, double? blockSpacing, double? listIndent, TextStyle? listBullet, EdgeInsets? listBulletPadding, TextStyle? tableHead, TextStyle? tableBody, TextAlign? tableHeadAlign, TableBorder? tableBorder, TableColumnWidth? tableColumnWidth, EdgeInsets? tableCellsPadding, Decoration? tableCellsDecoration, TableCellVerticalAlignment? tableVerticalAlignment, EdgeInsets? blockquotePadding, Decoration? blockquoteDecoration, EdgeInsets? codeblockPadding, Decoration? codeblockDecoration, Decoration? horizontalRuleDecoration, WrapAlignment? textAlign, WrapAlignment? h1Align, WrapAlignment? h2Align, WrapAlignment? h3Align, WrapAlignment? h4Align, WrapAlignment? h5Align, WrapAlignment? h6Align, WrapAlignment? unorderedListAlign, WrapAlignment? orderedListAlign, WrapAlignment? blockquoteAlign, WrapAlignment? codeblockAlign, @Deprecated('Use textScaler instead.') double? textScaleFactor, TextScaler? textScaler, }) { assert( textScaler == null || textScaleFactor == null, 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', ); // If either of textScaler or textScaleFactor is non-null, pass null for the // other instead of the previous value, since only one is allowed. final TextScaler? newTextScaler = textScaler ?? (textScaleFactor == null ? this.textScaler : null); final double? nextTextScaleFactor = textScaleFactor ?? (textScaler == null ? this.textScaleFactor : null); return MarkdownStyleSheet( a: a ?? this.a, p: p ?? this.p, pPadding: pPadding ?? this.pPadding, code: code ?? this.code, h1: h1 ?? this.h1, h1Padding: h1Padding ?? this.h1Padding, h2: h2 ?? this.h2, h2Padding: h2Padding ?? this.h2Padding, h3: h3 ?? this.h3, h3Padding: h3Padding ?? this.h3Padding, h4: h4 ?? this.h4, h4Padding: h4Padding ?? this.h4Padding, h5: h5 ?? this.h5, h5Padding: h5Padding ?? this.h5Padding, h6: h6 ?? this.h6, h6Padding: h6Padding ?? this.h6Padding, em: em ?? this.em, strong: strong ?? this.strong, del: del ?? this.del, blockquote: blockquote ?? this.blockquote, img: img ?? this.img, checkbox: checkbox ?? this.checkbox, blockSpacing: blockSpacing ?? this.blockSpacing, listIndent: listIndent ?? this.listIndent, listBullet: listBullet ?? this.listBullet, listBulletPadding: listBulletPadding ?? this.listBulletPadding, tableHead: tableHead ?? this.tableHead, tableBody: tableBody ?? this.tableBody, tableHeadAlign: tableHeadAlign ?? this.tableHeadAlign, tableBorder: tableBorder ?? this.tableBorder, tableColumnWidth: tableColumnWidth ?? this.tableColumnWidth, tableCellsPadding: tableCellsPadding ?? this.tableCellsPadding, tableCellsDecoration: tableCellsDecoration ?? this.tableCellsDecoration, tableVerticalAlignment: tableVerticalAlignment ?? this.tableVerticalAlignment, blockquotePadding: blockquotePadding ?? this.blockquotePadding, blockquoteDecoration: blockquoteDecoration ?? this.blockquoteDecoration, codeblockPadding: codeblockPadding ?? this.codeblockPadding, codeblockDecoration: codeblockDecoration ?? this.codeblockDecoration, horizontalRuleDecoration: horizontalRuleDecoration ?? this.horizontalRuleDecoration, textAlign: textAlign ?? this.textAlign, h1Align: h1Align ?? this.h1Align, h2Align: h2Align ?? this.h2Align, h3Align: h3Align ?? this.h3Align, h4Align: h4Align ?? this.h4Align, h5Align: h5Align ?? this.h5Align, h6Align: h6Align ?? this.h6Align, unorderedListAlign: unorderedListAlign ?? this.unorderedListAlign, orderedListAlign: orderedListAlign ?? this.orderedListAlign, blockquoteAlign: blockquoteAlign ?? this.blockquoteAlign, codeblockAlign: codeblockAlign ?? this.codeblockAlign, textScaler: newTextScaler, textScaleFactor: nextTextScaleFactor, ); } /// Returns a new text style that is a combination of this style and the given /// [other] style. MarkdownStyleSheet merge(MarkdownStyleSheet? other) { if (other == null) { return this; } return copyWith( a: a!.merge(other.a), p: p!.merge(other.p), pPadding: other.pPadding, code: code!.merge(other.code), h1: h1!.merge(other.h1), h1Padding: other.h1Padding, h2: h2!.merge(other.h2), h2Padding: other.h2Padding, h3: h3!.merge(other.h3), h3Padding: other.h3Padding, h4: h4!.merge(other.h4), h4Padding: other.h4Padding, h5: h5!.merge(other.h5), h5Padding: other.h5Padding, h6: h6!.merge(other.h6), h6Padding: other.h6Padding, em: em!.merge(other.em), strong: strong!.merge(other.strong), del: del!.merge(other.del), blockquote: blockquote!.merge(other.blockquote), img: img!.merge(other.img), checkbox: checkbox!.merge(other.checkbox), blockSpacing: other.blockSpacing, listIndent: other.listIndent, listBullet: listBullet!.merge(other.listBullet), listBulletPadding: other.listBulletPadding, tableHead: tableHead!.merge(other.tableHead), tableBody: tableBody!.merge(other.tableBody), tableHeadAlign: other.tableHeadAlign, tableBorder: other.tableBorder, tableColumnWidth: other.tableColumnWidth, tableCellsPadding: other.tableCellsPadding, tableCellsDecoration: other.tableCellsDecoration, tableVerticalAlignment: other.tableVerticalAlignment, blockquotePadding: other.blockquotePadding, blockquoteDecoration: other.blockquoteDecoration, codeblockPadding: other.codeblockPadding, codeblockDecoration: other.codeblockDecoration, horizontalRuleDecoration: other.horizontalRuleDecoration, textAlign: other.textAlign, h1Align: other.h1Align, h2Align: other.h2Align, h3Align: other.h3Align, h4Align: other.h4Align, h5Align: other.h5Align, h6Align: other.h6Align, unorderedListAlign: other.unorderedListAlign, orderedListAlign: other.orderedListAlign, blockquoteAlign: other.blockquoteAlign, codeblockAlign: other.codeblockAlign, textScaleFactor: other.textScaleFactor, // Only one of textScaler and textScaleFactor can be passed. If // other.textScaleFactor is non-null, then the sheet was created with a // textScaleFactor and the textScaler was derived from that, so should be // ignored so that the textScaleFactor continues to be set. textScaler: other.textScaleFactor == null ? other.textScaler : null, ); } /// The [TextStyle] to use for `a` elements. final TextStyle? a; /// The [TextStyle] to use for `p` elements. final TextStyle? p; /// The padding to use for `p` elements. final EdgeInsets? pPadding; /// The [TextStyle] to use for `code` elements. final TextStyle? code; /// The [TextStyle] to use for `h1` elements. final TextStyle? h1; /// The padding to use for `h1` elements. final EdgeInsets? h1Padding; /// The [TextStyle] to use for `h2` elements. final TextStyle? h2; /// The padding to use for `h2` elements. final EdgeInsets? h2Padding; /// The [TextStyle] to use for `h3` elements. final TextStyle? h3; /// The padding to use for `h3` elements. final EdgeInsets? h3Padding; /// The [TextStyle] to use for `h4` elements. final TextStyle? h4; /// The padding to use for `h4` elements. final EdgeInsets? h4Padding; /// The [TextStyle] to use for `h5` elements. final TextStyle? h5; /// The padding to use for `h5` elements. final EdgeInsets? h5Padding; /// The [TextStyle] to use for `h6` elements. final TextStyle? h6; /// The padding to use for `h6` elements. final EdgeInsets? h6Padding; /// The [TextStyle] to use for `em` elements. final TextStyle? em; /// The [TextStyle] to use for `strong` elements. final TextStyle? strong; /// The [TextStyle] to use for `del` elements. final TextStyle? del; /// The [TextStyle] to use for `blockquote` elements. final TextStyle? blockquote; /// The [TextStyle] to use for `img` elements. final TextStyle? img; /// The [TextStyle] to use for `input` elements. final TextStyle? checkbox; /// The amount of vertical space to use between block-level elements. final double? blockSpacing; /// The amount of horizontal space to indent list items. final double? listIndent; /// The [TextStyle] to use for bullets. final TextStyle? listBullet; /// The padding to use for bullets. final EdgeInsets? listBulletPadding; /// The [TextStyle] to use for `th` elements. final TextStyle? tableHead; /// The [TextStyle] to use for `td` elements. final TextStyle? tableBody; /// The [TextAlign] to use for `th` elements. final TextAlign? tableHeadAlign; /// The [TableBorder] to use for `table` elements. final TableBorder? tableBorder; /// The [TableColumnWidth] to use for `th` and `td` elements. final TableColumnWidth? tableColumnWidth; /// The padding to use for `th` and `td` elements. final EdgeInsets? tableCellsPadding; /// The decoration to use for `th` and `td` elements. final Decoration? tableCellsDecoration; /// The [TableCellVerticalAlignment] to use for `th` and `td` elements. final TableCellVerticalAlignment tableVerticalAlignment; /// The padding to use for `blockquote` elements. final EdgeInsets? blockquotePadding; /// The decoration to use behind `blockquote` elements. final Decoration? blockquoteDecoration; /// The padding to use for `pre` elements. final EdgeInsets? codeblockPadding; /// The decoration to use behind for `pre` elements. final Decoration? codeblockDecoration; /// The decoration to use for `hr` elements. final Decoration? horizontalRuleDecoration; /// The [WrapAlignment] to use for normal text. Defaults to start. final WrapAlignment textAlign; /// The [WrapAlignment] to use for h1 text. Defaults to start. final WrapAlignment h1Align; /// The [WrapAlignment] to use for h2 text. Defaults to start. final WrapAlignment h2Align; /// The [WrapAlignment] to use for h3 text. Defaults to start. final WrapAlignment h3Align; /// The [WrapAlignment] to use for h4 text. Defaults to start. final WrapAlignment h4Align; /// The [WrapAlignment] to use for h5 text. Defaults to start. final WrapAlignment h5Align; /// The [WrapAlignment] to use for h6 text. Defaults to start. final WrapAlignment h6Align; /// The [WrapAlignment] to use for an unordered list. Defaults to start. final WrapAlignment unorderedListAlign; /// The [WrapAlignment] to use for an ordered list. Defaults to start. final WrapAlignment orderedListAlign; /// The [WrapAlignment] to use for a blockquote. Defaults to start. final WrapAlignment blockquoteAlign; /// The [WrapAlignment] to use for a code block. Defaults to start. final WrapAlignment codeblockAlign; /// The text scaler to use in textual elements. final TextScaler? textScaler; /// The text scale factor to use in textual elements. /// /// This will be non-null only if the sheet was created with the deprecated /// [textScaleFactor] instead of [textScaler]. @Deprecated('Use textScaler instead.') final double? textScaleFactor; /// A [Map] from element name to the corresponding [TextStyle] object. Map<String, TextStyle?> get styles => _styles; Map<String, TextStyle?> _styles; @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != MarkdownStyleSheet) { return false; } return other is MarkdownStyleSheet && other.a == a && other.p == p && other.pPadding == pPadding && other.code == code && other.h1 == h1 && other.h1Padding == h1Padding && other.h2 == h2 && other.h2Padding == h2Padding && other.h3 == h3 && other.h3Padding == h3Padding && other.h4 == h4 && other.h4Padding == h4Padding && other.h5 == h5 && other.h5Padding == h5Padding && other.h6 == h6 && other.h6Padding == h6Padding && other.em == em && other.strong == strong && other.del == del && other.blockquote == blockquote && other.img == img && other.checkbox == checkbox && other.blockSpacing == blockSpacing && other.listIndent == listIndent && other.listBullet == listBullet && other.listBulletPadding == listBulletPadding && other.tableHead == tableHead && other.tableBody == tableBody && other.tableHeadAlign == tableHeadAlign && other.tableBorder == tableBorder && other.tableColumnWidth == tableColumnWidth && other.tableCellsPadding == tableCellsPadding && other.tableCellsDecoration == tableCellsDecoration && other.tableVerticalAlignment == tableVerticalAlignment && other.blockquotePadding == blockquotePadding && other.blockquoteDecoration == blockquoteDecoration && other.codeblockPadding == codeblockPadding && other.codeblockDecoration == codeblockDecoration && other.horizontalRuleDecoration == horizontalRuleDecoration && other.textAlign == textAlign && other.h1Align == h1Align && other.h2Align == h2Align && other.h3Align == h3Align && other.h4Align == h4Align && other.h5Align == h5Align && other.h6Align == h6Align && other.unorderedListAlign == unorderedListAlign && other.orderedListAlign == orderedListAlign && other.blockquoteAlign == blockquoteAlign && other.codeblockAlign == codeblockAlign && other.textScaler == textScaler; } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode { return Object.hashAll(<Object?>[ a, p, pPadding, code, h1, h1Padding, h2, h2Padding, h3, h3Padding, h4, h4Padding, h5, h5Padding, h6, h6Padding, em, strong, del, blockquote, img, checkbox, blockSpacing, listIndent, listBullet, listBulletPadding, tableHead, tableBody, tableHeadAlign, tableBorder, tableColumnWidth, tableCellsPadding, tableCellsDecoration, tableVerticalAlignment, blockquotePadding, blockquoteDecoration, codeblockPadding, codeblockDecoration, horizontalRuleDecoration, textAlign, h1Align, h2Align, h3Align, h4Align, h5Align, h6Align, unorderedListAlign, orderedListAlign, blockquoteAlign, codeblockAlign, textScaler, textScaleFactor, ]); } }
packages/packages/flutter_markdown/lib/src/style_sheet.dart/0
{ "file_path": "packages/packages/flutter_markdown/lib/src/style_sheet.dart", "repo_id": "packages", "token_count": 11492 }
955
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:markdown/markdown.dart' as md; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('InlineWidget', () { testWidgets( 'Test inline widget', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( MarkdownBody( data: 'Hello, foo bar', builders: <String, MarkdownElementBuilder>{ 'sub': SubscriptBuilder(), }, extensionSet: md.ExtensionSet( <md.BlockSyntax>[], <md.InlineSyntax>[SubscriptSyntax()], ), ), ), ); final Text textWidget = tester.firstWidget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; final TextSpan part1 = span.children![0] as TextSpan; expect(part1.toPlainText(), 'Hello, '); final WidgetSpan part2 = span.children![1] as WidgetSpan; expect(part2.alignment, PlaceholderAlignment.middle); expect(part2.child, isA<Text>()); expect((part2.child as Text).data, 'foo'); final TextSpan part3 = span.children![2] as TextSpan; expect(part3.toPlainText(), ' bar'); }, ); }); } class SubscriptBuilder extends MarkdownElementBuilder { @override Widget visitElementAfterWithContext( BuildContext context, md.Element element, TextStyle? preferredStyle, TextStyle? parentStyle, ) { return Text.rich(WidgetSpan( alignment: PlaceholderAlignment.middle, child: Text(element.textContent), )); } } class SubscriptSyntax extends md.InlineSyntax { SubscriptSyntax() : super(_pattern); static const String _pattern = r'(foo)'; @override bool onMatch(md.InlineParser parser, Match match) { parser.addNode(md.Element.text('sub', match[1]!)); return true; } }
packages/packages/flutter_markdown/test/inline_widget_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/inline_widget_test.dart", "repo_id": "packages", "token_count": 933 }
956
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'common.dart'; import 'io.dart' as io; import 'logger.dart'; enum TerminalColor { red, green, blue, cyan, yellow, magenta, grey, } /// A class that contains the context settings for command text output to the /// console. class OutputPreferences { OutputPreferences({ bool? wrapText, int? wrapColumn, bool? showColor, io.Stdio? stdio, }) : _stdio = stdio, wrapText = wrapText ?? stdio?.hasTerminal ?? false, _overrideWrapColumn = wrapColumn, showColor = showColor ?? false; /// A version of this class for use in tests. OutputPreferences.test( {this.wrapText = false, int wrapColumn = kDefaultTerminalColumns, this.showColor = false}) : _overrideWrapColumn = wrapColumn, _stdio = null; final io.Stdio? _stdio; /// If [wrapText] is true, then any text sent to the context's [Logger] /// instance (e.g. from the [printError] or [printStatus] functions) will be /// wrapped (newlines added between words) to be no longer than the /// [wrapColumn] specifies. Defaults to true if there is a terminal. To /// determine if there's a terminal, [OutputPreferences] asks the context's /// stdio. final bool wrapText; /// The terminal width used by the [wrapText] function if there is no terminal /// attached to [io.Stdio], --wrap is on, and --wrap-columns was not specified. static const int kDefaultTerminalColumns = 100; /// The column at which output sent to the context's [Logger] instance /// (e.g. from the [printError] or [printStatus] functions) will be wrapped. /// Ignored if [wrapText] is false. Defaults to the width of the output /// terminal, or to [kDefaultTerminalColumns] if not writing to a terminal. final int? _overrideWrapColumn; int get wrapColumn { return _overrideWrapColumn ?? _stdio?.terminalColumns ?? kDefaultTerminalColumns; } /// Whether or not to output ANSI color codes when writing to the output /// terminal. Defaults to whatever [platform.stdoutSupportsAnsi] says if /// writing to a terminal, and false otherwise. final bool showColor; @override String toString() { return 'OutputPreferences[wrapText: $wrapText, wrapColumn: $wrapColumn, showColor: $showColor]'; } } /// The command line terminal, if available. abstract class Terminal { /// Create a new test [Terminal]. /// /// If not specified, [supportsColor] defaults to `false`. factory Terminal.test({bool supportsColor, bool supportsEmoji}) = _TestTerminal; /// Whether the current terminal supports color escape codes. bool get supportsColor; /// Whether the current terminal can display emoji. bool get supportsEmoji; /// When we have a choice of styles (e.g. animated spinners), this selects the /// style to use. int get preferredStyle; /// Whether we are interacting with the flutter tool via the terminal. /// /// If not set, defaults to false. bool get usesTerminalUi; set usesTerminalUi(bool value); /// Whether there is a terminal attached to stdin. /// /// If true, this usually indicates that a user is using the CLI as /// opposed to using an IDE. This can be used to determine /// whether it is appropriate to show a terminal prompt, /// or whether an automatic selection should be made instead. bool get stdinHasTerminal; /// Warning mark to use in stdout or stderr. String get warningMark; /// Success mark to use in stdout. String get successMark; String bolden(String message); String color(String message, TerminalColor color); String clearScreen(); bool get singleCharMode; set singleCharMode(bool value); /// Return keystrokes from the console. /// /// This is a single-subscription stream. This stream may be closed before /// the application exits. /// /// Useful when the console is in [singleCharMode]. Stream<String> get keystrokes; /// Prompts the user to input a character within a given list. Re-prompts if /// entered character is not in the list. /// /// The `prompt`, if non-null, is the text displayed prior to waiting for user /// input each time. If `prompt` is non-null and `displayAcceptedCharacters` /// is true, the accepted keys are printed next to the `prompt`. /// /// The returned value is the user's input; if `defaultChoiceIndex` is not /// null, and the user presses enter without any other input, the return value /// will be the character in `acceptedCharacters` at the index given by /// `defaultChoiceIndex`. /// /// The accepted characters must be a String with a length of 1, excluding any /// whitespace characters such as `\t`, `\n`, or ` `. /// /// If [usesTerminalUi] is false, throws a [StateError]. Future<String> promptForCharInput( List<String> acceptedCharacters, { required Logger logger, String? prompt, int? defaultChoiceIndex, bool displayAcceptedCharacters = true, }); } class AnsiTerminal implements Terminal { AnsiTerminal({ required io.Stdio stdio, DateTime? now, // Time used to determine preferredStyle. Defaults to 0001-01-01 00:00. bool? supportsColor, }) : _stdio = stdio, _now = now ?? DateTime(1), _supportsColor = supportsColor; final io.Stdio _stdio; final DateTime _now; static const String bold = '\u001B[1m'; static const String resetAll = '\u001B[0m'; static const String resetColor = '\u001B[39m'; static const String resetBold = '\u001B[22m'; static const String clear = '\u001B[2J\u001B[H'; static const String red = '\u001b[31m'; static const String green = '\u001b[32m'; static const String blue = '\u001b[34m'; static const String cyan = '\u001b[36m'; static const String magenta = '\u001b[35m'; static const String yellow = '\u001b[33m'; static const String grey = '\u001b[90m'; static const Map<TerminalColor, String> _colorMap = <TerminalColor, String>{ TerminalColor.red: red, TerminalColor.green: green, TerminalColor.blue: blue, TerminalColor.cyan: cyan, TerminalColor.magenta: magenta, TerminalColor.yellow: yellow, TerminalColor.grey: grey, }; static String colorCode(TerminalColor color) => _colorMap[color]!; @override bool get supportsColor => _supportsColor ?? stdout.supportsAnsiEscapes; final bool? _supportsColor; // Assume unicode emojis are supported when not on Windows. // If we are on Windows, unicode emojis are supported in Windows Terminal, // which sets the WT_SESSION environment variable. See: // https://github.com/microsoft/terminal/blob/master/doc/user-docs/index.md#tips-and-tricks @override bool get supportsEmoji => !isWindows || Platform.environment.containsKey('WT_SESSION'); @override int get preferredStyle { const int workdays = DateTime.friday; if (_now.weekday <= workdays) { return _now.weekday - 1; } return _now.hour + workdays; } final RegExp _boldControls = RegExp( '(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})', ); @override bool usesTerminalUi = false; @override String get warningMark { return bolden(color('[!]', TerminalColor.red)); } @override String get successMark { return bolden(color('✓', TerminalColor.green)); } @override String bolden(String message) { if (!supportsColor || message.isEmpty) { return message; } final StringBuffer buffer = StringBuffer(); for (String line in message.split('\n')) { // If there were bolds or resetBolds in the string before, then nuke them: // they're redundant. This prevents previously embedded resets from // stopping the boldness. line = line.replaceAll(_boldControls, ''); buffer.writeln('$bold$line$resetBold'); } final String result = buffer.toString(); // avoid introducing a new newline to the emboldened text return (!message.endsWith('\n') && result.endsWith('\n')) ? result.substring(0, result.length - 1) : result; } @override String color(String message, TerminalColor color) { if (!supportsColor || message.isEmpty) { return message; } final StringBuffer buffer = StringBuffer(); final String colorCodes = _colorMap[color]!; for (String line in message.split('\n')) { // If there were resets in the string before, then keep them, but // restart the color right after. This prevents embedded resets from // stopping the colors, and allows nesting of colors. line = line.replaceAll(resetColor, '$resetColor$colorCodes'); buffer.writeln('$colorCodes$line$resetColor'); } final String result = buffer.toString(); // avoid introducing a new newline to the colored text return (!message.endsWith('\n') && result.endsWith('\n')) ? result.substring(0, result.length - 1) : result; } @override String clearScreen() => supportsColor ? clear : '\n\n'; @override bool get singleCharMode { if (!_stdio.stdinHasTerminal) { return false; } final io.Stdin stdin = _stdio.stdin as io.Stdin; return stdin.lineMode && stdin.echoMode; } @override set singleCharMode(bool value) { if (!_stdio.stdinHasTerminal) { return; } final io.Stdin stdin = _stdio.stdin as io.Stdin; // The order of setting lineMode and echoMode is important on Windows. if (value) { stdin.echoMode = false; stdin.lineMode = false; } else { stdin.lineMode = true; stdin.echoMode = true; } } @override bool get stdinHasTerminal => _stdio.stdinHasTerminal; Stream<String>? _broadcastStdInString; @override Stream<String> get keystrokes { return _broadcastStdInString ??= _stdio.stdin .transform<String>(const AsciiDecoder(allowInvalid: true)) .asBroadcastStream(); } @override Future<String> promptForCharInput( List<String> acceptedCharacters, { required Logger logger, String? prompt, int? defaultChoiceIndex, bool displayAcceptedCharacters = true, }) async { assert(acceptedCharacters.isNotEmpty); assert(prompt == null || prompt.isNotEmpty); if (!usesTerminalUi) { throw StateError('cannot prompt without a terminal ui'); } List<String> charactersToDisplay = acceptedCharacters; if (defaultChoiceIndex != null) { assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length); charactersToDisplay = List<String>.of(charactersToDisplay); charactersToDisplay[defaultChoiceIndex] = bolden(charactersToDisplay[defaultChoiceIndex]); acceptedCharacters.add(''); } String? choice; singleCharMode = true; while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) { if (prompt != null) { logger.printStatus(prompt, emphasis: true, newline: false); if (displayAcceptedCharacters) { logger.printStatus(' [${charactersToDisplay.join("|")}]', newline: false); } // prompt ends with ': ' logger.printStatus(': ', emphasis: true, newline: false); } choice = (await keystrokes.first).trim(); logger.printStatus(choice); } singleCharMode = false; if (defaultChoiceIndex != null && choice == '') { choice = acceptedCharacters[defaultChoiceIndex]; } return choice; } } class _TestTerminal implements Terminal { _TestTerminal({this.supportsColor = false, this.supportsEmoji = false}); @override bool usesTerminalUi = false; @override String bolden(String message) => message; @override String clearScreen() => '\n\n'; @override String color(String message, TerminalColor color) => message; @override Stream<String> get keystrokes => const Stream<String>.empty(); @override Future<String> promptForCharInput( List<String> acceptedCharacters, { required Logger logger, String? prompt, int? defaultChoiceIndex, bool displayAcceptedCharacters = true, }) { throw UnsupportedError( 'promptForCharInput not supported in the test terminal.'); } @override bool get singleCharMode => false; @override set singleCharMode(bool value) {} @override final bool supportsColor; @override final bool supportsEmoji; @override int get preferredStyle => 0; @override bool get stdinHasTerminal => false; @override String get successMark => '✓'; @override String get warningMark => '[!]'; }
packages/packages/flutter_migrate/lib/src/base/terminal.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/base/terminal.dart", "repo_id": "packages", "token_count": 4289 }
957
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_migrate/src/base/context.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/base/signals.dart'; import 'package:flutter_migrate/src/base/terminal.dart'; import 'package:flutter_migrate/src/commands/abandon.dart'; import 'package:flutter_migrate/src/utils.dart'; import 'package:process/process.dart'; import 'src/common.dart'; import 'src/context.dart'; import 'src/test_flutter_command_runner.dart'; void main() { late FileSystem fileSystem; late BufferLogger logger; late Terminal terminal; late ProcessManager processManager; late Directory appDir; setUp(() { fileSystem = LocalFileSystem.test(signals: LocalSignals.instance); appDir = fileSystem.systemTempDirectory.createTempSync('apptestdir'); logger = BufferLogger.test(); terminal = Terminal.test(); processManager = const LocalProcessManager(); }); tearDown(() async { tryToDelete(appDir); }); testUsingContext('abandon deletes staging directory', () async { final MigrateAbandonCommand command = MigrateAbandonCommand( logger: logger, fileSystem: fileSystem, terminal: terminal, processManager: processManager, ); final Directory stagingDir = appDir.childDirectory(kDefaultMigrateStagingDirectoryName); appDir.childFile('lib/main.dart').createSync(recursive: true); final File pubspecOriginal = appDir.childFile('pubspec.yaml'); pubspecOriginal.createSync(); pubspecOriginal.writeAsStringSync(''' name: originalname description: A new Flutter project. version: 1.0.0+1 environment: sdk: '>=2.18.0-58.0.dev <3.0.0' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true''', flush: true); expect(stagingDir.existsSync(), false); await createTestCommandRunner(command).run(<String>[ 'abandon', '--staging-directory=${stagingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect(logger.errorText, contains('Provided staging directory')); expect(logger.errorText, contains('migrate_staging_dir` does not exist or is not valid.')); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'abandon', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect(logger.statusText, contains('No migration in progress. Start a new migration with:')); final File pubspecModified = stagingDir.childFile('pubspec.yaml'); pubspecModified.createSync(recursive: true); pubspecModified.writeAsStringSync(''' name: newname description: new description of the test project version: 1.0.0+1 environment: sdk: '>=2.18.0-58.0.dev <3.0.0' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: false EXTRALINE''', flush: true); final File addedFile = stagingDir.childFile('added.file'); addedFile.createSync(recursive: true); addedFile.writeAsStringSync('new file contents'); final File manifestFile = stagingDir.childFile('.migrate_manifest'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: added_files: - added.file deleted_files: '''); expect(appDir.childFile('lib/main.dart').existsSync(), true); expect(stagingDir.existsSync(), true); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'abandon', '--staging-directory=${stagingDir.path}', '--project-directory=${appDir.path}', '--force', '--flutter-subcommand', ]); expect(logger.statusText, contains('Abandon complete. Start a new migration with:')); expect(stagingDir.existsSync(), false); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, }); }
packages/packages/flutter_migrate/test/abandon_test.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/abandon_test.dart", "repo_id": "packages", "token_count": 1516 }
958
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io show IOSink, Stdout, StdoutException; import 'package:flutter_migrate/src/base/io.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:test/fake.dart'; /// An IOSink that completes a future with the first line written to it. class CompleterIOSink extends MemoryIOSink { CompleterIOSink({ this.throwOnAdd = false, }); final bool throwOnAdd; final Completer<List<int>> _completer = Completer<List<int>>(); Future<List<int>> get future => _completer.future; @override void add(List<int> data) { if (!_completer.isCompleted) { // When throwOnAdd is true, complete with empty so any expected output // doesn't appear. _completer.complete(throwOnAdd ? <int>[] : data); } if (throwOnAdd) { throw Exception('CompleterIOSink Error'); } super.add(data); } } /// An IOSink that collects whatever is written to it. class MemoryIOSink implements IOSink { @override Encoding encoding = utf8; final List<List<int>> writes = <List<int>>[]; @override void add(List<int> data) { writes.add(data); } @override Future<void> addStream(Stream<List<int>> stream) { final Completer<void> completer = Completer<void>(); late StreamSubscription<List<int>> sub; sub = stream.listen( (List<int> data) { try { add(data); // Catches all exceptions to propagate them to the completer. } catch (err, stack) { // ignore: avoid_catches_without_on_clauses sub.cancel(); completer.completeError(err, stack); } }, onError: completer.completeError, onDone: completer.complete, cancelOnError: true, ); return completer.future; } @override void writeCharCode(int charCode) { add(<int>[charCode]); } @override void write(Object? obj) { add(encoding.encode('$obj')); } @override void writeln([Object? obj = '']) { add(encoding.encode('$obj\n')); } @override void writeAll(Iterable<dynamic> objects, [String separator = '']) { bool addSeparator = false; for (final dynamic object in objects) { if (addSeparator) { write(separator); } write(object); addSeparator = true; } } @override void addError(dynamic error, [StackTrace? stackTrace]) { throw UnimplementedError(); } @override Future<void> get done => close(); @override Future<void> close() async {} @override Future<void> flush() async {} void clear() { writes.clear(); } String getAndClear() { final String result = utf8.decode(writes.expand((List<int> l) => l).toList()); clear(); return result; } } class MemoryStdout extends MemoryIOSink implements io.Stdout { @override bool get hasTerminal => _hasTerminal; set hasTerminal(bool value) { _hasTerminal = value; } bool _hasTerminal = true; @override // ignore: override_on_non_overriding_member String get lineTerminator => '\n'; @override // ignore: override_on_non_overriding_member set lineTerminator(String value) { throw UnimplementedError('Setting the line terminator is not supported'); } @override io.IOSink get nonBlocking => this; @override bool get supportsAnsiEscapes => _supportsAnsiEscapes; set supportsAnsiEscapes(bool value) { _supportsAnsiEscapes = value; } bool _supportsAnsiEscapes = true; @override int get terminalColumns { if (_terminalColumns != null) { return _terminalColumns!; } throw const io.StdoutException('unspecified mock value'); } set terminalColumns(int value) => _terminalColumns = value; int? _terminalColumns; @override int get terminalLines { if (_terminalLines != null) { return _terminalLines!; } throw const io.StdoutException('unspecified mock value'); } set terminalLines(int value) => _terminalLines = value; int? _terminalLines; } /// A Stdio that collects stdout and supports simulated stdin. class FakeStdio extends Stdio { final MemoryStdout _stdout = MemoryStdout()..terminalColumns = 80; final MemoryIOSink _stderr = MemoryIOSink(); final FakeStdin _stdin = FakeStdin(); @override MemoryStdout get stdout => _stdout; @override MemoryIOSink get stderr => _stderr; @override Stream<List<int>> get stdin => _stdin; void simulateStdin(String line) { _stdin.controller.add(utf8.encode('$line\n')); } @override bool hasTerminal = true; List<String> get writtenToStdout => _stdout.writes.map<String>(_stdout.encoding.decode).toList(); List<String> get writtenToStderr => _stderr.writes.map<String>(_stderr.encoding.decode).toList(); } class FakeStdin extends Fake implements Stdin { final StreamController<List<int>> controller = StreamController<List<int>>(); @override bool echoMode = true; @override bool hasTerminal = true; @override bool echoNewlineMode = true; @override bool lineMode = true; @override Stream<S> transform<S>(StreamTransformer<List<int>, S> transformer) { return controller.stream.transform(transformer); } @override StreamSubscription<List<int>> listen( void Function(List<int> event)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError, }) { return controller.stream.listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } } class FakeStopwatch implements Stopwatch { @override bool get isRunning => _isRunning; bool _isRunning = false; @override void start() => _isRunning = true; @override void stop() => _isRunning = false; @override Duration elapsed = Duration.zero; @override int get elapsedMicroseconds => elapsed.inMicroseconds; @override int get elapsedMilliseconds => elapsed.inMilliseconds; @override int get elapsedTicks => elapsed.inMilliseconds; @override int get frequency => 1000; @override void reset() { _isRunning = false; elapsed = Duration.zero; } @override String toString() => 'FakeStopwatch $elapsed $isRunning'; } class FakeStopwatchFactory implements StopwatchFactory { FakeStopwatchFactory( {Stopwatch? stopwatch, Map<String, Stopwatch>? stopwatches}) : stopwatches = <String, Stopwatch>{ if (stopwatches != null) ...stopwatches, if (stopwatch != null) '': stopwatch, }; Map<String, Stopwatch> stopwatches; @override Stopwatch createStopwatch([String name = '']) { return stopwatches[name] ?? FakeStopwatch(); } }
packages/packages/flutter_migrate/test/src/fakes.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/fakes.dart", "repo_id": "packages", "token_count": 2527 }
959
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:label="flutter_plugin_android_lifecycle_example" android:icon="@mipmap/ic_launcher"> <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> </application> </manifest>
packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 391 }
960
dartdoc: categories: "Get started": markdown: doc/get-started.md name: Get started "Upgrading": markdown: doc/upgrading.md name: Upgrade an existing app "Configuration": markdown: doc/configuration.md name: Configuration "Navigation": markdown: doc/navigation.md name: Navigation "Redirection": markdown: doc/redirection.md name: Redirection "Web": markdown: doc/web.md name: Web "Deep linking": markdown: doc/deep-linking.md name: Deep linking "Transition animations": markdown: doc/transition-animations.md name: Transition animations "Type-safe routes": markdown: doc/type-safe-routes.md name: Type-safe routes "Named routes": markdown: doc/named-routes.md name: Type-safe routes "Error handling": markdown: doc/error-handling.md name: Error handling categoryOrder: - "Get started" - "Upgrading" - "Configuration" - "Navigation" - "Redirection" - "Web" - "Deep linking" - "Transition animations" - "Type-safe routes" - "Named routes" - "Error handling" showUndocumentedCategories: true ignore: - broken-link - missing-from-search-index
packages/packages/go_router/dartdoc_options.yaml/0
{ "file_path": "packages/packages/go_router/dartdoc_options.yaml", "repo_id": "packages", "token_count": 531 }
961
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/go_router/example/android/gradle.properties/0
{ "file_path": "packages/packages/go_router/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
962
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'author.dart'; import 'book.dart'; /// Library data mock. final Library libraryInstance = Library() ..addBook( title: 'Left Hand of Darkness', authorName: 'Ursula K. Le Guin', isPopular: true, isNew: true) ..addBook( title: 'Too Like the Lightning', authorName: 'Ada Palmer', isPopular: false, isNew: true) ..addBook( title: 'Kindred', authorName: 'Octavia E. Butler', isPopular: true, isNew: false) ..addBook( title: 'The Lathe of Heaven', authorName: 'Ursula K. Le Guin', isPopular: false, isNew: false); /// A library that contains books and authors. class Library { /// The books in the library. final List<Book> allBooks = <Book>[]; /// The authors in the library. final List<Author> allAuthors = <Author>[]; /// Adds a book into the library. void addBook({ required String title, required String authorName, required bool isPopular, required bool isNew, }) { final Author author = allAuthors.firstWhere( (Author author) => author.name == authorName, orElse: () { final Author value = Author(id: allAuthors.length, name: authorName); allAuthors.add(value); return value; }, ); final Book book = Book( id: allBooks.length, title: title, isPopular: isPopular, isNew: isNew, author: author, ); author.books.add(book); allBooks.add(book); } /// The list of popular books in the library. List<Book> get popularBooks => <Book>[ ...allBooks.where((Book book) => book.isPopular), ]; /// The list of new books in the library. List<Book> get newBooks => <Book>[ ...allBooks.where((Book book) => book.isNew), ]; }
packages/packages/go_router/example/lib/books/src/data/library.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/data/library.dart", "repo_id": "packages", "token_count": 753 }
963
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() => runApp(App()); /// The main app. class App extends StatelessWidget { /// Creates an [App]. App({super.key}); /// The title of the app. static const String title = 'GoRouter Example: Custom Error Screen'; @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, title: title, ); final GoRouter _router = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/page2', builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), ], errorBuilder: (BuildContext context, GoRouterState state) => ErrorScreen(state.error!), ); } /// 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.go('/page2'), 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.go('/'), child: const Text('Go to home page'), ), ], ), ), ); } /// The screen of the error page. class ErrorScreen extends StatelessWidget { /// Creates an [ErrorScreen]. const ErrorScreen(this.error, {super.key}); /// The error to display. final Exception error; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('My "Page Not Found" Screen')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SelectableText(error.toString()), TextButton( onPressed: () => context.go('/'), child: const Text('Home'), ), ], ), ), ); }
packages/packages/go_router/example/lib/others/error_screen.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/error_screen.dart", "repo_id": "packages", "token_count": 1294 }
964
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; /// To use a custom transition animation, provide a `pageBuilder` with a /// CustomTransitionPage. /// /// To learn more about animation in Flutter, check out the [Introduction to /// animations](https://docs.flutter.dev/development/ui/animations) page on /// flutter.dev. void main() => runApp(const MyApp()); /// The route configuration. final GoRouter _router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const HomeScreen(); }, routes: <RouteBase>[ GoRoute( path: 'details', pageBuilder: (BuildContext context, GoRouterState state) { return CustomTransitionPage<void>( key: state.pageKey, child: const DetailsScreen(), transitionDuration: const Duration(milliseconds: 150), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { // Change the opacity of the screen using a Curve based on the the animation's // value return FadeTransition( opacity: CurveTween(curve: Curves.easeInOut).animate(animation), child: child, ); }, ); }, ), GoRoute( path: 'dismissible-details', pageBuilder: (BuildContext context, GoRouterState state) { return CustomTransitionPage<void>( key: state.pageKey, child: const DismissibleDetails(), barrierDismissible: true, barrierColor: Colors.black38, opaque: false, transitionDuration: Duration.zero, transitionsBuilder: (_, __, ___, Widget child) => child, ); }, ), GoRoute( path: 'custom-reverse-transition-duration', pageBuilder: (BuildContext context, GoRouterState state) { return CustomTransitionPage<void>( key: state.pageKey, child: const DetailsScreen(), barrierDismissible: true, barrierColor: Colors.black38, opaque: false, transitionDuration: const Duration(milliseconds: 500), reverseTransitionDuration: const Duration(milliseconds: 200), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return FadeTransition( opacity: animation, child: child, ); }, ); }, ), ], ), ], ); /// The main app. class MyApp extends StatelessWidget { /// Constructs a [MyApp] const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: _router, ); } } /// The home screen class HomeScreen extends StatelessWidget { /// Constructs a [HomeScreen] const HomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Home Screen')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/details'), child: const Text('Go to the Details screen'), ), const SizedBox(height: 48), ElevatedButton( onPressed: () => context.go('/dismissible-details'), child: const Text('Go to the Dismissible Details screen'), ), const SizedBox(height: 48), ElevatedButton( onPressed: () => context.go('/custom-reverse-transition-duration'), child: const Text( 'Go to the Custom Reverse Transition Duration Screen', ), ), ], ), ), ); } } /// The details screen class DetailsScreen extends StatelessWidget { /// Constructs a [DetailsScreen] const DetailsScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Details Screen')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/'), child: const Text('Go back to the Home screen'), ), ], ), ), ); } } /// The dismissible details screen class DismissibleDetails extends StatelessWidget { /// Constructs a [DismissibleDetails] const DismissibleDetails({super.key}); @override Widget build(BuildContext context) { return const Padding( padding: EdgeInsets.all(48), child: ColoredBox(color: Colors.red), ); } }
packages/packages/go_router/example/lib/transition_animations.dart/0
{ "file_path": "packages/packages/go_router/example/lib/transition_animations.dart", "repo_id": "packages", "token_count": 2441 }
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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_examples/on_exit.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(const example.MyApp()); await tester.tap(find.text('Go to the Details screen')); await tester.pumpAndSettle(); await tester.tap(find.byType(BackButton)); await tester.pumpAndSettle(); expect(find.text('Are you sure to leave this page?'), findsOneWidget); await tester.tap(find.text('Cancel')); await tester.pumpAndSettle(); expect(find.byType(example.DetailsScreen), findsOneWidget); await tester.tap(find.byType(BackButton)); await tester.pumpAndSettle(); expect(find.text('Are you sure to leave this page?'), findsOneWidget); await tester.tap(find.text('Confirm')); await tester.pumpAndSettle(); expect(find.byType(example.HomeScreen), findsOneWidget); }); }
packages/packages/go_router/example/test/on_exit_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/on_exit_test.dart", "repo_id": "packages", "token_count": 393 }
966
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'builder.dart'; import 'configuration.dart'; import 'match.dart'; import 'misc/errors.dart'; import 'route.dart'; /// GoRouter implementation of [RouterDelegate]. class GoRouterDelegate extends RouterDelegate<RouteMatchList> with ChangeNotifier { /// Constructor for GoRouter's implementation of the RouterDelegate base /// class. GoRouterDelegate({ required RouteConfiguration configuration, required GoRouterBuilderWithNav builderWithNav, required GoRouterPageBuilder? errorPageBuilder, required GoRouterWidgetBuilder? errorBuilder, required List<NavigatorObserver> observers, required this.routerNeglect, String? restorationScopeId, bool requestFocus = true, }) : _configuration = configuration { builder = RouteBuilder( configuration: configuration, builderWithNav: builderWithNav, errorPageBuilder: errorPageBuilder, errorBuilder: errorBuilder, restorationScopeId: restorationScopeId, observers: observers, onPopPageWithRouteMatch: _handlePopPageWithRouteMatch, requestFocus: requestFocus, ); } /// Builds the top-level Navigator given a configuration and location. @visibleForTesting late final RouteBuilder builder; /// Set to true to disable creating history entries on the web. final bool routerNeglect; final RouteConfiguration _configuration; @override Future<bool> popRoute() async { NavigatorState? state = navigatorKey.currentState; if (state == null) { return false; } if (!state.canPop()) { state = null; } RouteMatchBase walker = currentConfiguration.matches.last; while (walker is ShellRouteMatch) { if (walker.navigatorKey.currentState?.canPop() ?? false) { state = walker.navigatorKey.currentState; } walker = walker.matches.last; } if (state != null) { return state.maybePop(); } // This should be the only place where the last GoRoute exit the screen. final GoRoute lastRoute = currentConfiguration.last.route; if (lastRoute.onExit != null && navigatorKey.currentContext != null) { return !(await lastRoute.onExit!(navigatorKey.currentContext!)); } return false; } /// Returns `true` if the active Navigator can pop. bool canPop() { if (navigatorKey.currentState?.canPop() ?? false) { return true; } RouteMatchBase walker = currentConfiguration.matches.last; while (walker is ShellRouteMatch) { if (walker.navigatorKey.currentState?.canPop() ?? false) { return true; } walker = walker.matches.last; } return false; } /// Pops the top-most route. void pop<T extends Object?>([T? result]) { NavigatorState? state; if (navigatorKey.currentState?.canPop() ?? false) { state = navigatorKey.currentState; } RouteMatchBase walker = currentConfiguration.matches.last; while (walker is ShellRouteMatch) { if (walker.navigatorKey.currentState?.canPop() ?? false) { state = walker.navigatorKey.currentState; } walker = walker.matches.last; } if (state == null) { throw GoError('There is nothing to pop'); } state.pop(result); } void _debugAssertMatchListNotEmpty() { assert( currentConfiguration.isNotEmpty, 'You have popped the last page off of the stack,' ' there are no pages left to show', ); } bool _handlePopPageWithRouteMatch( Route<Object?> route, Object? result, RouteMatchBase match) { if (route.willHandlePopInternally) { final bool popped = route.didPop(result); assert(!popped); return popped; } final RouteBase routeBase = match.route; if (routeBase is! GoRoute || routeBase.onExit == null) { route.didPop(result); _completeRouteMatch(result, match); return true; } // The _handlePopPageWithRouteMatch is called during draw frame, schedule // a microtask in case the onExit callback want to launch dialog or other // navigator operations. scheduleMicrotask(() async { final bool onExitResult = await routeBase.onExit!(navigatorKey.currentContext!); if (onExitResult) { _completeRouteMatch(result, match); } }); return false; } void _completeRouteMatch(Object? result, RouteMatchBase match) { if (match is ImperativeRouteMatch) { match.complete(result); } currentConfiguration = currentConfiguration.remove(match); notifyListeners(); assert(() { _debugAssertMatchListNotEmpty(); return true; }()); } /// For use by the Router architecture as part of the RouterDelegate. GlobalKey<NavigatorState> get navigatorKey => _configuration.navigatorKey; /// For use by the Router architecture as part of the RouterDelegate. @override RouteMatchList currentConfiguration = RouteMatchList.empty; /// For use by the Router architecture as part of the RouterDelegate. @override Widget build(BuildContext context) { return builder.build( context, currentConfiguration, routerNeglect, ); } /// For use by the Router architecture as part of the RouterDelegate. // This class avoids using async to make sure the route is processed // synchronously if possible. @override Future<void> setNewRoutePath(RouteMatchList configuration) { if (currentConfiguration == configuration) { return SynchronousFuture<void>(null); } assert(configuration.isNotEmpty || configuration.isError); final BuildContext? navigatorContext = navigatorKey.currentContext; // If navigator is not built or disposed, the GoRoute.onExit is irrelevant. if (navigatorContext != null) { final List<RouteMatch> currentGoRouteMatches = <RouteMatch>[]; currentConfiguration.visitRouteMatches((RouteMatchBase match) { if (match is RouteMatch) { currentGoRouteMatches.add(match); } return true; }); final List<RouteMatch> newGoRouteMatches = <RouteMatch>[]; configuration.visitRouteMatches((RouteMatchBase match) { if (match is RouteMatch) { newGoRouteMatches.add(match); } return true; }); final int compareUntil = math.min( currentGoRouteMatches.length, newGoRouteMatches.length, ); int indexOfFirstDiff = 0; for (; indexOfFirstDiff < compareUntil; indexOfFirstDiff++) { if (currentGoRouteMatches[indexOfFirstDiff] != newGoRouteMatches[indexOfFirstDiff]) { break; } } if (indexOfFirstDiff < currentGoRouteMatches.length) { final List<GoRoute> exitingGoRoutes = currentGoRouteMatches .sublist(indexOfFirstDiff) .map<RouteBase>((RouteMatch match) => match.route) .whereType<GoRoute>() .toList(); return _callOnExitStartsAt(exitingGoRoutes.length - 1, context: navigatorContext, routes: exitingGoRoutes) .then<void>((bool exit) { if (!exit) { return SynchronousFuture<void>(null); } return _setCurrentConfiguration(configuration); }); } } return _setCurrentConfiguration(configuration); } /// Calls [GoRoute.onExit] starting from the index /// /// The returned future resolves to true if all routes below the index all /// return true. Otherwise, the returned future resolves to false. static Future<bool> _callOnExitStartsAt(int index, {required BuildContext context, required List<GoRoute> routes}) { if (index < 0) { return SynchronousFuture<bool>(true); } final GoRoute goRoute = routes[index]; if (goRoute.onExit == null) { return _callOnExitStartsAt(index - 1, context: context, routes: routes); } Future<bool> handleOnExitResult(bool exit) { if (exit) { return _callOnExitStartsAt(index - 1, context: context, routes: routes); } return SynchronousFuture<bool>(false); } final FutureOr<bool> exitFuture = goRoute.onExit!(context); if (exitFuture is bool) { return handleOnExitResult(exitFuture); } return exitFuture.then<bool>(handleOnExitResult); } Future<void> _setCurrentConfiguration(RouteMatchList configuration) { currentConfiguration = configuration; notifyListeners(); return SynchronousFuture<void>(null); } }
packages/packages/go_router/lib/src/delegate.dart/0
{ "file_path": "packages/packages/go_router/lib/src/delegate.dart", "repo_id": "packages", "token_count": 3122 }
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/widgets.dart'; import 'package:meta/meta.dart'; import 'configuration.dart'; import 'misc/errors.dart'; import 'route.dart'; /// The route state during routing. /// /// The state contains parsed artifacts of the current URI. @immutable class GoRouterState { /// Default constructor for creating route state during routing. const GoRouterState( this._configuration, { required this.uri, required this.matchedLocation, this.name, this.path, required this.fullPath, required this.pathParameters, this.extra, this.error, required this.pageKey, this.topRoute, }); final RouteConfiguration _configuration; /// The full uri of the route, e.g. /family/f2/person/p1?filter=name#fragment final Uri uri; /// The matched location until this point. /// /// For example: /// /// location = /family/f2/person/p1 /// route = GoRoute('/family/:id') /// /// matchedLocation = /family/f2 final String matchedLocation; /// The optional name of the route associated with this app. /// /// This can be null for GoRouterState pass into top level redirect. final String? name; /// The path of the route associated with this app. e.g. family/:fid /// /// This can be null for GoRouterState pass into top level redirect. final String? path; /// The full path to this sub-route, e.g. /family/:fid /// /// For top level redirect, this is the entire path that matches the location. /// It can be empty if go router can't find a match. In that case, the [error] /// contains more information. final String? fullPath; /// The parameters for this match, e.g. {'fid': 'f2'} final Map<String, String> pathParameters; /// An extra object to pass along with the navigation. final Object? extra; /// The error associated with this sub-route. final GoException? error; /// A unique string key for this sub-route. /// E.g. /// ```dart /// ValueKey('/family/:fid') /// ``` final ValueKey<String> pageKey; /// The current matched top route associated with this state. /// /// If this state represents a [ShellRoute], the top [GoRoute] will be the current /// matched location associated with the [ShellRoute]. This allows the [ShellRoute]'s /// associated GoRouterState to be uniquely identified using [GoRoute.name] final GoRoute? topRoute; /// Gets the [GoRouterState] from context. /// /// The returned [GoRouterState] will depends on which [GoRoute] or /// [ShellRoute] the input `context` is in. /// /// This method only supports [GoRoute] and [ShellRoute] that generate /// [ModalRoute]s. This is typically the case if one uses [GoRoute.builder], /// [ShellRoute.builder], [CupertinoPage], [MaterialPage], /// [CustomTransitionPage], or [NoTransitionPage]. /// /// This method is fine to be called during [GoRoute.builder] or /// [ShellRoute.builder]. /// /// This method cannot be called during [GoRoute.pageBuilder] or /// [ShellRoute.pageBuilder] since there is no [GoRouterState] to be /// associated with. /// /// To access GoRouterState from a widget. /// /// ``` /// GoRoute( /// path: '/:id' /// builder: (_, __) => MyWidget(), /// ); /// /// class MyWidget extends StatelessWidget { /// @override /// Widget build(BuildContext context) { /// return Text('${GoRouterState.of(context).pathParameters['id']}'); /// } /// } /// ``` static GoRouterState of(BuildContext context) { final ModalRoute<Object?>? route = ModalRoute.of(context); if (route == null) { throw GoError('There is no modal route above the current context.'); } final RouteSettings settings = route.settings; if (settings is! Page<Object?>) { throw GoError( 'The parent route must be a page route to have a GoRouterState'); } final GoRouterStateRegistryScope? scope = context .dependOnInheritedWidgetOfExactType<GoRouterStateRegistryScope>(); if (scope == null) { throw GoError( 'There is no GoRouterStateRegistryScope above the current context.'); } final GoRouterState state = scope.notifier!._createPageRouteAssociation(settings, route); return state; } /// Get a location from route name and parameters. /// This is useful for redirecting to a named location. String namedLocation( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, String> queryParameters = const <String, String>{}, }) { return _configuration.namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters); } @override bool operator ==(Object other) { return other is GoRouterState && other.uri == uri && other.matchedLocation == matchedLocation && other.name == name && other.path == path && other.fullPath == fullPath && other.pathParameters == pathParameters && other.extra == extra && other.error == error && other.pageKey == pageKey; } @override int get hashCode => Object.hash( uri, matchedLocation, name, path, fullPath, pathParameters, extra, error, pageKey, ); } /// An inherited widget to host a [GoRouterStateRegistry] for the subtree. /// /// Should not be used directly, consider using [GoRouterState.of] to access /// [GoRouterState] from the context. @internal class GoRouterStateRegistryScope extends InheritedNotifier<GoRouterStateRegistry> { /// Creates a GoRouterStateRegistryScope. const GoRouterStateRegistryScope({ super.key, required GoRouterStateRegistry registry, required super.child, }) : super(notifier: registry); } /// A registry to record [GoRouterState] to [Page] relation. /// /// Should not be used directly, consider using [GoRouterState.of] to access /// [GoRouterState] from the context. @internal class GoRouterStateRegistry extends ChangeNotifier { /// creates a [GoRouterStateRegistry]. GoRouterStateRegistry(); /// A [Map] that maps a [Page] to a [GoRouterState]. @visibleForTesting final Map<Page<Object?>, GoRouterState> registry = <Page<Object?>, GoRouterState>{}; final Map<Route<Object?>, Page<Object?>> _routePageAssociation = <ModalRoute<Object?>, Page<Object?>>{}; GoRouterState _createPageRouteAssociation( Page<Object?> page, ModalRoute<Object?> route) { assert(route.settings == page); assert(registry.containsKey(page)); final Page<Object?>? oldPage = _routePageAssociation[route]; if (oldPage == null) { // This is a new association. _routePageAssociation[route] = page; // If there is an association, the registry relies on the route to remove // entry from registry because it wants to preserve the GoRouterState // until the route finishes the popping animations. route.completed.then<void>((Object? result) { // Can't use `page` directly because Route.settings may have changed during // the lifetime of this route. final Page<Object?> associatedPage = _routePageAssociation.remove(route)!; assert(registry.containsKey(associatedPage)); registry.remove(associatedPage); }); } else if (oldPage != page) { // Need to update the association to avoid memory leak. _routePageAssociation[route] = page; assert(registry.containsKey(oldPage)); registry.remove(oldPage); } assert(_routePageAssociation[route] == page); return registry[page]!; } /// Updates this registry with new records. void updateRegistry(Map<Page<Object?>, GoRouterState> newRegistry) { bool shouldNotify = false; final Set<Page<Object?>> pagesWithAssociation = _routePageAssociation.values.toSet(); for (final MapEntry<Page<Object?>, GoRouterState> entry in newRegistry.entries) { final GoRouterState? existingState = registry[entry.key]; if (existingState != null) { if (existingState != entry.value) { shouldNotify = shouldNotify || pagesWithAssociation.contains(entry.key); registry[entry.key] = entry.value; } continue; } // Not in the _registry. registry[entry.key] = entry.value; // Adding or removing registry does not need to notify the listen since // no one should be depending on them. } registry.removeWhere((Page<Object?> key, GoRouterState value) { if (newRegistry.containsKey(key)) { return false; } // For those that have page route association, it will be removed by the // route future. Need to notify the listener so they can update the page // route association if its page has changed. if (pagesWithAssociation.contains(key)) { shouldNotify = true; return false; } return true; }); if (shouldNotify) { notifyListeners(); } } }
packages/packages/go_router/lib/src/state.dart/0
{ "file_path": "packages/packages/go_router/lib/src/state.dart", "repo_id": "packages", "token_count": 3144 }
968