text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('PostGridTileBlock', () { test('can be (de)serialized', () { final block = PostGridTileBlock( id: 'id', category: PostCategory.science, author: 'author', publishedAt: DateTime(2022, 3, 12), imageUrl: 'imageUrl', title: 'title', ); expect(PostGridTileBlock.fromJson(block.toJson()), equals(block)); }); group('PostGridTitleBlockExt', () { const id = 'id'; const category = PostCategory.science; const author = 'author'; final publishedAt = DateTime(2022, 3, 12); const imageUrl = 'imageUrl'; const title = 'title'; const description = 'description'; const action = NavigateToArticleAction(articleId: id); final gridTile = PostGridTileBlock( id: id, category: category, author: author, publishedAt: publishedAt, imageUrl: imageUrl, title: title, description: description, action: action, ); test('toPostLargeBlock creates PostLargeBlock instance', () { final largeBlock = PostLargeBlock( id: id, category: category, author: author, publishedAt: publishedAt, imageUrl: imageUrl, title: title, isContentOverlaid: true, description: description, action: action, ); expect(gridTile.toPostLargeBlock(), equals(largeBlock)); }); test('toPostMediumBlock creates PostMediumBlock instance', () { final mediumBlock = PostMediumBlock( id: id, category: category, author: author, publishedAt: publishedAt, imageUrl: imageUrl, title: title, isContentOverlaid: true, description: description, action: action, ); expect(gridTile.toPostMediumBlock(), equals(mediumBlock)); }); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_grid_tile_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_grid_tile_block_test.dart", "repo_id": "news_toolkit", "token_count": 885 }
920
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('VideoIntroductionBlock', () { test('can be (de)serialized', () { final block = VideoIntroductionBlock( category: PostCategory.technology, title: 'title', videoUrl: 'videoUrl', ); expect(VideoIntroductionBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/video_intro_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/video_intro_block_test.dart", "repo_id": "news_toolkit", "token_count": 175 }
921
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; import '../../../../routes/api/v1/articles/[id]/related.dart' as route; class _MockNewsDataSource extends Mock implements NewsDataSource {} class _MockRequestContext extends Mock implements RequestContext {} class _MockRelatedArticles extends Mock implements RelatedArticles {} void main() { const id = '__test_article_id__'; group('GET /api/v1/articles/<id>/related', () { late NewsDataSource newsDataSource; setUp(() { newsDataSource = _MockNewsDataSource(); }); test('returns a 200 on success', () async { final blocks = <NewsBlock>[]; final relatedArticles = _MockRelatedArticles(); when(() => relatedArticles.blocks).thenReturn(blocks); when(() => relatedArticles.totalBlocks).thenReturn(blocks.length); when( () => newsDataSource.getRelatedArticles( id: any(named: 'id'), limit: any(named: 'limit'), offset: any(named: 'offset'), ), ).thenAnswer((_) async => relatedArticles); final expected = RelatedArticlesResponse( relatedArticles: blocks, totalCount: blocks.length, ); 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, id); expect(response.statusCode, equals(HttpStatus.ok)); expect(await response.json(), equals(expected.toJson())); }); test('parses limit and offset correctly', () async { const limit = 42; const offset = 7; final blocks = <NewsBlock>[]; final relatedArticles = _MockRelatedArticles(); when(() => relatedArticles.blocks).thenReturn(blocks); when(() => relatedArticles.totalBlocks).thenReturn(blocks.length); when( () => newsDataSource.getRelatedArticles( id: any(named: 'id'), limit: any(named: 'limit'), offset: any(named: 'offset'), ), ).thenAnswer((_) async => relatedArticles); final expected = RelatedArticlesResponse( relatedArticles: blocks, totalCount: blocks.length, ); final request = Request( 'GET', Uri.parse('http://127.0.0.1/').replace( queryParameters: <String, String>{ 'limit': '$limit', 'offset': '$offset', }, ), ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.ok)); expect(await response.json(), equals(expected.toJson())); verify( () => newsDataSource.getRelatedArticles( id: id, limit: limit, offset: offset, ), ).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, id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }
news_toolkit/flutter_news_example/api/test/routes/articles/[id]/related_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/articles/[id]/related_test.dart", "repo_id": "news_toolkit", "token_count": 1408 }
922
targets: $default: builders: json_serializable: options: explicit_to_json: true
news_toolkit/flutter_news_example/build.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/build.yaml", "repo_id": "news_toolkit", "token_count": 54 }
923
import 'package:ads_consent_client/ads_consent_client.dart'; import 'package:analytics_repository/analytics_repository.dart'; import 'package:app_ui/app_ui.dart'; import 'package:article_repository/article_repository.dart'; import 'package:flow_builder/flow_builder.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/ads/ads.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/login/login.dart' hide LoginEvent; import 'package:flutter_news_example/theme_selector/theme_selector.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart' as ads; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:news_repository/news_repository.dart'; import 'package:notifications_repository/notifications_repository.dart'; import 'package:platform/platform.dart'; import 'package:user_repository/user_repository.dart'; class App extends StatelessWidget { const App({ required UserRepository userRepository, required NewsRepository newsRepository, required NotificationsRepository notificationsRepository, required ArticleRepository articleRepository, required InAppPurchaseRepository inAppPurchaseRepository, required AnalyticsRepository analyticsRepository, required AdsConsentClient adsConsentClient, required User user, super.key, }) : _userRepository = userRepository, _newsRepository = newsRepository, _notificationsRepository = notificationsRepository, _articleRepository = articleRepository, _inAppPurchaseRepository = inAppPurchaseRepository, _analyticsRepository = analyticsRepository, _adsConsentClient = adsConsentClient, _user = user; final UserRepository _userRepository; final NewsRepository _newsRepository; final NotificationsRepository _notificationsRepository; final ArticleRepository _articleRepository; final InAppPurchaseRepository _inAppPurchaseRepository; final AnalyticsRepository _analyticsRepository; final AdsConsentClient _adsConsentClient; final User _user; @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [ RepositoryProvider.value(value: _userRepository), RepositoryProvider.value(value: _newsRepository), RepositoryProvider.value(value: _notificationsRepository), RepositoryProvider.value(value: _articleRepository), RepositoryProvider.value(value: _analyticsRepository), RepositoryProvider.value(value: _inAppPurchaseRepository), RepositoryProvider.value(value: _adsConsentClient), ], child: MultiBlocProvider( providers: [ BlocProvider( create: (_) => AppBloc( userRepository: _userRepository, notificationsRepository: _notificationsRepository, user: _user, )..add(const AppOpened()), ), BlocProvider(create: (_) => ThemeModeBloc()), BlocProvider( create: (_) => LoginWithEmailLinkBloc( userRepository: _userRepository, ), lazy: false, ), BlocProvider( create: (context) => AnalyticsBloc( analyticsRepository: _analyticsRepository, userRepository: _userRepository, ), lazy: false, ), BlocProvider( create: (context) => FullScreenAdsBloc( interstitialAdLoader: ads.InterstitialAd.load, rewardedAdLoader: ads.RewardedAd.load, adsRetryPolicy: const AdsRetryPolicy(), localPlatform: const LocalPlatform(), ) ..add(const LoadInterstitialAdRequested()) ..add(const LoadRewardedAdRequested()), lazy: false, ), ], child: const AppView(), ), ); } } class AppView extends StatelessWidget { const AppView({super.key}); @override Widget build(BuildContext context) { return MaterialApp( themeMode: ThemeMode.light, theme: const AppTheme().themeData, darkTheme: const AppDarkTheme().themeData, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: AuthenticatedUserListener( child: FlowBuilder<AppStatus>( state: context.select((AppBloc bloc) => bloc.state.status), onGeneratePages: onGenerateAppViewPages, ), ), ); } }
news_toolkit/flutter_news_example/lib/app/view/app.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/app/view/app.dart", "repo_id": "news_toolkit", "token_count": 1858 }
924
export 'article_comments.dart'; export 'article_content.dart'; export 'article_content_item.dart'; export 'article_content_loader_item.dart'; export 'article_theme_override.dart'; export 'article_trailing_content.dart';
news_toolkit/flutter_news_example/lib/article/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/article/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 72 }
925
import 'package:flutter/material.dart' hide Spacer; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/newsletter/newsletter.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; class CategoryFeedItem extends StatelessWidget { const CategoryFeedItem({required this.block, super.key}); /// The associated [NewsBlock] instance. final NewsBlock block; @override Widget build(BuildContext context) { final newsBlock = block; final isUserSubscribed = context.select((AppBloc bloc) => bloc.state.isUserSubscribed); late Widget widget; if (newsBlock is DividerHorizontalBlock) { widget = DividerHorizontal(block: newsBlock); } else if (newsBlock is SpacerBlock) { widget = Spacer(block: newsBlock); } else if (newsBlock is SectionHeaderBlock) { widget = SectionHeader( block: newsBlock, onPressed: (action) => _onFeedItemAction(context, action), ); } else if (newsBlock is PostLargeBlock) { widget = PostLarge( block: newsBlock, premiumText: context.l10n.newsBlockPremiumText, isLocked: newsBlock.isPremium && !isUserSubscribed, onPressed: (action) => _onFeedItemAction(context, action), ); } else if (newsBlock is PostMediumBlock) { widget = PostMedium( block: newsBlock, onPressed: (action) => _onFeedItemAction(context, action), ); } else if (newsBlock is PostSmallBlock) { widget = PostSmall( block: newsBlock, onPressed: (action) => _onFeedItemAction(context, action), ); } else if (newsBlock is PostGridGroupBlock) { widget = PostGrid( gridGroupBlock: newsBlock, premiumText: context.l10n.newsBlockPremiumText, onPressed: (action) => _onFeedItemAction(context, action), ); } else if (newsBlock is NewsletterBlock) { widget = const Newsletter(); } else if (newsBlock is BannerAdBlock) { widget = BannerAd( block: newsBlock, adFailedToLoadTitle: context.l10n.adLoadFailure, ); } else { // Render an empty widget for the unsupported block type. widget = const SizedBox(); } return (newsBlock is! PostGridGroupBlock) ? SliverToBoxAdapter(child: widget) : widget; } /// Handles actions triggered by tapping on feed items. Future<void> _onFeedItemAction( BuildContext context, BlockAction action, ) async { if (action is NavigateToArticleAction) { await Navigator.of(context).push<void>( ArticlePage.route(id: action.articleId), ); } else if (action is NavigateToVideoArticleAction) { await Navigator.of(context).push<void>( ArticlePage.route(id: action.articleId, isVideoArticle: true), ); } else if (action is NavigateToFeedCategoryAction) { context .read<CategoriesBloc>() .add(CategorySelected(category: action.category)); } } }
news_toolkit/flutter_news_example/lib/feed/widgets/category_feed_item.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/feed/widgets/category_feed_item.dart", "repo_id": "news_toolkit", "token_count": 1235 }
926
part of 'login_with_email_link_bloc.dart'; enum LoginWithEmailLinkStatus { initial, loading, success, failure, } class LoginWithEmailLinkState extends Equatable { const LoginWithEmailLinkState({ this.status = LoginWithEmailLinkStatus.initial, }); final LoginWithEmailLinkStatus status; @override List<Object> get props => [status]; LoginWithEmailLinkState copyWith({ LoginWithEmailLinkStatus? status, }) { return LoginWithEmailLinkState( status: status ?? this.status, ); } }
news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_state.dart", "repo_id": "news_toolkit", "token_count": 173 }
927
part of 'notification_preferences_bloc.dart'; abstract class NotificationPreferencesEvent extends Equatable { const NotificationPreferencesEvent(); } class CategoriesPreferenceToggled extends NotificationPreferencesEvent { const CategoriesPreferenceToggled({required this.category}); final Category category; @override List<Object?> get props => [category]; } class InitialCategoriesPreferencesRequested extends NotificationPreferencesEvent { @override List<Object?> get props => []; }
news_toolkit/flutter_news_example/lib/notification_preferences/bloc/notification_preferences_event.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/bloc/notification_preferences_event.dart", "repo_id": "news_toolkit", "token_count": 134 }
928
import 'dart:async'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_repository/news_repository.dart'; import 'package:stream_transform/stream_transform.dart'; part 'search_event.dart'; part 'search_state.dart'; const _duration = Duration(milliseconds: 300); EventTransformer<Event> restartableDebounce<Event>( Duration duration, { required bool Function(Event) isDebounced, }) { return (events, mapper) { final debouncedEvents = events.where(isDebounced).debounce(duration); final otherEvents = events.where((event) => !isDebounced(event)); return otherEvents.merge(debouncedEvents).switchMap(mapper); }; } class SearchBloc extends Bloc<SearchEvent, SearchState> { SearchBloc({ required NewsRepository newsRepository, }) : _newsRepository = newsRepository, super(const SearchState.initial()) { on<SearchTermChanged>( (event, emit) async { event.searchTerm.isEmpty ? await _onEmptySearchRequested(event, emit) : await _onSearchTermChanged(event, emit); }, transformer: restartableDebounce( _duration, isDebounced: (event) => event.searchTerm.isNotEmpty, ), ); } final NewsRepository _newsRepository; FutureOr<void> _onEmptySearchRequested( SearchTermChanged event, Emitter<SearchState> emit, ) async { emit( state.copyWith( status: SearchStatus.loading, searchType: SearchType.popular, ), ); try { final popularSearch = await _newsRepository.popularSearch(); emit( state.copyWith( articles: popularSearch.articles, topics: popularSearch.topics, status: SearchStatus.populated, ), ); } catch (error, stackTrace) { emit(state.copyWith(status: SearchStatus.failure)); addError(error, stackTrace); } } FutureOr<void> _onSearchTermChanged( SearchTermChanged event, Emitter<SearchState> emit, ) async { emit( state.copyWith( status: SearchStatus.loading, searchType: SearchType.relevant, ), ); try { final relevantSearch = await _newsRepository.relevantSearch( term: event.searchTerm, ); emit( state.copyWith( articles: relevantSearch.articles, topics: relevantSearch.topics, status: SearchStatus.populated, ), ); } catch (error, stackTrace) { emit(state.copyWith(status: SearchStatus.failure)); addError(error, stackTrace); } } }
news_toolkit/flutter_news_example/lib/search/bloc/search_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/bloc/search_bloc.dart", "repo_id": "news_toolkit", "token_count": 1051 }
929
part of 'subscriptions_bloc.dart'; abstract class SubscriptionsEvent extends Equatable {} class SubscriptionsRequested extends SubscriptionsEvent { SubscriptionsRequested(); @override List<Object> get props => []; } class SubscriptionPurchaseRequested extends SubscriptionsEvent { SubscriptionPurchaseRequested({required this.subscription}); final Subscription subscription; @override List<Object> get props => [subscription]; } class SubscriptionPurchaseCompleted extends SubscriptionsEvent { SubscriptionPurchaseCompleted({required this.subscription}); final Subscription subscription; @override List<Object> get props => [subscription]; } class SubscriptionPurchaseUpdated extends SubscriptionsEvent { SubscriptionPurchaseUpdated({required this.purchase}); final PurchaseUpdate purchase; @override List<Object> get props => [purchase]; }
news_toolkit/flutter_news_example/lib/subscriptions/dialog/bloc/subscriptions_event.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/dialog/bloc/subscriptions_event.dart", "repo_id": "news_toolkit", "token_count": 227 }
930
import 'package:flutter/material.dart'; part '../terms_of_service_mock_text.dart'; @visibleForTesting class TermsOfServiceBody extends StatelessWidget { const TermsOfServiceBody({ super.key, this.contentPadding = EdgeInsets.zero, }); final EdgeInsets contentPadding; @override Widget build(BuildContext context) { return Flexible( child: SingleChildScrollView( child: Padding( padding: contentPadding, child: const Text( termsOfServiceMockText, key: Key('termsOfServiceBody_text'), ), ), ), ); } }
news_toolkit/flutter_news_example/lib/terms_of_service/widgets/terms_of_service_body.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/terms_of_service/widgets/terms_of_service_body.dart", "repo_id": "news_toolkit", "token_count": 254 }
931
# ads_consent_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A client that handles requesting ads consent on a device. [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/ads_consent_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/ads_consent_client/README.md", "repo_id": "news_toolkit", "token_count": 173 }
932
# Flutter News Example UI A UI Toolkit for Flutter News
news_toolkit/flutter_news_example/packages/app_ui/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/README.md", "repo_id": "news_toolkit", "token_count": 17 }
933
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class ColorsPage extends StatelessWidget { const ColorsPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const ColorsPage()); } @override Widget build(BuildContext context) { const colorItems = [ _ColorItem(name: 'Secondary', color: AppColors.secondary), _ColorItem(name: 'Black', color: AppColors.black), _ColorItem(name: 'Black Light', color: AppColors.lightBlack), _ColorItem( name: 'Medium Emphasis', color: AppColors.mediumEmphasisSurface, ), _ColorItem(name: 'White', color: AppColors.white), _ColorItem(name: 'Modal Background', color: AppColors.modalBackground), _ColorItem(name: 'Transparent', color: AppColors.transparent), _ColorItem(name: 'Blue', color: AppColors.blue), _ColorItem(name: 'Sky Blue', color: AppColors.skyBlue), _ColorItem(name: 'Ocean Blue', color: AppColors.oceanBlue), _ColorItem(name: 'Light Blue', color: AppColors.lightBlue), _ColorItem(name: 'Blue Dress', color: AppColors.blueDress), _ColorItem(name: 'Crystal Blue', color: AppColors.crystalBlue), _ColorItem(name: 'Yellow', color: AppColors.yellow), _ColorItem(name: 'Red', color: AppColors.red), _ColorItem(name: 'Red Wine', color: AppColors.redWine), _ColorItem(name: 'Grey', color: AppColors.grey), _ColorItem(name: 'Liver', color: AppColors.liver), _ColorItem(name: 'Surface 2', color: AppColors.surface2), _ColorItem(name: 'Input Enabled', color: AppColors.inputEnabled), _ColorItem(name: 'Input Hover', color: AppColors.inputHover), _ColorItem(name: 'Input Focused', color: AppColors.inputFocused), _ColorItem(name: 'Pastel Grey', color: AppColors.pastelGrey), _ColorItem(name: 'Bright Grey', color: AppColors.brightGrey), _ColorItem(name: 'Pale Sky', color: AppColors.paleSky), _ColorItem(name: 'Green', color: AppColors.green), _ColorItem(name: 'Rangoon Green', color: AppColors.rangoonGreen), _ColorItem(name: 'Teal', color: AppColors.teal), _ColorItem(name: 'Dark Aqua', color: AppColors.darkAqua), _ColorItem(name: 'Eerie Black', color: AppColors.eerieBlack), _ColorItem(name: 'Gainsboro', color: AppColors.gainsboro), _ColorItem(name: 'Orange', color: AppColors.orange), _ColorItem(name: 'Outline Light', color: AppColors.outlineLight), _ColorItem(name: 'Outline On Dark', color: AppColors.outlineOnDark), _ColorItem( name: 'Medium Emphasis Primary', color: AppColors.mediumEmphasisPrimary, ), _ColorItem( name: 'High Emphasis Primary', color: AppColors.highEmphasisPrimary, ), _ColorItem( name: 'Medium High Emphasis Primary', color: AppColors.mediumHighEmphasisPrimary, ), _ColorItem( name: 'Medium High Emphasis Surface', color: AppColors.mediumHighEmphasisSurface, ), _ColorItem( name: 'High Emphasis Surface', color: AppColors.highEmphasisSurface, ), _ColorItem( name: 'Disabled Foreground', color: AppColors.disabledForeground, ), _ColorItem( name: 'Disabled Button', color: AppColors.disabledButton, ), _ColorItem( name: 'Disabled Surface', color: AppColors.disabledSurface, ), ]; return Scaffold( appBar: AppBar(title: const Text('Colors')), body: ListView.builder( scrollDirection: Axis.horizontal, itemCount: colorItems.length, itemBuilder: (_, index) => colorItems[index], ), ); } } class _ColorItem extends StatelessWidget { const _ColorItem({required this.name, required this.color}); final String name; final Color color; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(name), const SizedBox(height: 16), Expanded( child: SingleChildScrollView( child: color is MaterialColor ? _MaterialColorView(color: color as MaterialColor) : _ColorSquare(color: color), ), ), ], ), ); } } class _MaterialColorView extends StatelessWidget { const _MaterialColorView({required this.color}); static const List<int> shades = [ 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, ]; final MaterialColor color; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: shades.map((shade) { return _ColorSquare(color: color[shade]!); }).toList(), ); } } class _ColorSquare extends StatelessWidget { const _ColorSquare({required this.color}); final Color color; TextStyle get textStyle { return TextStyle( color: color.computeLuminance() > 0.5 ? Colors.black : Colors.white, ); } String get hexCode { if (color.value.toRadixString(16).length <= 2) { return '--'; } else { return '#${color.value.toRadixString(16).substring(2).toUpperCase()}'; } } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 2), child: Stack( children: [ SizedBox( width: 100, height: 100, child: DecoratedBox( decoration: BoxDecoration(color: color, border: Border.all()), ), ), Positioned( top: 0, bottom: 0, left: 0, right: 0, child: Center(child: Text(hexCode, style: textStyle)), ), ], ), ); } }
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/colors/colors_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/colors/colors_page.dart", "repo_id": "news_toolkit", "token_count": 2560 }
934
import 'package:flutter/widgets.dart'; /// Namespace for Default App Font Weights abstract class AppFontWeight { /// FontWeight value of `w900` static const FontWeight black = FontWeight.w900; /// FontWeight value of `w800` static const FontWeight extraBold = FontWeight.w800; /// FontWeight value of `w700` static const FontWeight bold = FontWeight.w700; /// FontWeight value of `w600` static const FontWeight semiBold = FontWeight.w600; /// FontWeight value of `w500` static const FontWeight medium = FontWeight.w500; /// FontWeight value of `w400` static const FontWeight regular = FontWeight.w400; /// FontWeight value of `w300` static const FontWeight light = FontWeight.w300; /// FontWeight value of `w200` static const FontWeight extraLight = FontWeight.w200; /// FontWeight value of `w100` static const FontWeight thin = FontWeight.w100; }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/app_font_weight.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/app_font_weight.dart", "repo_id": "news_toolkit", "token_count": 265 }
935
import 'package:app_ui/src/typography/typography.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('AppTextStyles', () { group('UITextStyle', () { test('display2 returns TextStyle', () { expect(UITextStyle.display2, isA<TextStyle>()); }); test('display3 returns TextStyle', () { expect(UITextStyle.display3, isA<TextStyle>()); }); test('headline1 returns TextStyle', () { expect(UITextStyle.headline1, isA<TextStyle>()); }); test('headline2 returns TextStyle', () { expect(UITextStyle.headline2, isA<TextStyle>()); }); test('headline3 returns TextStyle', () { expect(UITextStyle.headline3, isA<TextStyle>()); }); test('headline4 returns TextStyle', () { expect(UITextStyle.headline4, isA<TextStyle>()); }); test('headline5 returns TextStyle', () { expect(UITextStyle.headline5, isA<TextStyle>()); }); test('headline6 returns TextStyle', () { expect(UITextStyle.headline6, isA<TextStyle>()); }); test('subtitle1 returns TextStyle', () { expect(UITextStyle.subtitle1, isA<TextStyle>()); }); test('subtitle2 returns TextStyle', () { expect(UITextStyle.subtitle2, isA<TextStyle>()); }); test('bodyText1 returns TextStyle', () { expect(UITextStyle.bodyText1, isA<TextStyle>()); }); test('bodyText2 returns TextStyle', () { expect(UITextStyle.bodyText2, isA<TextStyle>()); }); test('button returns TextStyle', () { expect(UITextStyle.button, isA<TextStyle>()); }); test('caption returns TextStyle', () { expect(UITextStyle.caption, isA<TextStyle>()); }); test('overline returns TextStyle', () { expect(UITextStyle.overline, isA<TextStyle>()); }); test('labelSmall returns TextStyle', () { expect(UITextStyle.labelSmall, isA<TextStyle>()); }); }); group('ContentTextStyle', () { test('display1 returns TextStyle', () { expect(ContentTextStyle.display1, isA<TextStyle>()); }); test('display2 returns TextStyle', () { expect(ContentTextStyle.display2, isA<TextStyle>()); }); test('display3 returns TextStyle', () { expect(ContentTextStyle.display3, isA<TextStyle>()); }); test('headline1 returns TextStyle', () { expect(ContentTextStyle.headline1, isA<TextStyle>()); }); test('headline2 returns TextStyle', () { expect(ContentTextStyle.headline2, isA<TextStyle>()); }); test('headline3 returns TextStyle', () { expect(ContentTextStyle.headline3, isA<TextStyle>()); }); test('headline4 returns TextStyle', () { expect(ContentTextStyle.headline4, isA<TextStyle>()); }); test('headline5 returns TextStyle', () { expect(ContentTextStyle.headline5, isA<TextStyle>()); }); test('headline6 returns TextStyle', () { expect(ContentTextStyle.headline6, isA<TextStyle>()); }); test('subtitle1 returns TextStyle', () { expect(ContentTextStyle.subtitle1, isA<TextStyle>()); }); test('subtitle2 returns TextStyle', () { expect(ContentTextStyle.subtitle2, isA<TextStyle>()); }); test('bodyText1 returns TextStyle', () { expect(ContentTextStyle.bodyText1, isA<TextStyle>()); }); test('bodyText2 returns TextStyle', () { expect(ContentTextStyle.bodyText2, isA<TextStyle>()); }); test('button returns TextStyle', () { expect(ContentTextStyle.button, isA<TextStyle>()); }); test('caption returns TextStyle', () { expect(ContentTextStyle.caption, isA<TextStyle>()); }); test('overline returns TextStyle', () { expect(ContentTextStyle.overline, isA<TextStyle>()); }); test('labelSmall returns TextStyle', () { expect(ContentTextStyle.labelSmall, isA<TextStyle>()); }); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/typography/app_text_styles_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/typography/app_text_styles_test.dart", "repo_id": "news_toolkit", "token_count": 1711 }
936
name: article_repository description: A repository that manages article data. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: clock: ^1.1.0 equatable: ^2.0.3 flutter_news_example_api: path: ../../api storage: path: ../storage/storage dev_dependencies: coverage: ^1.3.2 mocktail: ^1.0.2 test: ^1.21.4 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/article_repository/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/article_repository/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 173 }
937
export 'src/firebase_authentication_client.dart';
news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/lib/firebase_authentication_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/lib/firebase_authentication_client.dart", "repo_id": "news_toolkit", "token_count": 16 }
938
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template article_introduction} /// A reusable article introduction block widget. /// {@endtemplate} class ArticleIntroduction extends StatelessWidget { /// {@macro article_introduction} const ArticleIntroduction({ required this.block, required this.premiumText, super.key, }); /// The associated [ArticleIntroductionBlock] instance. final ArticleIntroductionBlock block; /// Text displayed when article is premium content. final String premiumText; @override Widget build(BuildContext context) { return Column( children: [ if (block.imageUrl != null) InlineImage(imageUrl: block.imageUrl!), Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: PostContent( categoryName: block.category.name, title: block.title, author: block.author, publishedAt: block.publishedAt, premiumText: premiumText, isPremium: block.isPremium, ), ), const Divider(), const SizedBox(height: AppSpacing.lg), ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/article_introduction.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/article_introduction.dart", "repo_id": "news_toolkit", "token_count": 494 }
939
export 'post_medium.dart'; export 'post_medium_description_layout.dart'; export 'post_medium_overlaid_layout.dart';
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/index.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/index.dart", "repo_id": "news_toolkit", "token_count": 40 }
940
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart' hide ProgressIndicator; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template video_introduction} /// A reusable video introduction block widget. /// {@endtemplate} class VideoIntroduction extends StatelessWidget { /// {@macro video_introduction} const VideoIntroduction({required this.block, super.key}); /// The associated [VideoIntroductionBlock] instance. final VideoIntroductionBlock block; @override Widget build(BuildContext context) { return Column( children: [ InlineVideo( videoUrl: block.videoUrl, progressIndicator: const ProgressIndicator(), ), Padding( padding: const EdgeInsets.fromLTRB( AppSpacing.lg, 0, AppSpacing.lg, AppSpacing.lg, ), child: PostContent( categoryName: block.category.name, title: block.title, isVideoContent: true, ), ), ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/video_introduction.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/video_introduction.dart", "repo_id": "news_toolkit", "token_count": 469 }
941
name: news_blocks_ui description: A Flutter package that contains UI components for news blocks. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.19.3 <4.0.0" dependencies: app_ui: path: ../app_ui cached_network_image: ^3.2.1 flutter: sdk: flutter flutter_html: 3.0.0-beta.2 google_mobile_ads: ^4.0.0 news_blocks: path: ../../api/packages/news_blocks path_provider_platform_interface: ^2.0.5 platform: ^3.1.0 plugin_platform_interface: ^2.1.3 url_launcher: ^6.1.7 url_launcher_platform_interface: ^2.1.1 video_player: ^2.7.0 video_player_platform_interface: ^6.0.1 dev_dependencies: build_runner: ^2.0.3 fake_async: ^1.3.0 flutter_gen_runner: ^5.2.0 flutter_test: sdk: flutter mocktail: ^1.0.2 mocktail_image_network: ^1.0.0 very_good_analysis: ^5.1.0 flutter: uses-material-design: true assets: - assets/icons/ flutter_gen: assets: enabled: true outputs: package_parameter_enabled: true output: lib/src/generated/ line_length: 80 integrations: flutter_svg: true
news_toolkit/flutter_news_example/packages/news_blocks_ui/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 466 }
942
// ignore_for_file: prefer_const_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/newsletter/index.dart'; import '../../helpers/helpers.dart'; void main() { group('NewsletterSucceeded', () { testWidgets('renders correctly', (tester) async { const headerText = 'headerText'; const contentText = 'contentText'; const footerText = 'footerText'; await tester.pumpApp( NewsletterSucceeded( headerText: headerText, content: Text(contentText), footerText: footerText, ), ); expect(find.text(headerText), findsOneWidget); expect(find.text(contentText), findsOneWidget); expect(find.text(footerText), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_succeeded_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_succeeded_test.dart", "repo_id": "news_toolkit", "token_count": 327 }
943
// ignore_for_file: prefer_const_constructors import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart' hide ProgressIndicator; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('InlineImage', () { testWidgets('renders CachedNetworkImage with imageUrl', (tester) async { const imageUrl = 'imageUrl'; ProgressIndicator progressIndicatorBuilder( BuildContext context, String url, DownloadProgress progress, ) => ProgressIndicator(); await mockNetworkImages( () async => tester.pumpApp( InlineImage( imageUrl: imageUrl, progressIndicatorBuilder: progressIndicatorBuilder, ), ), ); expect( find.byWidgetPredicate( (widget) => widget is CachedNetworkImage && widget.imageUrl == imageUrl && widget.progressIndicatorBuilder == progressIndicatorBuilder, ), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/inline_image_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/inline_image_test.dart", "repo_id": "news_toolkit", "token_count": 514 }
944
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
945
import 'dart:async'; import 'dart:convert'; import 'package:equatable/equatable.dart'; import 'package:flutter_news_example_api/client.dart'; import 'package:notifications_client/notifications_client.dart'; import 'package:permission_client/permission_client.dart'; import 'package:storage/storage.dart'; part 'notifications_storage.dart'; /// {@template notifications_failure} /// A base failure for the notifications repository failures. /// {@endtemplate} abstract class NotificationsFailure with EquatableMixin implements Exception { /// {@macro notifications_failure} const NotificationsFailure(this.error); /// The error which was caught. final Object error; @override List<Object> get props => [error]; } /// {@template initialize_categories_preferences_failure} /// Thrown when initializing categories preferences fails. /// {@endtemplate} class InitializeCategoriesPreferencesFailure extends NotificationsFailure { /// {@macro initialize_categories_preferences_failure} const InitializeCategoriesPreferencesFailure(super.error); } /// {@template toggle_notifications_failure} /// Thrown when toggling notifications fails. /// {@endtemplate} class ToggleNotificationsFailure extends NotificationsFailure { /// {@macro toggle_notifications_failure} const ToggleNotificationsFailure(super.error); } /// {@template fetch_notifications_enabled_failure} /// Thrown when fetching a notifications enabled status fails. /// {@endtemplate} class FetchNotificationsEnabledFailure extends NotificationsFailure { /// {@macro fetch_notifications_enabled_failure} const FetchNotificationsEnabledFailure(super.error); } /// {@template set_categories_preferences_failure} /// Thrown when setting categories preferences fails. /// {@endtemplate} class SetCategoriesPreferencesFailure extends NotificationsFailure { /// {@macro set_categories_preferences_failure} const SetCategoriesPreferencesFailure(super.error); } /// {@template fetch_categories_preferences_failure} /// Thrown when fetching categories preferences fails. /// {@endtemplate} class FetchCategoriesPreferencesFailure extends NotificationsFailure { /// {@macro fetch_categories_preferences_failure} const FetchCategoriesPreferencesFailure(super.error); } /// {@template notifications_repository} /// A repository that manages notification permissions and topic subscriptions. /// /// Access to the device's notifications can be toggled with /// [toggleNotifications] and checked with [fetchNotificationsEnabled]. /// /// Notification preferences for topic subscriptions related to news categories /// may be updated with [setCategoriesPreferences] and checked with /// [fetchCategoriesPreferences]. /// {@endtemplate} class NotificationsRepository { /// {@macro notifications_repository} NotificationsRepository({ required PermissionClient permissionClient, required NotificationsStorage storage, required NotificationsClient notificationsClient, required FlutterNewsExampleApiClient apiClient, }) : _permissionClient = permissionClient, _storage = storage, _notificationsClient = notificationsClient, _apiClient = apiClient { unawaited(_initializeCategoriesPreferences()); } final PermissionClient _permissionClient; final NotificationsStorage _storage; final NotificationsClient _notificationsClient; final FlutterNewsExampleApiClient _apiClient; /// Toggles the notifications based on the [enable]. /// /// When [enable] is true, request the notification permission if not granted /// and marks the notification setting as enabled. Subscribes the user to /// notifications related to user's categories preferences. /// /// When [enable] is false, marks notification setting as disabled and /// unsubscribes the user from notifications related to user's categories /// preferences. Future<void> toggleNotifications({required bool enable}) async { try { // Request the notification permission when turning notifications on. if (enable) { // Find the current notification permission status. final permissionStatus = await _permissionClient.notificationsStatus(); // Navigate the user to permission settings // if the permission status is permanently denied or restricted. if (permissionStatus.isPermanentlyDenied || permissionStatus.isRestricted) { await _permissionClient.openPermissionSettings(); return; } // Request the permission if the permission status is denied. if (permissionStatus.isDenied) { final updatedPermissionStatus = await _permissionClient.requestNotifications(); if (!updatedPermissionStatus.isGranted) { return; } } } // Toggle categories preferences notification subscriptions. await _toggleCategoriesPreferencesSubscriptions(enable: enable); // Update the notifications enabled in Storage. await _storage.setNotificationsEnabled(enabled: enable); } catch (error, stackTrace) { Error.throwWithStackTrace(ToggleNotificationsFailure(error), stackTrace); } } /// Returns true when the notification permission is granted /// and the notification setting is enabled. Future<bool> fetchNotificationsEnabled() async { try { final results = await Future.wait([ _permissionClient.notificationsStatus(), _storage.fetchNotificationsEnabled(), ]); final permissionStatus = results.first as PermissionStatus; final notificationsEnabled = results.last as bool; return permissionStatus.isGranted && notificationsEnabled; } catch (error, stackTrace) { Error.throwWithStackTrace( FetchNotificationsEnabledFailure(error), stackTrace, ); } } /// Updates the user's notification preferences and subscribes the user to /// receive notifications related to [categories]. /// /// [categories] represents a set of categories the user has agreed to /// receive notifications from. /// /// Throws [SetCategoriesPreferencesFailure] when updating fails. Future<void> setCategoriesPreferences(Set<Category> categories) async { try { // Disable notification subscriptions for previous categories preferences. await _toggleCategoriesPreferencesSubscriptions(enable: false); // Update categories preferences in Storage. await _storage.setCategoriesPreferences(categories: categories); // Enable notification subscriptions for updated categories preferences. if (await fetchNotificationsEnabled()) { await _toggleCategoriesPreferencesSubscriptions(enable: true); } } catch (error, stackTrace) { Error.throwWithStackTrace( SetCategoriesPreferencesFailure(error), stackTrace, ); } } /// Fetches the user's notification preferences for news categories. /// /// The result represents a set of categories the user has agreed to /// receive notifications from. /// /// Throws [FetchCategoriesPreferencesFailure] when fetching fails. Future<Set<Category>?> fetchCategoriesPreferences() async { try { return await _storage.fetchCategoriesPreferences(); } on StorageException catch (error, stackTrace) { Error.throwWithStackTrace( FetchCategoriesPreferencesFailure(error), stackTrace, ); } } /// Toggles notification subscriptions based on user's categories preferences. Future<void> _toggleCategoriesPreferencesSubscriptions({ required bool enable, }) async { final categoriesPreferences = await _storage.fetchCategoriesPreferences() ?? {}; await Future.wait( categoriesPreferences.map((category) { return enable ? _notificationsClient.subscribeToCategory(category.name) : _notificationsClient.unsubscribeFromCategory(category.name); }), ); } /// Initializes categories preferences to all categories /// if they have not been set before. Future<void> _initializeCategoriesPreferences() async { try { final categoriesPreferences = await _storage.fetchCategoriesPreferences(); if (categoriesPreferences == null) { final categoriesResponse = await _apiClient.getCategories(); await _storage.setCategoriesPreferences( categories: categoriesResponse.categories.toSet(), ); } } catch (error, stackTrace) { Error.throwWithStackTrace( InitializeCategoriesPreferencesFailure(error), stackTrace, ); } } }
news_toolkit/flutter_news_example/packages/notifications_repository/lib/src/notifications_repository.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/lib/src/notifications_repository.dart", "repo_id": "news_toolkit", "token_count": 2590 }
946
import 'package:permission_handler/permission_handler.dart'; export 'package:permission_handler/permission_handler.dart' show PermissionStatus, PermissionStatusGetters; /// {@template permission_client} /// A client that handles requesting permissions on a device. /// {@endtemplate} class PermissionClient { /// {@macro permission_client} const PermissionClient(); /// Request access to the device's notifications, /// if access hasn't been previously granted. Future<PermissionStatus> requestNotifications() => Permission.notification.request(); /// Returns a permission status for the device's notifications. Future<PermissionStatus> notificationsStatus() => Permission.notification.status; /// Opens the app settings page. /// /// Returns true if the settings could be opened, otherwise false. Future<bool> openPermissionSettings() => openAppSettings(); }
news_toolkit/flutter_news_example/packages/permission_client/lib/src/permission_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/permission_client/lib/src/permission_client.dart", "repo_id": "news_toolkit", "token_count": 239 }
947
name: share_launcher description: A launcher that handles share functionality on a device. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: equatable: ^2.0.3 flutter: sdk: flutter share_plus: ^7.0.2 share_plus_platform_interface: ^3.1.2 dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 plugin_platform_interface: ^2.1.2 url_launcher_platform_interface: ^2.0.5 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/share_launcher/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/share_launcher/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 198 }
948
# Storage [![style: very good analysis](https://img.shields.io/badge/style-very_good_analysis-B22C89.svg)](https://pub.dev/packages/very_good_analysis) A Key/Value Storage Client for Dart.
news_toolkit/flutter_news_example/packages/storage/storage/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/storage/README.md", "repo_id": "news_toolkit", "token_count": 68 }
949
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; void main() { group('ArticleState', () { test('initial has correct status', () { expect( ArticleState.initial().status, equals(ArticleStatus.initial), ); }); test('supports value comparisons', () { expect( ArticleState.initial(), equals(ArticleState.initial()), ); }); group('contentMilestone', () { test( 'returns 0 ' 'when contentTotalCount is null', () { expect( ArticleState.initial().copyWith(contentSeenCount: 5).contentMilestone, isZero, ); }); test( 'returns 0 ' 'when isPreview is true', () { expect( ArticleState.initial() .copyWith(contentSeenCount: 5, isPreview: true) .contentMilestone, isZero, ); }); test( 'returns 0 ' 'when user has seen less than 25% of content', () { expect( ArticleState.initial() .copyWith( contentSeenCount: 0, contentTotalCount: 100, ) .contentMilestone, isZero, ); expect( ArticleState.initial() .copyWith( contentSeenCount: 24, contentTotalCount: 100, ) .contentMilestone, isZero, ); }); test( 'returns 25 ' 'when user has seen at least 25% of content ' 'and less than 50%', () { expect( ArticleState.initial() .copyWith( contentSeenCount: 25, contentTotalCount: 100, ) .contentMilestone, equals(25), ); expect( ArticleState.initial() .copyWith( contentSeenCount: 49, contentTotalCount: 100, ) .contentMilestone, equals(25), ); }); test( 'returns 50 ' 'when user has seen at least 50% of content ' 'and less than 75%', () { expect( ArticleState.initial() .copyWith( contentSeenCount: 50, contentTotalCount: 100, ) .contentMilestone, equals(50), ); expect( ArticleState.initial() .copyWith( contentSeenCount: 74, contentTotalCount: 100, ) .contentMilestone, equals(50), ); }); test( 'returns 75 ' 'when user has seen at least 75% of content ' 'and less than 100%', () { expect( ArticleState.initial() .copyWith( contentSeenCount: 75, contentTotalCount: 100, ) .contentMilestone, equals(75), ); expect( ArticleState.initial() .copyWith( contentSeenCount: 99, contentTotalCount: 100, ) .contentMilestone, equals(75), ); }); test( 'returns 100 ' 'when user has seen 100% of content', () { expect( ArticleState.initial() .copyWith( contentSeenCount: 100, contentTotalCount: 100, ) .contentMilestone, equals(100), ); }); }); group('copyWith', () { test( 'returns same object ' 'when no properties are passed', () { expect( ArticleState.initial().copyWith(), equals(ArticleState.initial()), ); }); test( 'returns object with updated title ' 'when title is passed', () { expect( ArticleState( status: ArticleStatus.populated, ).copyWith(title: 'title'), equals( ArticleState( status: ArticleStatus.populated, title: 'title', ), ), ); }); test( 'returns object with updated status ' 'when status is passed', () { expect( ArticleState.initial().copyWith( status: ArticleStatus.loading, ), equals( ArticleState( status: ArticleStatus.loading, ), ), ); }); test( 'returns object with updated content ' 'when content is passed', () { final content = <NewsBlock>[ TextCaptionBlock(text: 'text', color: TextCaptionColor.normal), TextParagraphBlock(text: 'text'), ]; expect( ArticleState(status: ArticleStatus.populated).copyWith( content: content, ), equals( ArticleState( status: ArticleStatus.populated, content: content, ), ), ); }); test( 'returns object with updated contentTotalCount ' 'when contentTotalCount is passed', () { const contentTotalCount = 10; expect( ArticleState(status: ArticleStatus.populated).copyWith( contentTotalCount: contentTotalCount, ), equals( ArticleState( status: ArticleStatus.populated, contentTotalCount: contentTotalCount, ), ), ); }); test( 'returns object with updated contentSeenCount ' 'when contentSeenCount is passed', () { const contentSeenCount = 10; expect( ArticleState(status: ArticleStatus.populated).copyWith( contentSeenCount: contentSeenCount, ), equals( ArticleState( status: ArticleStatus.populated, contentSeenCount: contentSeenCount, ), ), ); }); test( 'returns object with updated hasMoreContent ' 'when hasMoreContent is passed', () { const hasMoreContent = false; expect( ArticleState( status: ArticleStatus.populated, hasMoreContent: false, ).copyWith(hasMoreContent: hasMoreContent), equals( ArticleState( status: ArticleStatus.populated, hasMoreContent: hasMoreContent, ), ), ); }); test( 'returns object with updated relatedArticles ' 'when relatedArticles is passed', () { const relatedArticles = <NewsBlock>[DividerHorizontalBlock()]; expect( ArticleState( status: ArticleStatus.populated, ).copyWith(relatedArticles: relatedArticles), equals( ArticleState( status: ArticleStatus.populated, relatedArticles: relatedArticles, ), ), ); }); test( 'returns object with updated hasReachedArticleViewsLimit ' 'when hasReachedArticleViewsLimit is passed', () { const hasReachedArticleViewsLimit = true; expect( ArticleState( status: ArticleStatus.populated, ).copyWith(hasReachedArticleViewsLimit: hasReachedArticleViewsLimit), equals( ArticleState( status: ArticleStatus.populated, hasReachedArticleViewsLimit: hasReachedArticleViewsLimit, ), ), ); }); test( 'returns object with updated isPreview ' 'when isPreview is passed', () { const isPreview = true; expect( ArticleState( status: ArticleStatus.populated, ).copyWith(isPreview: isPreview), equals( ArticleState( status: ArticleStatus.populated, isPreview: isPreview, ), ), ); }); test( 'returns object with updated isPremium ' 'when isPremium is passed', () { const isPremium = true; expect( ArticleState( status: ArticleStatus.populated, ).copyWith(isPremium: isPremium), equals( ArticleState( status: ArticleStatus.populated, isPremium: isPremium, ), ), ); }); }); }); }
news_toolkit/flutter_news_example/test/article/bloc/article_state_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/bloc/article_state_test.dart", "repo_id": "news_toolkit", "token_count": 4639 }
950
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_repository/news_repository.dart'; void main() { group('FeedEvent', () { group('FeedRequested', () { test('supports value comparisons', () { final event1 = FeedRequested(category: Category.health); final event2 = FeedRequested(category: Category.health); expect(event1, equals(event2)); }); }); group('FeedRefreshRequested', () { test('supports value comparisons', () { final event1 = FeedRefreshRequested(category: Category.science); final event2 = FeedRefreshRequested(category: Category.science); expect(event1, equals(event2)); }); }); }); }
news_toolkit/flutter_news_example/test/feed/bloc/feed_event_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/feed/bloc/feed_event_test.dart", "repo_id": "news_toolkit", "token_count": 300 }
951
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:form_inputs/form_inputs.dart'; void main() { const email = Email.dirty('email'); group('LoginState', () { test('supports value comparisons', () { expect(LoginState(), LoginState()); }); test('returns same object when no properties are passed', () { expect(LoginState().copyWith(), LoginState()); }); test('returns object with updated status when status is passed', () { expect( LoginState().copyWith(status: FormzSubmissionStatus.initial), LoginState(), ); }); test('returns object with updated email when email is passed', () { expect( LoginState().copyWith(email: email), LoginState(email: email), ); }); test('returns object with updated valid when valid is passed', () { expect( LoginState().copyWith(valid: true), LoginState(valid: true), ); }); }); }
news_toolkit/flutter_news_example/test/login/bloc/login_state_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/login/bloc/login_state_test.dart", "repo_id": "news_toolkit", "token_count": 390 }
952
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_news_example/network_error/network_error.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { const tapMeText = 'Tap Me'; group('NetworkError', () { testWidgets('renders correctly', (tester) async { await tester.pumpApp(NetworkError()); expect(find.byType(NetworkError), findsOneWidget); }); testWidgets('router returns a valid navigation route', (tester) async { await tester.pumpApp( Scaffold( body: Builder( builder: (context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>(NetworkError.route()); }, child: const Text(tapMeText), ); }, ), ), ); await tester.tap(find.text(tapMeText)); await tester.pumpAndSettle(); expect(find.byType(NetworkError), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/test/network_error/view/network_error_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/network_error/view/network_error_test.dart", "repo_id": "news_toolkit", "token_count": 490 }
953
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/search/search.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('SearchEvent', () { group('SearchTermChanged', () { test('supports empty value comparisons', () { final event1 = SearchTermChanged(); final event2 = SearchTermChanged(); expect(event1, equals(event2)); }); }); test('supports searchTerm value comparisons', () { final event1 = SearchTermChanged(searchTerm: 'keyword'); final event2 = SearchTermChanged(searchTerm: 'keyword'); expect(event1, equals(event2)); }); }); }
news_toolkit/flutter_news_example/test/search/bloc/search_event_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/search/bloc/search_event_test.dart", "repo_id": "news_toolkit", "token_count": 240 }
954
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_news_example/terms_of_service/terms_of_service.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import '../../helpers/helpers.dart'; void main() { const termsOfServiceModalCloseButtonKey = Key('termsOfServiceModal_closeModal_iconButton'); group('TermsOfServiceModal', () { group('renders', () { testWidgets('terms of service modal header', (tester) async { await tester.pumpApp(TermsOfServiceModal()); expect(find.byType(TermsOfServiceModalHeader), findsOneWidget); }); testWidgets('terms of service modal close button', (tester) async { await tester.pumpApp(TermsOfServiceModal()); final closeButton = find.byKey(termsOfServiceModalCloseButtonKey); expect(closeButton, findsOneWidget); }); testWidgets('terms of service body', (tester) async { await tester.pumpApp(TermsOfServiceModal()); expect(find.byType(TermsOfServiceBody), findsOneWidget); }); }); group('closes terms of service modal', () { testWidgets('when the close icon button is pressed', (tester) async { final navigator = MockNavigator(); when(navigator.pop).thenAnswer((_) async {}); await tester.pumpApp( TermsOfServiceModal(), navigator: navigator, ); await tester.tap(find.byKey(termsOfServiceModalCloseButtonKey)); await tester.pumpAndSettle(); verify(navigator.pop).called(1); }); }); }); }
news_toolkit/flutter_news_example/test/terms_of_service/view/terms_of_service_modal_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/terms_of_service/view/terms_of_service_modal_test.dart", "repo_id": "news_toolkit", "token_count": 647 }
955
def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 33 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' checkReleaseBuilds false } defaultConfig { applicationId "{{reverse_domain}}" minSdkVersion 23 targetSdkVersion 31 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } signingConfigs { if (System.getenv("ANDROID_KEYSTORE_PATH")) { release { storeFile file(System.getenv("ANDROID_KEYSTORE_PATH")) keyAlias System.getenv("ANDROID_KEYSTORE_ALIAS") keyPassword System.getenv("ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD") storePassword System.getenv("ANDROID_KEYSTORE_PASSWORD") } } else { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } } flavorDimensions "default" productFlavors { {{#flavors}} {{name}} { dimension "default" applicationIdSuffix "{{suffix}}" manifestPlaceholders = [appName: "{{app_name}} [{{suffix.upperCase()}}]"] } {{/flavors}} } buildTypes { release { signingConfig signingConfigs.release } debug { signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.google.guava:guava:27.0.1-android' implementation 'com.google.firebase:firebase-analytics:17.4.4' implementation 'com.google.firebase:firebase-crashlytics:17.1.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics'
news_toolkit/tool/generator/static/build.gradle/0
{ "file_path": "news_toolkit/tool/generator/static/build.gradle", "repo_id": "news_toolkit", "token_count": 1386 }
956
#!/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 # Pathify the dependencies on changed packages (excluding major version # changes, which won't affect clients). .ci/scripts/tool_runner.sh make-deps-path-based --target-dependencies-with-non-breaking-updates # This uses --run-on-dirty-packages rather than --packages-for-branch # since only the packages changed by 'make-deps-path-based' need to be # re-checked. # --skip-if-resolving-fails is used to avoid failing if there's a resolution # conflict when using path-based dependencies, because that indicates that # the failing packages won't pick up the new versions of the changed packages # when they are published anyway, so publishing won't cause an out-of-band # failure regardless. dart ./script/tool/bin/flutter_plugin_tools.dart analyze --run-on-dirty-packages \ --skip-if-resolving-fails \ --log-timing --custom-analysis=script/configs/custom_analysis.yaml # Restore the tree to a clean state, to avoid accidental issues if # other script steps are added to the enclosing task. git checkout .
packages/.ci/scripts/analyze_pathified.sh/0
{ "file_path": "packages/.ci/scripts/analyze_pathified.sh", "repo_id": "packages", "token_count": 333 }
957
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 iOS debug script: .ci/scripts/build_all_packages_app.sh args: ["ios", "debug", "--no-codesign"] - name: build all_packages for iOS release script: .ci/scripts/build_all_packages_app.sh args: ["ios", "release", "--no-codesign"]
packages/.ci/targets/ios_build_all_packages.yaml/0
{ "file_path": "packages/.ci/targets/ios_build_all_packages.yaml", "repo_id": "packages", "token_count": 206 }
958
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: custom package tests script: .ci/scripts/custom_package_tests.sh
packages/.ci/targets/windows_custom_package_tests.yaml/0
{ "file_path": "packages/.ci/targets/windows_custom_package_tests.yaml", "repo_id": "packages", "token_count": 77 }
959
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'modal.dart'; /// The modal transition configuration for a Material fade transition. /// /// The fade pattern is used for UI elements that enter or exit from within /// the screen bounds. Elements that enter use a quick fade in and scale from /// 80% to 100%. Elements that exit simply fade out. The scale animation is /// only applied to entering elements to emphasize new content over old. /// /// ```dart /// /// Sample widget that uses [showModal] with [FadeScaleTransitionConfiguration]. /// class MyHomePage extends StatelessWidget { /// @override /// Widget build(BuildContext context) { /// return Scaffold( /// body: Center( /// child: ElevatedButton( /// onPressed: () { /// showModal( /// context: context, /// configuration: FadeScaleTransitionConfiguration(), /// builder: (BuildContext context) { /// return _CenteredFlutterLogo(); /// }, /// ); /// }, /// child: Icon(Icons.add), /// ), /// ), /// ); /// } /// } /// /// /// Displays a centered Flutter logo with size constraints. /// class _CenteredFlutterLogo extends StatelessWidget { /// const _CenteredFlutterLogo(); /// /// @override /// Widget build(BuildContext context) { /// return Center( /// child: SizedBox( /// width: 250, /// height: 250, /// child: const Material( /// child: Center( /// child: FlutterLogo(size: 250), /// ), /// ), /// ), /// ); /// } /// } /// ``` class FadeScaleTransitionConfiguration extends ModalConfiguration { /// Creates the Material fade transition configuration. /// /// [barrierDismissible] configures whether or not tapping the modal's /// scrim dismisses the modal. [barrierLabel] sets the semantic label for /// a dismissible barrier. [barrierDismissible] cannot be null. If /// [barrierDismissible] is true, the [barrierLabel] cannot be null. const FadeScaleTransitionConfiguration({ super.barrierColor = Colors.black54, super.barrierDismissible = true, super.transitionDuration = const Duration(milliseconds: 150), super.reverseTransitionDuration = const Duration(milliseconds: 75), String super.barrierLabel = 'Dismiss', }); @override Widget transitionBuilder( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { return FadeScaleTransition( animation: animation, child: child, ); } } /// A widget that implements the Material fade transition. /// /// The fade pattern is used for UI elements that enter or exit from within /// the screen bounds. Elements that enter use a quick fade in and scale from /// 80% to 100%. Elements that exit simply fade out. The scale animation is /// only applied to entering elements to emphasize new content over old. /// /// This widget is not to be confused with Flutter's [FadeTransition] widget, /// which animates only the opacity of its child widget. class FadeScaleTransition extends StatelessWidget { /// Creates a widget that implements the Material fade transition. /// /// The fade pattern is used for UI elements that enter or exit from within /// the screen bounds. Elements that enter use a quick fade in and scale from /// 80% to 100%. Elements that exit simply fade out. The scale animation is /// only applied to entering elements to emphasize new content over old. /// /// This widget is not to be confused with Flutter's [FadeTransition] widget, /// which animates only the opacity of its child widget. /// /// [animation] is typically an [AnimationController] that drives the transition /// animation. [animation] cannot be null. const FadeScaleTransition({ super.key, required this.animation, 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 widget below this widget in the tree. /// /// This widget will transition in and out as driven by [animation] and /// [secondaryAnimation]. final Widget? child; static final Animatable<double> _fadeInTransition = CurveTween( curve: const Interval(0.0, 0.3), ); static final Animatable<double> _scaleInTransition = Tween<double>( begin: 0.80, end: 1.00, ).chain(CurveTween(curve: Easing.legacyDecelerate)); static final Animatable<double> _fadeOutTransition = Tween<double>( begin: 1.0, end: 0.0, ); @override Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, forwardBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return FadeTransition( opacity: _fadeInTransition.animate(animation), child: ScaleTransition( scale: _scaleInTransition.animate(animation), child: child, ), ); }, reverseBuilder: ( BuildContext context, Animation<double> animation, Widget? child, ) { return FadeTransition( opacity: _fadeOutTransition.animate(animation), child: child, ); }, child: child, ); } }
packages/packages/animations/lib/src/fade_scale_transition.dart/0
{ "file_path": "packages/packages/animations/lib/src/fade_scale_transition.dart", "repo_id": "packages", "token_count": 1959 }
960
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=false
packages/packages/camera/camera/example/android/gradle.properties/0
{ "file_path": "packages/packages/camera/camera/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
961
{ "name": "camera example", "short_name": "camera", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "An example of the camera on the web.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" } ] }
packages/packages/camera/camera/example/web/manifest.json/0
{ "file_path": "packages/packages/camera/camera/example/web/manifest.json", "repo_id": "packages", "token_count": 305 }
962
rootProject.name = 'camera_android'
packages/packages/camera/camera_android/android/settings.gradle/0
{ "file_path": "packages/packages/camera/camera_android/android/settings.gradle", "repo_id": "packages", "token_count": 11 }
963
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera; import android.annotation.SuppressLint; import android.os.Build; import androidx.annotation.ChecksSdkIntAtLeast; import androidx.annotation.VisibleForTesting; /** Abstracts SDK version checks, and allows overriding them in unit tests. */ public class SdkCapabilityChecker { /** The current SDK version, overridable for testing. */ @SuppressLint("AnnotateVersionCheck") @VisibleForTesting public static int SDK_VERSION = Build.VERSION.SDK_INT; @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.P) public static boolean supportsDistortionCorrection() { // See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES return SDK_VERSION >= Build.VERSION_CODES.P; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.O) public static boolean supportsEglRecordableAndroid() { // See https://developer.android.com/reference/android/opengl/EGLExt#EGL_RECORDABLE_ANDROID return SDK_VERSION >= Build.VERSION_CODES.O; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) public static boolean supportsEncoderProfiles() { // See https://developer.android.com/reference/android/media/EncoderProfiles return SDK_VERSION >= Build.VERSION_CODES.S; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.M) public static boolean supportsMarshmallowNoiseReductionModes() { // See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES return SDK_VERSION >= Build.VERSION_CODES.M; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.P) public static boolean supportsSessionConfiguration() { // See https://developer.android.com/reference/android/hardware/camera2/params/SessionConfiguration return SDK_VERSION >= Build.VERSION_CODES.P; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.N) public static boolean supportsVideoPause() { // See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Pause return SDK_VERSION >= Build.VERSION_CODES.N; } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R) public static boolean supportsZoomRatio() { // See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest#CONTROL_ZOOM_RATIO return SDK_VERSION >= Build.VERSION_CODES.R; } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/SdkCapabilityChecker.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/SdkCapabilityChecker.java", "repo_id": "packages", "token_count": 849 }
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. package io.flutter.plugins.camera.media; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.graphics.ImageFormat; import android.media.Image; import java.nio.ByteBuffer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ImageStreamReaderUtilsTest { private ImageStreamReaderUtils imageStreamReaderUtils; @Before public void setUp() { this.imageStreamReaderUtils = new ImageStreamReaderUtils(); } Image getImage(int imageWidth, int imageHeight, int padding) { int rowStride = imageWidth + padding; int ySize = (rowStride * imageHeight) - padding; int uSize = (ySize / 2) - (padding / 2); int vSize = uSize; // Mock YUV image Image mockImage = mock(Image.class); when(mockImage.getWidth()).thenReturn(imageWidth); when(mockImage.getHeight()).thenReturn(imageHeight); when(mockImage.getFormat()).thenReturn(ImageFormat.YUV_420_888); // Mock planes. YUV images have 3 planes (Y, U, V). Image.Plane planeY = mock(Image.Plane.class); Image.Plane planeU = mock(Image.Plane.class); Image.Plane planeV = mock(Image.Plane.class); // Y plane is width*height // Row stride is generally == width but when there is padding it will // be larger. // Here we are adding 256 padding. when(planeY.getBuffer()).thenReturn(ByteBuffer.allocate(ySize)); when(planeY.getRowStride()).thenReturn(rowStride); when(planeY.getPixelStride()).thenReturn(1); // U and V planes are always the same sizes/values. // https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888 when(planeU.getBuffer()).thenReturn(ByteBuffer.allocate(uSize)); when(planeV.getBuffer()).thenReturn(ByteBuffer.allocate(vSize)); when(planeU.getRowStride()).thenReturn(rowStride); when(planeV.getRowStride()).thenReturn(rowStride); when(planeU.getPixelStride()).thenReturn(2); when(planeV.getPixelStride()).thenReturn(2); // Add planes to image Image.Plane[] planes = {planeY, planeU, planeV}; when(mockImage.getPlanes()).thenReturn(planes); return mockImage; } /** Ensure that passing in an image with padding returns one without padding */ @Test public void yuv420ThreePlanesToNV21_trimsPaddingWhenPresent() { Image mockImage = getImage(160, 120, 16); int imageWidth = mockImage.getWidth(); int imageHeight = mockImage.getHeight(); ByteBuffer result = imageStreamReaderUtils.yuv420ThreePlanesToNV21( mockImage.getPlanes(), mockImage.getWidth(), mockImage.getHeight()); Assert.assertEquals( ((long) imageWidth * imageHeight) + (2 * ((long) (imageWidth / 2) * (imageHeight / 2))), result.limit()); } /** Ensure that passing in an image without padding returns the same size */ @Test public void yuv420ThreePlanesToNV21_trimsPaddingWhenAbsent() { Image mockImage = getImage(160, 120, 0); int imageWidth = mockImage.getWidth(); int imageHeight = mockImage.getHeight(); ByteBuffer result = imageStreamReaderUtils.yuv420ThreePlanesToNV21( mockImage.getPlanes(), mockImage.getWidth(), mockImage.getHeight()); Assert.assertEquals( ((long) imageWidth * imageHeight) + (2 * ((long) (imageWidth / 2) * (imageHeight / 2))), result.limit()); } }
packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/media/ImageStreamReaderUtilsTest.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/media/ImageStreamReaderUtilsTest.java", "repo_id": "packages", "token_count": 1287 }
965
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:camera_platform_interface/camera_platform_interface.dart'; /// Converts method channel call [data] for `receivedImageStreamData` to a /// [CameraImageData]. CameraImageData cameraImageFromPlatformData(Map<dynamic, dynamic> data) { return CameraImageData( format: _cameraImageFormatFromPlatformData(data['format']), height: data['height'] as int, width: data['width'] as int, lensAperture: data['lensAperture'] as double?, sensorExposureTime: data['sensorExposureTime'] as int?, sensorSensitivity: data['sensorSensitivity'] as double?, planes: List<CameraImagePlane>.unmodifiable( (data['planes'] as List<dynamic>).map<CameraImagePlane>( (dynamic planeData) => _cameraImagePlaneFromPlatformData( planeData as Map<dynamic, dynamic>)))); } CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) { return CameraImageFormat(_imageFormatGroupFromPlatformData(data), raw: data); } ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { switch (data) { case 35: // android.graphics.ImageFormat.YUV_420_888 return ImageFormatGroup.yuv420; case 256: // android.graphics.ImageFormat.JPEG return ImageFormatGroup.jpeg; case 17: // android.graphics.ImageFormat.NV21 return ImageFormatGroup.nv21; } return ImageFormatGroup.unknown; } CameraImagePlane _cameraImagePlaneFromPlatformData(Map<dynamic, dynamic> data) { return CameraImagePlane( bytes: data['bytes'] as Uint8List, bytesPerPixel: data['bytesPerPixel'] as int?, bytesPerRow: data['bytesPerRow'] as int, height: data['height'] as int?, width: data['width'] as int?); }
packages/packages/camera/camera_android/lib/src/type_conversion.dart/0
{ "file_path": "packages/packages/camera/camera_android/lib/src/type_conversion.dart", "repo_id": "packages", "token_count": 653 }
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. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageProxy; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AnalyzerFlutterApi; import java.util.Objects; /** * Flutter API implementation for {@link ImageAnalysis.Analyzer}. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class AnalyzerFlutterApiImpl { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private AnalyzerFlutterApi api; /** * Constructs a {@link AnalyzerFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public AnalyzerFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new AnalyzerFlutterApi(binaryMessenger); } /** * Stores the {@link ImageAnalysis.Analyzer} instance and notifies Dart to create and store a new * {@code Analyzer} instance that is attached to this one. If {@code instance} has already been * added, this method does nothing. */ public void create( @NonNull ImageAnalysis.Analyzer instance, @NonNull AnalyzerFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create(instanceManager.addHostCreatedInstance(instance), callback); } } /** * Sends a message to Dart to call {@code Analyzer.analyze} on the Dart object representing * `instance`. */ public void analyze( @NonNull ImageAnalysis.Analyzer analyzerInstance, @NonNull ImageProxy imageProxyInstance, @NonNull AnalyzerFlutterApi.Reply<Void> callback) { api.analyze( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(analyzerInstance)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(imageProxyInstance)), callback); } /** * Sets the Flutter API used to send messages to Dart. * * <p>This is only visible for testing. */ @VisibleForTesting void setApi(@NonNull AnalyzerFlutterApi api) { this.api = api; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java", "repo_id": "packages", "token_count": 821 }
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. package io.flutter.plugins.camerax; import android.app.Activity; import android.graphics.SurfaceTexture; import android.util.Size; import android.view.Surface; import androidx.annotation.NonNull; import androidx.camera.core.CameraSelector; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageCapture; import androidx.camera.core.Preview; import androidx.camera.video.Recorder; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; import java.io.File; /** Utility class used to create CameraX-related objects primarily for testing purposes. */ public class CameraXProxy { /** * Converts a {@link ResolutionInfo} instance to a {@link Size} for setting the target resolution * of {@link UseCase}s. */ public static @NonNull Size sizeFromResolution(@NonNull ResolutionInfo resolutionInfo) { return new Size(resolutionInfo.getWidth().intValue(), resolutionInfo.getHeight().intValue()); } public @NonNull CameraSelector.Builder createCameraSelectorBuilder() { return new CameraSelector.Builder(); } /** Creates an instance of {@link CameraPermissionsManager}. */ public @NonNull CameraPermissionsManager createCameraPermissionsManager() { return new CameraPermissionsManager(); } /** Creates an instance of the {@link DeviceOrientationManager}. */ public @NonNull DeviceOrientationManager createDeviceOrientationManager( @NonNull Activity activity, @NonNull Boolean isFrontFacing, int sensorOrientation, @NonNull DeviceOrientationManager.DeviceOrientationChangeCallback callback) { return new DeviceOrientationManager(activity, isFrontFacing, sensorOrientation, callback); } /** Creates a builder for an instance of the {@link Preview} use case. */ public @NonNull Preview.Builder createPreviewBuilder() { return new Preview.Builder(); } /** Creates a {@link Surface} instance from the specified {@link SurfaceTexture}. */ public @NonNull Surface createSurface(@NonNull SurfaceTexture surfaceTexture) { return new Surface(surfaceTexture); } /** * Creates an instance of the {@link SystemServicesFlutterApiImpl}. * * <p>Included in this class to utilize the callback methods it provides, e.g. {@code * onCameraError(String)}. */ public @NonNull SystemServicesFlutterApiImpl createSystemServicesFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger) { return new SystemServicesFlutterApiImpl(binaryMessenger); } /** Creates an instance of {@link Recorder.Builder}. */ @NonNull public Recorder.Builder createRecorderBuilder() { return new Recorder.Builder(); } /** Creates a builder for an instance of the {@link ImageCapture} use case. */ @NonNull public ImageCapture.Builder createImageCaptureBuilder() { return new ImageCapture.Builder(); } /** * Creates an {@link ImageCapture.OutputFileOptions} to configure where to save a captured image. */ @NonNull public ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File file) { return new ImageCapture.OutputFileOptions.Builder(file).build(); } /** Creates an instance of {@link ImageAnalysis.Builder}. */ @NonNull public ImageAnalysis.Builder createImageAnalysisBuilder() { return new ImageAnalysis.Builder(); } /** Creates an array of {@code byte}s with the size provided. */ @NonNull public byte[] getBytesFromBuffer(int size) { return new byte[size]; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java", "repo_id": "packages", "token_count": 1066 }
968
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.JavaObjectHostApi; /** * A pigeon Host API implementation that handles creating {@link Object}s and invoking its static * and instance methods. * * <p>{@link Object} instances created by {@link JavaObjectHostApiImpl} are used to intercommunicate * with a paired Dart object. */ public class JavaObjectHostApiImpl implements JavaObjectHostApi { private final InstanceManager instanceManager; /** * Constructs a {@link JavaObjectHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with Dart objects */ public JavaObjectHostApiImpl(@NonNull InstanceManager instanceManager) { this.instanceManager = instanceManager; } @Override public void dispose(@NonNull Long identifier) { instanceManager.remove(identifier); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java", "repo_id": "packages", "token_count": 301 }
969
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraSelector; import io.flutter.plugin.common.BinaryMessenger; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class CameraSelectorTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public CameraSelector mockCameraSelector; @Mock public BinaryMessenger mockBinaryMessenger; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { testInstanceManager.stopFinalizationListener(); } @Test public void createTest() { final CameraSelectorHostApiImpl cameraSelectorHostApi = new CameraSelectorHostApiImpl(mockBinaryMessenger, testInstanceManager); final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); final CameraSelector.Builder mockCameraSelectorBuilder = mock(CameraSelector.Builder.class); cameraSelectorHostApi.cameraXProxy = mockCameraXProxy; when(mockCameraXProxy.createCameraSelectorBuilder()).thenReturn(mockCameraSelectorBuilder); when(mockCameraSelectorBuilder.requireLensFacing(1)).thenReturn(mockCameraSelectorBuilder); when(mockCameraSelectorBuilder.build()).thenReturn(mockCameraSelector); cameraSelectorHostApi.create(0L, 1L); verify(mockCameraSelectorBuilder).requireLensFacing(CameraSelector.LENS_FACING_BACK); assertEquals(testInstanceManager.getInstance(0L), mockCameraSelector); } @Test public void filterTest() { final CameraSelectorHostApiImpl cameraSelectorHostApi = new CameraSelectorHostApiImpl(mockBinaryMessenger, testInstanceManager); final CameraInfo cameraInfo = mock(CameraInfo.class); final List<CameraInfo> cameraInfosForFilter = Arrays.asList(cameraInfo); final List<Long> cameraInfosIds = Arrays.asList(1L); testInstanceManager.addDartCreatedInstance(mockCameraSelector, 0); testInstanceManager.addDartCreatedInstance(cameraInfo, 1); when(mockCameraSelector.filter(cameraInfosForFilter)).thenReturn(cameraInfosForFilter); assertEquals( cameraSelectorHostApi.filter(0L, cameraInfosIds), Arrays.asList(testInstanceManager.getIdentifierForStrongReference(cameraInfo))); verify(mockCameraSelector).filter(cameraInfosForFilter); } @Test public void flutterApiCreateTest() { final CameraSelectorFlutterApiImpl spyFlutterApi = spy(new CameraSelectorFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); spyFlutterApi.create(mockCameraSelector, 0L, reply -> {}); final long identifier = Objects.requireNonNull( testInstanceManager.getIdentifierForStrongReference(mockCameraSelector)); verify(spyFlutterApi).create(eq(identifier), eq(0L), any()); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java", "repo_id": "packages", "token_count": 1183 }
970
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraState; import androidx.camera.core.ZoomState; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LiveData; import androidx.lifecycle.Observer; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataFlutterApi; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedTypeData; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class LiveDataTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public LiveData<CameraState> mockLiveData; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public LiveDataFlutterApi mockFlutterApi; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test @SuppressWarnings({"unchecked", "rawtypes"}) public void observe_addsExpectedObserverToLiveDataInstance() { final LiveDataHostApiImpl hostApi = new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); final Observer mockObserver = mock(Observer.class); final long observerIdentifier = 20; final long instanceIdentifier = 29; final LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); instanceManager.addDartCreatedInstance(mockObserver, observerIdentifier); instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); hostApi.setLifecycleOwner(mockLifecycleOwner); hostApi.observe(instanceIdentifier, observerIdentifier); verify(mockLiveData).observe(mockLifecycleOwner, mockObserver); } @Test public void removeObservers_makesCallToRemoveObserversFromLiveDataInstance() { final LiveDataHostApiImpl hostApi = new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); final long instanceIdentifier = 10; final LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); hostApi.setLifecycleOwner(mockLifecycleOwner); hostApi.removeObservers(instanceIdentifier); verify(mockLiveData).removeObservers(mockLifecycleOwner); } @Test @SuppressWarnings("unchecked") public void getValue_returnsExpectedValue() { final LiveDataHostApiImpl hostApi = new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); for (LiveDataSupportedType supportedType : LiveDataSupportedType.values()) { LiveDataSupportedTypeData typeData = new LiveDataSupportedTypeData.Builder().setValue(supportedType).build(); switch (supportedType) { case CAMERA_STATE: CameraState mockCameraState = mock(CameraState.class); final Long mockCameraStateIdentifier = 56L; final long instanceIdentifier = 33; instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); instanceManager.addDartCreatedInstance(mockCameraState, mockCameraStateIdentifier); when(mockLiveData.getValue()).thenReturn(mockCameraState); when(mockCameraState.getType()).thenReturn(CameraState.Type.CLOSED); when(mockCameraState.getError()).thenReturn(null); assertEquals(hostApi.getValue(instanceIdentifier, typeData), mockCameraStateIdentifier); break; case ZOOM_STATE: final LiveData<ZoomState> mockLiveZoomState = (LiveData<ZoomState>) mock(LiveData.class); ZoomState mockZoomState = mock(ZoomState.class); final Long mockLiveZoomStateIdentifier = 22L; final Long mockZoomStateIdentifier = 8L; when(mockLiveZoomState.getValue()).thenReturn(mockZoomState); instanceManager.addDartCreatedInstance(mockLiveZoomState, mockLiveZoomStateIdentifier); instanceManager.addDartCreatedInstance(mockZoomState, mockZoomStateIdentifier); assertEquals( hostApi.getValue(mockLiveZoomStateIdentifier, typeData), mockZoomStateIdentifier); break; default: fail( "The LiveDataSupportedType " + supportedType.toString() + "is unhandled by this test."); } } } @Test public void flutterApiCreate_makesCallToDartToCreateInstance() { final LiveDataFlutterApiWrapper flutterApi = new LiveDataFlutterApiWrapper(mockBinaryMessenger, instanceManager); final LiveDataSupportedType liveDataType = LiveDataSupportedType.CAMERA_STATE; flutterApi.setApi(mockFlutterApi); final ArgumentCaptor<LiveDataSupportedTypeData> liveDataSupportedTypeDataCaptor = ArgumentCaptor.forClass(LiveDataSupportedTypeData.class); flutterApi.create(mockLiveData, liveDataType, reply -> {}); final long instanceIdentifier = Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockLiveData)); verify(mockFlutterApi) .create(eq(instanceIdentifier), liveDataSupportedTypeDataCaptor.capture(), any()); assertEquals(liveDataSupportedTypeDataCaptor.getValue().getValue(), liveDataType); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java", "repo_id": "packages", "token_count": 2116 }
971
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/camera/camera_android_camerax/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/camera/camera_android_camerax/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
972
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '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 'image_proxy.dart'; import 'instance_manager.dart'; import 'java_object.dart'; /// Wrapper of callback for analyzing images. /// /// See https://developer.android.com/reference/androidx/camera/core/ImageAnalysis.Analyzer. @immutable class Analyzer extends JavaObject { /// Creates an [Analyzer]. Analyzer( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.analyze}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _AnalyzerHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); _api.createfromInstances(this); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } /// Constructs a [Analyzer] that is not automatically attached to a native object. Analyzer.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.analyze}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _AnalyzerHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } late final _AnalyzerHostApiImpl _api; /// Analyzes an image to produce a result. final Future<void> Function(ImageProxy imageProxy) analyze; } /// Host API implementation of [Analyzer]. class _AnalyzerHostApiImpl extends AnalyzerHostApi { _AnalyzerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); final BinaryMessenger? binaryMessenger; final InstanceManager instanceManager; /// Creates an [Analyzer] instance on the native side. Future<void> createfromInstances( Analyzer instance, ) { return create( instanceManager.addDartCreatedInstance( instance, onCopy: (Analyzer original) => Analyzer.detached( analyze: original.analyze, binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), ), ); } } /// Flutter API implementation for [Analyzer]. /// /// 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 AnalyzerFlutterApiImpl implements AnalyzerFlutterApi { /// Constructs a [AnalyzerFlutterApiImpl]. /// /// 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]. AnalyzerFlutterApiImpl({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? _binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager _instanceManager; @override void create( int identifier, ) { _instanceManager.addHostCreatedInstance( Analyzer.detached( analyze: (ImageProxy imageProxy) async {}, binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), identifier, onCopy: (Analyzer original) => Analyzer.detached( analyze: original.analyze, binaryMessenger: _binaryMessenger, instanceManager: _instanceManager, ), ); } @override void analyze( int identifier, int imageProxyIdentifier, ) { final Analyzer instance = _instanceManager.getInstanceWithWeakReference(identifier)!; final ImageProxy imageProxy = _instanceManager.getInstanceWithWeakReference(imageProxyIdentifier)!; instance.analyze( imageProxy, ); } }
packages/packages/camera/camera_android_camerax/lib/src/analyzer.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/analyzer.dart", "repo_id": "packages", "token_count": 1509 }
973
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:meta/meta.dart' show immutable; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; /// Strategy that will be adopted when the device in use does not support all /// of the desired quality specified for a particular QualitySelector instance. /// /// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. @immutable class FallbackStrategy extends JavaObject { /// Creates a [FallbackStrategy]. FallbackStrategy( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, required this.quality, required this.fallbackRule}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _FallbackStrategyHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); _api.createFromInstance(this, quality, fallbackRule); } /// Constructs a [FallbackStrategy] that is not automatically attached to a native object. FallbackStrategy.detached( {super.binaryMessenger, super.instanceManager, required this.quality, required this.fallbackRule}) : super.detached(); late final _FallbackStrategyHostApiImpl _api; /// The input quality used to specify this fallback strategy relative to. final VideoQuality quality; /// The fallback rule that this strategy will follow. final VideoResolutionFallbackRule fallbackRule; } /// Host API implementation of [FallbackStrategy]. class _FallbackStrategyHostApiImpl extends FallbackStrategyHostApi { /// Constructs a [FallbackStrategyHostApiImpl]. /// /// 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]. _FallbackStrategyHostApiImpl( {this.binaryMessenger, InstanceManager? instanceManager}) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default [BinaryMessenger] will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Creates a [FallbackStrategy] instance with the specified video [quality] /// and [fallbackRule]. void createFromInstance(FallbackStrategy instance, VideoQuality quality, VideoResolutionFallbackRule fallbackRule) { final int identifier = instanceManager.addDartCreatedInstance(instance, onCopy: (FallbackStrategy original) { return FallbackStrategy.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, quality: original.quality, fallbackRule: original.fallbackRule, ); }); create(identifier, quality, fallbackRule); } }
packages/packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart", "repo_id": "packages", "token_count": 1009 }
974
// Copyright 2013 The Flutter 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 'camerax_library.g.dart'; import 'fallback_strategy.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'pending_recording.dart'; import 'quality_selector.dart'; /// A dart wrapping of the CameraX Recorder class. /// /// See https://developer.android.com/reference/androidx/camera/video/Recorder. @immutable class Recorder extends JavaObject { /// Creates a [Recorder]. Recorder( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.aspectRatio, this.bitRate, this.qualitySelector}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); _api = RecorderHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); _api.createFromInstance(this, aspectRatio, bitRate, qualitySelector); } /// Creates a [Recorder] that is not automatically attached to a native object Recorder.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.aspectRatio, this.bitRate, this.qualitySelector}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = RecorderHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } /// Returns default [QualitySelector] for recordings. /// /// See https://developer.android.com/reference/androidx/camera/video/Recorder#DEFAULT_QUALITY_SELECTOR(). static QualitySelector getDefaultQualitySelector({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) { return QualitySelector.fromOrderedList( binaryMessenger: binaryMessenger, instanceManager: instanceManager, qualityList: <VideoQualityData>[ VideoQualityData(quality: VideoQuality.FHD), VideoQualityData(quality: VideoQuality.HD), VideoQualityData(quality: VideoQuality.SD), ], fallbackStrategy: FallbackStrategy( quality: VideoQuality.FHD, fallbackRule: VideoResolutionFallbackRule.higherQualityOrLowerThan), ); } late final RecorderHostApiImpl _api; /// The video aspect ratio of this [Recorder]. final int? aspectRatio; /// The intended video encoding bitrate for recording. final int? bitRate; /// The [QualitySelector] of this [Recorder] used to select the resolution of /// the recording depending on the resoutions supported by the camera. /// /// Default selector is that returned by [getDefaultQualitySelector], and it /// is compatible with setting the aspect ratio. final QualitySelector? qualitySelector; /// Prepare a recording that will be saved to a file. Future<PendingRecording> prepareRecording(String path) { return _api.prepareRecordingFromInstance(this, path); } } /// Host API implementation of [Recorder]. class RecorderHostApiImpl extends RecorderHostApi { /// Constructs a [RecorderHostApiImpl]. RecorderHostApiImpl( {this.binaryMessenger, InstanceManager? instanceManager}) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Creates a [Recorder] with the provided aspect ratio and bitrate if specified. void createFromInstance(Recorder instance, int? aspectRatio, int? bitRate, QualitySelector? qualitySelector) { int? identifier = instanceManager.getIdentifier(instance); identifier ??= instanceManager.addDartCreatedInstance(instance, onCopy: (Recorder original) { return Recorder.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, aspectRatio: aspectRatio, bitRate: bitRate, qualitySelector: qualitySelector); }); create( identifier, aspectRatio, bitRate, qualitySelector == null ? null : instanceManager.getIdentifier(qualitySelector)!); } /// Prepares a [Recording] using this recorder. The output file will be saved /// at the provided path. Future<PendingRecording> prepareRecordingFromInstance( Recorder instance, String path) async { final int pendingRecordingId = await prepareRecording(instanceManager.getIdentifier(instance)!, path); return instanceManager.getInstanceWithWeakReference(pendingRecordingId)!; } } /// Flutter API implementation of [Recorder]. class RecorderFlutterApiImpl extends RecorderFlutterApi { /// Constructs a [RecorderFlutterApiImpl]. RecorderFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void create(int identifier, int? aspectRatio, int? bitRate) { instanceManager.addHostCreatedInstance( Recorder.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, aspectRatio: aspectRatio, bitRate: bitRate, ), identifier, onCopy: (Recorder original) { return Recorder.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, aspectRatio: aspectRatio, bitRate: bitRate, ); }); } }
packages/packages/camera/camera_android_camerax/lib/src/recorder.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/recorder.dart", "repo_id": "packages", "token_count": 2105 }
975
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/aspect_ratio_strategy_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 [TestAspectRatioStrategyHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestAspectRatioStrategyHostApi extends _i1.Mock implements _i2.TestAspectRatioStrategyHostApi { MockTestAspectRatioStrategyHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, int? preferredAspectRatio, int? fallbackRule, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, preferredAspectRatio, fallbackRule, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart", "repo_id": "packages", "token_count": 780 }
976
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/capture_request_options_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 [TestCaptureRequestOptionsHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestCaptureRequestOptionsHostApi extends _i1.Mock implements _i2.TestCaptureRequestOptionsHostApi { MockTestCaptureRequestOptionsHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, Map<int?, Object?>? options, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, options, ], ), 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/capture_request_options_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/capture_request_options_test.mocks.dart", "repo_id": "packages", "token_count": 738 }
977
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/image_proxy_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 [TestImageProxyHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestImageProxyHostApi extends _i1.Mock implements _i2.TestImageProxyHostApi { MockTestImageProxyHostApi() { _i1.throwOnMissingStub(this); } @override List<int?> getPlanes(int? identifier) => (super.noSuchMethod( Invocation.method( #getPlanes, [identifier], ), returnValue: <int?>[], ) as List<int?>); @override void close(int? identifier) => super.noSuchMethod( Invocation.method( #close, [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/image_proxy_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/image_proxy_test.mocks.dart", "repo_id": "packages", "token_count": 777 }
978
// Copyright 2013 The Flutter 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/camerax_library.g.dart'; import 'package:camera_android_camerax/src/fallback_strategy.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/quality_selector.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'quality_selector_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[ CameraInfo, FallbackStrategy, TestQualitySelectorHostApi, TestInstanceManagerHostApi ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('QualitySelector', () { tearDown(() { TestQualitySelectorHostApi.setup(null); TestInstanceManagerHostApi.setup(null); }); test('detached constructor does not make call to create on the Java side', () { final MockTestQualitySelectorHostApi mockApi = MockTestQualitySelectorHostApi(); TestQualitySelectorHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); QualitySelector.detached( qualityList: <VideoQualityData>[ VideoQualityData(quality: VideoQuality.UHD) ], fallbackStrategy: MockFallbackStrategy(), instanceManager: instanceManager, ); verifyNever(mockApi.create( argThat(isA<int>()), argThat(isA<List<int>>()), argThat(isA<int>()))); }); test('single quality constructor calls create on the Java side', () { final MockTestQualitySelectorHostApi mockApi = MockTestQualitySelectorHostApi(); TestQualitySelectorHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const VideoQuality videoQuality = VideoQuality.FHD; final VideoQualityData quality = VideoQualityData(quality: videoQuality); final FallbackStrategy fallbackStrategy = MockFallbackStrategy(); const int fallbackStrategyIdentifier = 9; instanceManager.addHostCreatedInstance( fallbackStrategy, fallbackStrategyIdentifier, onCopy: (_) => MockFallbackStrategy(), ); final QualitySelector instance = QualitySelector.from( quality: quality, fallbackStrategy: fallbackStrategy, instanceManager: instanceManager, ); final VerificationResult verificationResult = verify(mockApi.create( instanceManager.getIdentifier(instance), captureAny, fallbackStrategyIdentifier, )); final List<VideoQualityData?> videoQualityData = verificationResult.captured.single as List<VideoQualityData?>; expect(videoQualityData.length, equals(1)); expect(videoQualityData.first!.quality, equals(videoQuality)); }); test('quality list constructor calls create on the Java side', () { final MockTestQualitySelectorHostApi mockApi = MockTestQualitySelectorHostApi(); TestQualitySelectorHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final List<VideoQualityData> qualityList = <VideoQualityData>[ VideoQualityData(quality: VideoQuality.FHD), VideoQualityData(quality: VideoQuality.highest), ]; final FallbackStrategy fallbackStrategy = MockFallbackStrategy(); const int fallbackStrategyIdentifier = 9; instanceManager.addHostCreatedInstance( fallbackStrategy, fallbackStrategyIdentifier, onCopy: (_) => MockFallbackStrategy(), ); final QualitySelector instance = QualitySelector.fromOrderedList( qualityList: qualityList, fallbackStrategy: fallbackStrategy, instanceManager: instanceManager, ); final VerificationResult verificationResult = verify(mockApi.create( instanceManager.getIdentifier(instance), captureAny, fallbackStrategyIdentifier, )); final List<VideoQualityData?> videoQualityData = verificationResult.captured.single as List<VideoQualityData?>; expect(videoQualityData.length, equals(2)); expect(videoQualityData.first!.quality, equals(VideoQuality.FHD)); expect(videoQualityData.last!.quality, equals(VideoQuality.highest)); }); test('getResolution returns expected resolution info', () async { final MockTestQualitySelectorHostApi mockApi = MockTestQualitySelectorHostApi(); TestQualitySelectorHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final QualitySelector instance = QualitySelector.detached( instanceManager: instanceManager, qualityList: <VideoQualityData>[ VideoQualityData(quality: VideoQuality.HD) ], fallbackStrategy: MockFallbackStrategy(), ); const int instanceIdentifier = 0; instanceManager.addHostCreatedInstance( instance, instanceIdentifier, onCopy: (QualitySelector original) => QualitySelector.detached( qualityList: original.qualityList, fallbackStrategy: original.fallbackStrategy, instanceManager: instanceManager, ), ); final CameraInfo cameraInfo = MockCameraInfo(); const int cameraInfoIdentifier = 6; instanceManager.addHostCreatedInstance( cameraInfo, cameraInfoIdentifier, onCopy: (_) => MockCameraInfo(), ); const VideoQuality quality = VideoQuality.FHD; final ResolutionInfo expectedResult = ResolutionInfo(width: 34, height: 23); when(mockApi.getResolution( cameraInfoIdentifier, quality, )).thenAnswer((_) { return expectedResult; }); final ResolutionInfo result = await QualitySelector.getResolution( cameraInfo, quality, instanceManager: instanceManager); expect(result.width, expectedResult.width); expect(result.height, expectedResult.height); verify(mockApi.getResolution( cameraInfoIdentifier, quality, )); }); }); }
packages/packages/camera/camera_android_camerax/test/quality_selector_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/quality_selector_test.dart", "repo_id": "packages", "token_count": 2504 }
979
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export 'camera_description.dart'; export 'camera_exception.dart'; export 'camera_image_data.dart'; export 'exposure_mode.dart'; export 'flash_mode.dart'; export 'focus_mode.dart'; export 'image_file_format.dart'; export 'image_format_group.dart'; export 'media_settings.dart'; export 'resolution_preset.dart'; export 'video_capture_options.dart';
packages/packages/camera/camera_platform_interface/lib/src/types/types.dart/0
{ "file_path": "packages/packages/camera/camera_platform_interface/lib/src/types/types.dart", "repo_id": "packages", "token_count": 164 }
980
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: always_specify_types import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test( 'MediaSettings non-parametrized constructor should have correct initial values', () { const MediaSettings settingsWithNoParameters = MediaSettings(); expect( settingsWithNoParameters.resolutionPreset, isNull, reason: 'MediaSettings constructor should have null default resolutionPreset', ); expect( settingsWithNoParameters.fps, isNull, reason: 'MediaSettings constructor should have null default fps', ); expect( settingsWithNoParameters.videoBitrate, isNull, reason: 'MediaSettings constructor should have null default videoBitrate', ); expect( settingsWithNoParameters.audioBitrate, isNull, reason: 'MediaSettings constructor should have null default audioBitrate', ); expect( settingsWithNoParameters.enableAudio, isFalse, reason: 'MediaSettings constructor should have false default enableAudio', ); }); test('MediaSettings fps should hold parameters', () { const MediaSettings settings = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, audioBitrate: 32000, enableAudio: true, ); expect( settings.resolutionPreset, ResolutionPreset.low, reason: 'MediaSettings constructor should hold resolutionPreset parameter', ); expect( settings.fps, 20, reason: 'MediaSettings constructor should hold fps parameter', ); expect( settings.videoBitrate, 128000, reason: 'MediaSettings constructor should hold videoBitrate parameter', ); expect( settings.audioBitrate, 32000, reason: 'MediaSettings constructor should hold audioBitrate parameter', ); expect( settings.enableAudio, true, reason: 'MediaSettings constructor should hold enableAudio parameter', ); }); test('MediaSettings hash should be Object.hash of passed parameters', () { const MediaSettings settings = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, audioBitrate: 32000, enableAudio: true, ); expect( settings.hashCode, Object.hash(ResolutionPreset.low, 20, 128000, 32000, true), reason: 'MediaSettings hash() should be equal to Object.hash of parameters', ); }); group('MediaSettings == operator', () { const ResolutionPreset preset1 = ResolutionPreset.low; const int fps1 = 20; const int videoBitrate1 = 128000; const int audioBitrate1 = 32000; const bool enableAudio1 = true; const ResolutionPreset preset2 = ResolutionPreset.high; const int fps2 = fps1 + 10; const int videoBitrate2 = videoBitrate1 * 2; const int audioBitrate2 = audioBitrate1 * 2; const bool enableAudio2 = !enableAudio1; const MediaSettings settings1 = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, audioBitrate: 32000, enableAudio: true, ); test('should compare resolutionPreset', () { const MediaSettings settings2 = MediaSettings( resolutionPreset: preset2, fps: fps1, videoBitrate: videoBitrate1, audioBitrate: audioBitrate1, enableAudio: enableAudio1, ); expect(settings1 == settings2, isFalse); }); test('should compare fps', () { const MediaSettings settings2 = MediaSettings( resolutionPreset: preset1, fps: fps2, videoBitrate: videoBitrate1, audioBitrate: audioBitrate1, enableAudio: enableAudio1, ); expect(settings1 == settings2, isFalse); }); test('should compare videoBitrate', () { const MediaSettings settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate2, audioBitrate: audioBitrate1, enableAudio: enableAudio1, ); expect(settings1 == settings2, isFalse); }); test('should compare audioBitrate', () { const MediaSettings settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, audioBitrate: audioBitrate2, enableAudio: enableAudio1, ); expect(settings1 == settings2, isFalse); }); test('should compare enableAudio', () { const MediaSettings settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, audioBitrate: audioBitrate1, // ignore: avoid_redundant_argument_values enableAudio: enableAudio2, ); expect(settings1 == settings2, isFalse); }); test('should return true when all parameters are equal', () { const MediaSettings sameSettings = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, audioBitrate: audioBitrate1, enableAudio: enableAudio1, ); expect( settings1 == sameSettings, isTrue, ); }); test('Identical objects should be equal', () { const MediaSettings settingsIdentical = settings1; expect( settings1 == settingsIdentical, isTrue, reason: 'MediaSettings == operator should return true for identical objects', ); }); test('Objects of different types should be non-equal', () { expect( settings1 == Object(), isFalse, reason: 'MediaSettings == operator should return false for objects of different types', ); }); }); }
packages/packages/camera/camera_platform_interface/test/types/media_settings_test.dart/0
{ "file_path": "packages/packages/camera/camera_platform_interface/test/types/media_settings_test.dart", "repo_id": "packages", "token_count": 2275 }
981
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show Color; // ignore_for_file: public_member_api_docs /// Provides a collection of [Color] constants corresponding to the CSS named /// colors. class CSSColors { static const Color aliceBlue = Color(0xFFF0F8FF); static const Color antiqueWhite = Color(0xFFFAEBD7); static const Color aqua = Color(0xFF00FFFF); static const Color aquamarine = Color(0xFF7FFFD4); static const Color azure = Color(0xFFF0FFFF); static const Color beige = Color(0xFFF5F5DC); static const Color bisque = Color(0xFFFFE4C4); static const Color black = Color(0xFF000000); static const Color blanchedAlmond = Color(0xFFFFEBCD); static const Color blue = Color(0xFF0000FF); static const Color blueViolet = Color(0xFF8A2BE2); static const Color brown = Color(0xFFA52A2A); static const Color burlyWood = Color(0xFFDEB887); static const Color cadetBlue = Color(0xFF5F9EA0); static const Color chartreuse = Color(0xFF7FFF00); static const Color chocolate = Color(0xFFD2691E); static const Color coral = Color(0xFFFF7F50); static const Color cornflowerBlue = Color(0xFF6495ED); static const Color cornsilk = Color(0xFFFFF8DC); static const Color crimson = Color(0xFFDC143C); static const Color cyan = Color(0xFF00FFFF); static const Color darkBlue = Color(0xFF00008B); static const Color darkCyan = Color(0xFF008B8B); static const Color darkGoldenRod = Color(0xFFB8860B); static const Color darkGray = Color(0xFFA9A9A9); static const Color darkGreen = Color(0xFF006400); static const Color darkGrey = Color(0xFFA9A9A9); static const Color darkKhaki = Color(0xFFBDB76B); static const Color darkMagenta = Color(0xFF8B008B); static const Color darkOliveGreen = Color(0xFF556B2F); static const Color darkOrange = Color(0xFFFF8C00); static const Color darkOrchid = Color(0xFF9932CC); static const Color darkRed = Color(0xFF8B0000); static const Color darkSalmon = Color(0xFFE9967A); static const Color darkSeaGreen = Color(0xFF8FBC8F); static const Color darkSlateBlue = Color(0xFF483D8B); static const Color darkSlateGray = Color(0xFF2F4F4F); static const Color darkSlateGrey = Color(0xFF2F4F4F); static const Color darkTurquoise = Color(0xFF00CED1); static const Color darkViolet = Color(0xFF9400D3); static const Color deepPink = Color(0xFFFF1493); static const Color deepSkyBlue = Color(0xFF00BFFF); static const Color dimGray = Color(0xFF696969); static const Color dimGrey = Color(0xFF696969); static const Color dodgerBlue = Color(0xFF1E90FF); static const Color fireBrick = Color(0xFFB22222); static const Color floralWhite = Color(0xFFFFFAF0); static const Color forestGreen = Color(0xFF228B22); static const Color fuchsia = Color(0xFFFF00FF); static const Color gainsboro = Color(0xFFDCDCDC); static const Color ghostWhite = Color(0xFFF8F8FF); static const Color gold = Color(0xFFFFD700); static const Color goldenRod = Color(0xFFDAA520); static const Color gray = Color(0xFF808080); static const Color green = Color(0xFF008000); static const Color greenYellow = Color(0xFFADFF2F); static const Color grey = Color(0xFF808080); static const Color honeyDew = Color(0xFFF0FFF0); static const Color hotPink = Color(0xFFFF69B4); static const Color indianRed = Color(0xFFCD5C5C); static const Color indigo = Color(0xFF4B0082); static const Color ivory = Color(0xFFFFFFF0); static const Color khaki = Color(0xFFF0E68C); static const Color lavender = Color(0xFFE6E6FA); static const Color lavenderBlush = Color(0xFFFFF0F5); static const Color lawnGreen = Color(0xFF7CFC00); static const Color lemonChiffon = Color(0xFFFFFACD); static const Color lightBlue = Color(0xFFADD8E6); static const Color lightCoral = Color(0xFFF08080); static const Color lightCyan = Color(0xFFE0FFFF); static const Color lightGoldenRodYellow = Color(0xFFFAFAD2); static const Color lightGray = Color(0xFFD3D3D3); static const Color lightGreen = Color(0xFF90EE90); static const Color lightGrey = Color(0xFFD3D3D3); static const Color lightPink = Color(0xFFFFB6C1); static const Color lightSalmon = Color(0xFFFFA07A); static const Color lightSeaGreen = Color(0xFF20B2AA); static const Color lightSkyBlue = Color(0xFF87CEFA); static const Color lightSlateGray = Color(0xFF778899); static const Color lightSlateGrey = Color(0xFF778899); static const Color lightSteelBlue = Color(0xFFB0C4DE); static const Color lightYellow = Color(0xFFFFFFE0); static const Color lime = Color(0xFF00FF00); static const Color limeGreen = Color(0xFF32CD32); static const Color linen = Color(0xFFFAF0E6); static const Color magenta = Color(0xFFFF00FF); static const Color maroon = Color(0xFF800000); static const Color mediumAquaMarine = Color(0xFF66CDAA); static const Color mediumBlue = Color(0xFF0000CD); static const Color mediumOrchid = Color(0xFFBA55D3); static const Color mediumPurple = Color(0xFF9370DB); static const Color mediumSeaGreen = Color(0xFF3CB371); static const Color mediumSlateBlue = Color(0xFF7B68EE); static const Color mediumSpringGreen = Color(0xFF00FA9A); static const Color mediumTurquoise = Color(0xFF48D1CC); static const Color mediumVioletRed = Color(0xFFC71585); static const Color midnightBlue = Color(0xFF191970); static const Color mintCream = Color(0xFFF5FFFA); static const Color mistyRose = Color(0xFFFFE4E1); static const Color moccasin = Color(0xFFFFE4B5); static const Color navajoWhite = Color(0xFFFFDEAD); static const Color navy = Color(0xFF000080); static const Color oldLace = Color(0xFFFDF5E6); static const Color olive = Color(0xFF808000); static const Color oliveDrab = Color(0xFF6B8E23); static const Color orange = Color(0xFFFFA500); static const Color orangeRed = Color(0xFFFF4500); static const Color orchid = Color(0xFFDA70D6); static const Color paleGoldenRod = Color(0xFFEEE8AA); static const Color paleGreen = Color(0xFF98FB98); static const Color paleTurquoise = Color(0xFFAFEEEE); static const Color paleVioletRed = Color(0xFFDB7093); static const Color papayaWhip = Color(0xFFFFEFD5); static const Color peachPuff = Color(0xFFFFDAB9); static const Color peru = Color(0xFFCD853F); static const Color pink = Color(0xFFFFC0CB); static const Color plum = Color(0xFFDDA0DD); static const Color powderBlue = Color(0xFFB0E0E6); static const Color purple = Color(0xFF800080); static const Color rebeccaPurple = Color(0xFF663399); static const Color red = Color(0xFFFF0000); static const Color rosyBrown = Color(0xFFBC8F8F); static const Color royalBlue = Color(0xFF4169E1); static const Color saddleBrown = Color(0xFF8B4513); static const Color salmon = Color(0xFFFA8072); static const Color sandyBrown = Color(0xFFF4A460); static const Color seaGreen = Color(0xFF2E8B57); static const Color seaShell = Color(0xFFFFF5EE); static const Color sienna = Color(0xFFA0522D); static const Color silver = Color(0xFFC0C0C0); static const Color skyBlue = Color(0xFF87CEEB); static const Color slateBlue = Color(0xFF6A5ACD); static const Color slateGray = Color(0xFF708090); static const Color slateGrey = Color(0xFF708090); static const Color snow = Color(0xFFFFFAFA); static const Color springGreen = Color(0xFF00FF7F); static const Color steelBlue = Color(0xFF4682B4); static const Color tan = Color(0xFFD2B48C); static const Color teal = Color(0xFF008080); static const Color thistle = Color(0xFFD8BFD8); static const Color tomato = Color(0xFFFF6347); static const Color turquoise = Color(0xFF40E0D0); static const Color violet = Color(0xFFEE82EE); static const Color wheat = Color(0xFFF5DEB3); static const Color white = Color(0xFFFFFFFF); static const Color whiteSmoke = Color(0xFFF5F5F5); static const Color yellow = Color(0xFFFFFF00); static const Color yellowGreen = Color(0xFF9ACD32); }
packages/packages/css_colors/lib/css_colors.dart/0
{ "file_path": "packages/packages/css_colors/lib/css_colors.dart", "repo_id": "packages", "token_count": 2755 }
982
#include "ephemeral/Flutter-Generated.xcconfig"
packages/packages/dynamic_layouts/example/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "packages/packages/dynamic_layouts/example/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
983
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.action; import static androidx.test.espresso.flutter.action.ActionUtil.loopUntilCompletion; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isFlutterView; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.Futures.transformAsync; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import android.os.Looper; import android.view.View; import androidx.test.annotation.ExperimentalTestApi; import androidx.test.espresso.IdlingRegistry; import androidx.test.espresso.IdlingResource; import androidx.test.espresso.UiController; import androidx.test.espresso.ViewAction; import androidx.test.espresso.flutter.api.FlutterAction; import androidx.test.espresso.flutter.api.FlutterTestingProtocol; import androidx.test.espresso.flutter.api.WidgetMatcher; import androidx.test.espresso.flutter.internal.idgenerator.IdGenerator; import androidx.test.espresso.flutter.internal.jsonrpc.JsonRpcClient; import androidx.test.espresso.flutter.internal.protocol.impl.DartVmService; import androidx.test.espresso.flutter.internal.protocol.impl.DartVmServiceUtil; import androidx.test.espresso.flutter.internal.protocol.impl.FlutterProtocolException; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.JdkFutureAdapters; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.flutter.embedding.android.FlutterView; import io.flutter.embedding.engine.FlutterJNI; import java.net.URI; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import okhttp3.OkHttpClient; import org.hamcrest.Matcher; /** * A {@code ViewAction} which performs an action on the given {@code FlutterView}. * * <p>This class acts as a bridge to perform {@code WidgetAction} on a Flutter widget on the given * {@code FlutterView}. */ public final class FlutterViewAction<T> implements ViewAction { private static final String FLUTTER_IDLE_TASK_NAME = "flutterIdlingResource"; private final SettableFuture<T> resultFuture = SettableFuture.create(); private final WidgetMatcher widgetMatcher; private final FlutterAction<T> widgetAction; private final OkHttpClient webSocketClient; private final IdGenerator<Integer> messageIdGenerator; private final ExecutorService taskExecutor; /** * Constructs an instance based on the given params. * * @param widgetMatcher the matcher that uniquely matches a widget on the {@code FlutterView}. * Could be {@code null} if this is a universal action that doesn't apply to any specific * widget. * @param widgetAction the action to be performed on the matched Flutter widget. * @param webSocketClient the WebSocket client that shall be used in the {@code * FlutterTestingProtocol}. * @param messageIdGenerator an ID generator that shall be used in the {@code * FlutterTestingProtocol}. * @param taskExecutor the task executor that shall be used in the {@code WidgetAction}. */ public FlutterViewAction( WidgetMatcher widgetMatcher, FlutterAction<T> widgetAction, OkHttpClient webSocketClient, IdGenerator<Integer> messageIdGenerator, ExecutorService taskExecutor) { this.widgetMatcher = widgetMatcher; this.widgetAction = checkNotNull(widgetAction); this.webSocketClient = checkNotNull(webSocketClient); this.messageIdGenerator = checkNotNull(messageIdGenerator); this.taskExecutor = checkNotNull(taskExecutor); } @Override public Matcher<View> getConstraints() { return isFlutterView(); } @Override public String getDescription() { return String.format( "Perform a %s action on the Flutter widget matched %s.", widgetAction, widgetMatcher); } @ExperimentalTestApi @Override public void perform(UiController uiController, View flutterView) { // There could be a gap between when the Flutter view is available in the view hierarchy and the // engine & Dart isolates are actually up and running. Check whether the first frame has been // rendered before proceeding in an unblocking way. loopUntilFlutterViewRendered(flutterView, uiController); // The url {@code FlutterNativeView} returns is the http url that the Dart VM Observatory http // server serves at. Need to convert to the one that the WebSocket uses. URI dartVmServiceProtocolUrl = DartVmServiceUtil.getServiceProtocolUri(FlutterJNI.getVMServiceUri()); String isolateId = DartVmServiceUtil.getDartIsolateId(flutterView); final FlutterTestingProtocol flutterTestingProtocol = new DartVmService( isolateId, new JsonRpcClient(webSocketClient, dartVmServiceProtocolUrl), messageIdGenerator, taskExecutor); try { // First checks the testing protocol is ready for use and then waits until the Flutter app is // idle before executing the action. ListenableFuture<Void> testingProtocolReadyFuture = JdkFutureAdapters.listenInPoolThread(flutterTestingProtocol.connect()); AsyncFunction<Void, Void> flutterIdleFunc = new AsyncFunction<Void, Void>() { public ListenableFuture<Void> apply(Void readyResult) { return JdkFutureAdapters.listenInPoolThread(flutterTestingProtocol.waitUntilIdle()); } }; ListenableFuture<Void> flutterIdleFuture = transformAsync(testingProtocolReadyFuture, flutterIdleFunc, taskExecutor); loopUntilCompletion(FLUTTER_IDLE_TASK_NAME, uiController, flutterIdleFuture, taskExecutor); perform(flutterView, flutterTestingProtocol, uiController); } catch (ExecutionException ee) { resultFuture.setException(ee.getCause()); } catch (InterruptedException ie) { resultFuture.setException(ie); } } @ExperimentalTestApi @VisibleForTesting void perform( View flutterView, FlutterTestingProtocol flutterTestingProtocol, UiController uiController) { final ListenableFuture<T> actionResultFuture = JdkFutureAdapters.listenInPoolThread( widgetAction.perform(widgetMatcher, flutterView, flutterTestingProtocol, uiController)); actionResultFuture.addListener( new Runnable() { @Override public void run() { try { resultFuture.set(actionResultFuture.get()); } catch (ExecutionException | InterruptedException e) { resultFuture.setException(e); } } }, directExecutor()); } /** Blocks until this action has completed execution. */ public T waitUntilCompleted() throws ExecutionException, InterruptedException { checkState(Looper.myLooper() != Looper.getMainLooper(), "On main thread!"); return resultFuture.get(); } /** Blocks until this action has completed execution with a configurable timeout. */ public T waitUntilCompleted(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { checkState(Looper.myLooper() != Looper.getMainLooper(), "On main thread!"); return resultFuture.get(timeout, unit); } private static void loopUntilFlutterViewRendered(View flutterView, UiController uiController) { FlutterViewRenderedIdlingResource idlingResource = new FlutterViewRenderedIdlingResource(flutterView); try { IdlingRegistry.getInstance().register(idlingResource); uiController.loopMainThreadUntilIdle(); } finally { IdlingRegistry.getInstance().unregister(idlingResource); } } /** * An {@link IdlingResource} that checks whether the Flutter view's first frame has been rendered * in an unblocking way. */ static final class FlutterViewRenderedIdlingResource implements IdlingResource { private final View flutterView; // Written from main thread, read from any thread. private volatile ResourceCallback resourceCallback; FlutterViewRenderedIdlingResource(View flutterView) { this.flutterView = checkNotNull(flutterView); } @Override public String getName() { return FlutterViewRenderedIdlingResource.class.getSimpleName(); } @SuppressWarnings("deprecation") @Override public boolean isIdleNow() { boolean isIdle = false; if (flutterView instanceof FlutterView) { isIdle = ((FlutterView) flutterView).hasRenderedFirstFrame(); } else if (flutterView instanceof io.flutter.view.FlutterView) { isIdle = ((io.flutter.view.FlutterView) flutterView).hasRenderedFirstFrame(); } else { throw new FlutterProtocolException( String.format("This is not a Flutter View instance [id: %d].", flutterView.getId())); } if (isIdle) { resourceCallback.onTransitionToIdle(); } return isIdle; } @Override public void registerIdleTransitionCallback(ResourceCallback callback) { resourceCallback = callback; } } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java", "repo_id": "packages", "token_count": 3184 }
984
// Copyright 2013 The Flutter 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.exception; import androidx.test.espresso.EspressoException; /** Indicates that the {@code View} that Espresso operates on is not a valid Flutter View. */ public final class InvalidFlutterViewException extends RuntimeException implements EspressoException { private static final long serialVersionUID = 0L; /** Constructs with an error message. */ public InvalidFlutterViewException(String message) { super(message); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/exception/InvalidFlutterViewException.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/exception/InvalidFlutterViewException.java", "repo_id": "packages", "token_count": 171 }
985
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.internal.protocol.impl; import static com.google.common.base.Preconditions.checkNotNull; import android.util.Log; import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcResponse; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Ascii; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Objects; /** Represents a response of the {@code GetWidgetDiagnosticsAction}. */ final class GetWidgetDiagnosticsResponse { private static final String TAG = GetWidgetDiagnosticsResponse.class.getSimpleName(); private static final Gson gson = new Gson(); @Expose private boolean isError; @Expose @SerializedName("response") private DiagnosticNodeInfo widgetInfo; private GetWidgetDiagnosticsResponse() {} /** * Builds the {@code GetWidgetDiagnosticsResponse} out of the JSON-RPC response. * * @param jsonRpcResponse the JSON-RPC response. Cannot be {@code null}. * @return a {@code GetWidgetDiagnosticsResponse} instance that's parsed out from the JSON-RPC * response. */ public static GetWidgetDiagnosticsResponse fromJsonRpcResponse(JsonRpcResponse jsonRpcResponse) { checkNotNull(jsonRpcResponse, "The JSON-RPC response cannot be null."); if (jsonRpcResponse.getResult() == null) { throw new FlutterProtocolException( String.format( "Error occurred during retrieving widget's diagnostics info. Response received: %s.", jsonRpcResponse)); } try { return gson.fromJson(jsonRpcResponse.getResult(), GetWidgetDiagnosticsResponse.class); } catch (JsonSyntaxException e) { throw new FlutterProtocolException( String.format( "Error occurred during retrieving widget's diagnostics info. Response received: %s.", jsonRpcResponse), e); } } /** Returns whether this is an error response. */ public boolean isError() { return isError; } /** Returns the runtime type of this widget, or {@code null} if the type info is not available. */ public String getRuntimeType() { if (widgetInfo == null) { Log.w(TAG, "Widget info is null."); return null; } else { return widgetInfo.runtimeType; } } /** * Gets the widget property by its name, or null if the property doesn't exist. * * @param propertyName the property name. Cannot be {@code null}. */ public WidgetProperty getPropertyByName(String propertyName) { checkNotNull(propertyName, "Widget property name cannot be null."); if (widgetInfo == null) { Log.w(TAG, "Widget info is null."); return null; } return widgetInfo.getPropertyByName(propertyName); } /** * Returns the description of this widget, or {@code null} if the diagnostics info is not * available. */ public String getDescription() { if (widgetInfo == null) { Log.w(TAG, "Widget info is null."); return null; } return widgetInfo.description; } /** * Returns whether this widget has children, or {@code false} if the diagnostics info is not * available. */ public boolean isHasChildren() { if (widgetInfo == null) { Log.w(TAG, "Widget info is null."); return false; } return widgetInfo.hasChildren; } @Override public String toString() { return gson.toJson(this); } /** A data structure that holds a widget's diagnostics info. */ static class DiagnosticNodeInfo { @Expose @SerializedName("widgetRuntimeType") private String runtimeType; @Expose private List<WidgetProperty> properties; @Expose private String description; @Expose private boolean hasChildren; WidgetProperty getPropertyByName(String propertyName) { checkNotNull(propertyName, "Widget property name cannot be null."); if (properties == null) { Log.w(TAG, "Widget property list is null."); return null; } for (WidgetProperty property : properties) { if (Ascii.equalsIgnoreCase(propertyName, property.getName())) { return property; } } return null; } } /** Represents a widget property. */ static class WidgetProperty { @Expose private final String name; @Expose private final String value; @Expose private final String description; @VisibleForTesting WidgetProperty(String name, String value, String description) { this.name = name; this.value = value; this.description = description; } /** Returns the name of this widget property. */ public String getName() { return name; } /** Returns the value of this widget property. */ public String getValue() { return value; } /** Returns the description of this widget property. */ public String getDescription() { return description; } @Override public boolean equals(Object obj) { if (!(obj instanceof WidgetProperty)) { return false; } else { WidgetProperty widgetProperty = (WidgetProperty) obj; return Objects.equals(this.name, widgetProperty.name) && Objects.equals(this.value, widgetProperty.value) && Objects.equals(this.description, widgetProperty.description); } } @Override public int hashCode() { return Objects.hash(name, value, description); } } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java", "repo_id": "packages", "token_count": 1976 }
986
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.espresso; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; /** EspressoPlugin */ public class EspressoPlugin implements FlutterPlugin, MethodCallHandler { @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { final MethodChannel channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "espresso"); channel.setMethodCallHandler(new EspressoPlugin()); } // This static function is optional and equivalent to onAttachedToEngine. It supports the old // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting // plugin registration via this function while apps migrate to use the new Android APIs // post-flutter-1.12 via https://flutter.dev/go/android-project-migration. // // It is encouraged to share logic between onAttachedToEngine and registerWith to keep // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called // depending on the user's project. onAttachedToEngine or registerWith must both be defined // in the same class. @SuppressWarnings("deprecation") public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), "espresso"); channel.setMethodCallHandler(new EspressoPlugin()); } @Override public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) { if (call.method.equals("getPlatformVersion")) { result.success("Android " + android.os.Build.VERSION.RELEASE); } else { result.notImplemented(); } } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} }
packages/packages/espresso/android/src/main/java/com/example/espresso/EspressoPlugin.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/com/example/espresso/EspressoPlugin.java", "repo_id": "packages", "token_count": 617 }
987
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector/file_selector.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select one or more directories using `getDirectoryPaths`, /// then displays the selected directories in a dialog. class GetMultipleDirectoriesPage extends StatelessWidget { /// Returns a new instance of the page. const GetMultipleDirectoriesPage({super.key}); Future<void> _getDirectoryPaths(BuildContext context) async { const String confirmButtonText = 'Choose'; final List<String?> directoryPaths = await getDirectoryPaths( confirmButtonText: confirmButtonText, ); if (directoryPaths.isEmpty) { // Operation was canceled by the user. return; } String paths = ''; for (final String? path in directoryPaths) { paths += '${path!} \n'; } if (context.mounted) { await showDialog<void>( context: context, builder: (BuildContext context) => TextDisplay(paths), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Select multiple directories'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, ), child: const Text( 'Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog. class TextDisplay extends StatelessWidget { /// Creates a `TextDisplay`. const TextDisplay(this.directoriesPaths, {super.key}); /// The path selected in the dialog. final String directoriesPaths; @override Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), content: Scrollbar( child: SingleChildScrollView( child: Text(directoriesPaths), ), ), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () => Navigator.pop(context), ), ], ); } }
packages/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart/0
{ "file_path": "packages/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart", "repo_id": "packages", "token_count": 975 }
988
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.flutter.packages.file_selector_android_example; import static androidx.test.espresso.flutter.EspressoFlutter.onFlutterWidget; import static androidx.test.espresso.flutter.action.FlutterActions.click; import static androidx.test.espresso.flutter.assertion.FlutterAssertions.matches; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isExisting; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withText; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withValueKey; import static androidx.test.espresso.intent.Intents.intended; import static androidx.test.espresso.intent.Intents.intending; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; import android.app.Activity; import android.app.Instrumentation; import android.content.ClipData; import android.content.Intent; import android.net.Uri; import androidx.test.core.app.ActivityScenario; import androidx.test.espresso.intent.rule.IntentsRule; import androidx.test.ext.junit.rules.ActivityScenarioRule; import org.junit.Rule; import org.junit.Test; public class FileSelectorAndroidTest { @Rule public ActivityScenarioRule<DriverExtensionActivity> myActivityTestRule = new ActivityScenarioRule<>(DriverExtensionActivity.class); @Rule public IntentsRule intentsRule = new IntentsRule(); public void clearAnySystemDialog() { myActivityTestRule .getScenario() .onActivity( new ActivityScenario.ActivityAction<DriverExtensionActivity>() { @Override public void perform(DriverExtensionActivity activity) { Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); activity.sendBroadcast(closeDialog); } }); } @Test public void openImageFile() { clearAnySystemDialog(); final Instrumentation.ActivityResult result = new Instrumentation.ActivityResult( Activity.RESULT_OK, new Intent().setData(Uri.parse("content://file_selector_android_test/dummy.png"))); intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(result); onFlutterWidget(withText("Open an image")).perform(click()); onFlutterWidget(withText("Press to open an image file(png, jpg)")).perform(click()); intended(hasAction(Intent.ACTION_OPEN_DOCUMENT)); onFlutterWidget(withValueKey("result_image_name")) .check(matches(withText("content://file_selector_android_test/dummy.png"))); } @Test public void openImageFiles() { clearAnySystemDialog(); final ClipData.Item clipDataItem = new ClipData.Item(Uri.parse("content://file_selector_android_test/dummy.png")); final ClipData clipData = new ClipData("", new String[0], clipDataItem); clipData.addItem(clipDataItem); final Intent resultIntent = new Intent(); resultIntent.setClipData(clipData); final Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultIntent); intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(result); onFlutterWidget(withText("Open multiple images")).perform(click()); onFlutterWidget(withText("Press to open multiple images (png, jpg)")).perform(click()); intended(hasAction(Intent.ACTION_OPEN_DOCUMENT)); intended(hasExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)); onFlutterWidget(withValueKey("result_image_name0")).check(matches(isExisting())); onFlutterWidget(withValueKey("result_image_name1")).check(matches(isExisting())); } }
packages/packages/file_selector/file_selector_android/example/android/app/src/androidTest/java/dev/flutter/packages/file_selector_android_example/FileSelectorAndroidTest.java/0
{ "file_path": "packages/packages/file_selector/file_selector_android/example/android/app/src/androidTest/java/dev/flutter/packages/file_selector_android_example/FileSelectorAndroidTest.java", "repo_id": "packages", "token_count": 1320 }
989
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/cupertino.dart'; import 'file_selector_api.g.dart'; /// An implementation of [FileSelectorPlatform] for Android. class FileSelectorAndroid extends FileSelectorPlatform { FileSelectorAndroid({@visibleForTesting FileSelectorApi? api}) : _api = api ?? FileSelectorApi(); final FileSelectorApi _api; /// Registers this class as the implementation of the file_selector platform interface. static void registerWith() { FileSelectorPlatform.instance = FileSelectorAndroid(); } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final FileResponse? file = await _api.openFile( initialDirectory, _fileTypesFromTypeGroups(acceptedTypeGroups), ); return file == null ? null : _xFileFromFileResponse(file); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<FileResponse?> files = await _api.openFiles( initialDirectory, _fileTypesFromTypeGroups(acceptedTypeGroups), ); return files .cast<FileResponse>() .map<XFile>(_xFileFromFileResponse) .toList(); } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { return _api.getDirectoryPath(initialDirectory); } XFile _xFileFromFileResponse(FileResponse file) { return XFile.fromData( file.bytes, // Note: The name parameter is not used by XFile. The XFile.name returns // the extracted file name from XFile.path. name: file.name, length: file.size, mimeType: file.mimeType, path: file.path, ); } FileTypes _fileTypesFromTypeGroups(List<XTypeGroup>? typeGroups) { if (typeGroups == null) { return FileTypes(extensions: <String>[], mimeTypes: <String>[]); } final Set<String> mimeTypes = <String>{}; final Set<String> extensions = <String>{}; for (final XTypeGroup group in typeGroups) { if (!group.allowsAny && group.mimeTypes == null && group.extensions == null) { throw ArgumentError( 'Provided type group $group does not allow all files, but does not ' 'set any of the Android supported filter categories. At least one of ' '"extensions" or "mimeTypes" must be non-empty for Android.', ); } mimeTypes.addAll(group.mimeTypes ?? <String>{}); extensions.addAll(group.extensions ?? <String>{}); } return FileTypes( mimeTypes: mimeTypes.toList(), extensions: extensions.toList(), ); } }
packages/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart", "repo_id": "packages", "token_count": 1107 }
990
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_ios/file_selector_ios.dart'; import 'package:file_selector_ios/src/messages.g.dart'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'file_selector_ios_test.mocks.dart'; import 'test_api.g.dart'; @GenerateMocks(<Type>[TestFileSelectorApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); final FileSelectorIOS plugin = FileSelectorIOS(); late MockTestFileSelectorApi mockApi; setUp(() { mockApi = MockTestFileSelectorApi(); TestFileSelectorApi.setup(mockApi); }); test('registered instance', () { FileSelectorIOS.registerWith(); expect(FileSelectorPlatform.instance, isA<FileSelectorIOS>()); }); group('openFile', () { setUp(() { when(mockApi.openFile(any)).thenAnswer((_) async => <String>['foo']); }); test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], uniformTypeIdentifiers: <String>['public.text'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], uniformTypeIdentifiers: <String>['public.image'], webWildCards: <String>['image/*']); await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; // iOS only accepts uniformTypeIdentifiers. expect(listEquals(config.utis, <String>['public.text', 'public.image']), isTrue); expect(config.allowMultiSelection, isFalse); }); test('throws for a type group that does not support iOS', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('correctly handles no type groups', () async { await expectLater(plugin.openFile(), completes); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; expect(listEquals(config.utis, <String>['public.data']), isTrue); }); test('correctly handles a wildcard group', () async { const XTypeGroup group = XTypeGroup( label: 'text', ); await expectLater( plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; expect(listEquals(config.utis, <String>['public.data']), isTrue); }); }); group('openFiles', () { setUp(() { when(mockApi.openFile(any)).thenAnswer((_) async => <String>['foo']); }); test('passes the accepted type groups correctly', () async { const XTypeGroup group = XTypeGroup( label: 'text', extensions: <String>['txt'], mimeTypes: <String>['text/plain'], uniformTypeIdentifiers: <String>['public.text'], ); const XTypeGroup groupTwo = XTypeGroup( label: 'image', extensions: <String>['jpg'], mimeTypes: <String>['image/jpg'], uniformTypeIdentifiers: <String>['public.image'], webWildCards: <String>['image/*']); await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; // iOS only accepts uniformTypeIdentifiers. expect(listEquals(config.utis, <String>['public.text', 'public.image']), isTrue); expect(config.allowMultiSelection, isTrue); }); test('throws for a type group that does not support iOS', () async { const XTypeGroup group = XTypeGroup( label: 'images', webWildCards: <String>['images/*'], ); await expectLater( plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), throwsArgumentError); }); test('correctly handles no type groups', () async { await expectLater(plugin.openFiles(), completes); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; expect(listEquals(config.utis, <String>['public.data']), isTrue); }); test('correctly handles a wildcard group', () async { const XTypeGroup group = XTypeGroup( label: 'text', ); await expectLater( plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes); final VerificationResult result = verify(mockApi.openFile(captureAny)); final FileSelectorConfig config = result.captured[0] as FileSelectorConfig; expect(listEquals(config.utis, <String>['public.data']), isTrue); }); }); }
packages/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart", "repo_id": "packages", "token_count": 2203 }
991
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PLUGINS_FILE_SELECTOR_LINUX_FILE_SELECTOR_PLUGIN_H_ #define PLUGINS_FILE_SELECTOR_LINUX_FILE_SELECTOR_PLUGIN_H_ // A plugin to show native save/open file choosers. #include <flutter_linux/flutter_linux.h> G_BEGIN_DECLS #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) #else #define FLUTTER_PLUGIN_EXPORT #endif G_DECLARE_FINAL_TYPE(FlFileSelectorPlugin, fl_file_selector_plugin, FL, FILE_SELECTOR_PLUGIN, GObject) FLUTTER_PLUGIN_EXPORT FlFileSelectorPlugin* fl_file_selector_plugin_new( FlPluginRegistrar* registrar); FLUTTER_PLUGIN_EXPORT void file_selector_plugin_register_with_registrar( FlPluginRegistrar* registrar); G_END_DECLS #endif // PLUGINS_FILE_SELECTOR_LINUX_FILE_SELECTOR_PLUGIN_H_
packages/packages/file_selector/file_selector_linux/linux/include/file_selector_linux/file_selector_plugin.h/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/linux/include/file_selector_linux/file_selector_plugin.h", "repo_id": "packages", "token_count": 378 }
992
<?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>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> </dict> </plist>
packages/packages/file_selector/file_selector_macos/example/macos/Runner/Release.entitlements/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/example/macos/Runner/Release.entitlements", "repo_id": "packages", "token_count": 137 }
993
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.6.2 * Updates minimum required plugin_platform_interface version to 2.1.7. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.6.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.6.0 * Adds `getSaveLocation` and deprecates `getSavePath`. ## 2.5.1 * Adds compatibility with `http` 1.0. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.5.0 * Deprecates `macUTIs` in favor of `uniformTypeIdentifiers`. * Aligns Dart and Flutter SDK constraints. ## 2.4.1 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.4.0 * Adds `getDirectoryPaths` method to the interface. ## 2.3.0 * Replaces `macUTIs` with `uniformTypeIdentifiers`. `macUTIs` is available as an alias, but will be deprecated in a future release. ## 2.2.0 * Makes `XTypeGroup`'s constructor constant. ## 2.1.1 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 2.1.0 * Adds `allowsAny` to `XTypeGroup` as a simple and future-proof way of identifying wildcard groups. ## 2.0.4 * Removes dependency on `meta`. ## 2.0.3 * Minor code cleanup for new analysis rules. * Update to use the `verify` method introduced in plugin_platform_interface 2.1.0. ## 2.0.2 * Update platform_plugin_interface version requirement. ## 2.0.1 * Replace extensions with leading dots. ## 2.0.0 * Migration to null-safety ## 1.0.3+1 * Bump the [cross_file](https://pub.dev/packages/cross_file) package version. ## 1.0.3 * Update Flutter SDK constraint. ## 1.0.2 * Replace locally defined `XFile` types with the versions from the [cross_file](https://pub.dev/packages/cross_file) package. ## 1.0.1 * Allow type groups that allow any file. ## 1.0.0 * Initial release.
packages/packages/file_selector/file_selector_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/file_selector/file_selector_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 663 }
994
## 0.9.4+1 * Removes a few deprecated API usages. ## 0.9.4 * Updates web code to package `web: ^0.5.0`. * Updates SDK version to Dart `^3.3.0`. Flutter `^3.16.0`. ## 0.9.3 * Updates minimum supported SDK version to Dart 3.2. ## 0.9.2+1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.9.2 * Adds and propagates `cancel` event on file selection. * Changes `openFile` to return `null` when no files are selected/selection is canceled, as in other platforms. ## 0.9.1 * Adds `getSaveLocation` and deprecates `getSavePath`. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.9.0+4 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.9.0+3 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 0.9.0+2 * Changes XTypeGroup initialization from final to const. ## 0.9.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. ## 0.9.0 * **BREAKING CHANGE**: Methods that take `XTypeGroup`s now throw an `ArgumentError` if any group is not a wildcard (all filter types null or empty), but doesn't include any of the filter types supported by web. ## 0.8.1+5 * Minor fixes for new analysis options. ## 0.8.1+4 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.1+3 * Minor code cleanup for new analysis rules. * Removes dependency on `meta`. ## 0.8.1+2 * Add `implements` to pubspec. # 0.8.1+1 - Updated installation instructions in README. # 0.8.1 - Return a non-null value from `getSavePath` for consistency with API expectations that null indicates canceling. # 0.8.0 - Migrated to null-safety # 0.7.0+1 - Add dummy `ios` dir, so flutter sdk can be lower than 1.20 # 0.7.0 - Initial open-source release.
packages/packages/file_selector/file_selector_web/CHANGELOG.md/0
{ "file_path": "packages/packages/file_selector/file_selector_web/CHANGELOG.md", "repo_id": "packages", "token_count": 701 }
995
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'dart:typed_data'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select a save location using `getSavePath`, /// then writes text to a file at that location. class SaveTextPage extends StatelessWidget { /// Default Constructor SaveTextPage({super.key}); final TextEditingController _nameController = TextEditingController(); final TextEditingController _contentController = TextEditingController(); Future<void> _saveFile() async { final String fileName = _nameController.text; final FileSaveLocation? result = await FileSelectorPlatform.instance.getSaveLocation( options: SaveDialogOptions(suggestedName: fileName), acceptedTypeGroups: const <XTypeGroup>[ XTypeGroup( label: 'Plain text', extensions: <String>['txt'], ), XTypeGroup( label: 'JSON', extensions: <String>['json'], ), ], ); // Operation was canceled by the user. if (result == null) { return; } String path = result.path; // Append an extension based on the selected type group if the user didn't // include one. if (!path.split(Platform.pathSeparator).last.contains('.')) { final XTypeGroup? activeGroup = result.activeFilter; if (activeGroup != null) { // The group is one of the groups passed in above, each of which has // exactly one `extensions` entry. path = '$path.${activeGroup.extensions!.first}'; } } final String text = _contentController.text; final Uint8List fileData = Uint8List.fromList(text.codeUnits); final XFile textFile = XFile.fromData(fileData, name: fileName); await textFile.saveTo(result.path); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Save text into a file'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: 300, child: TextField( minLines: 1, maxLines: 12, controller: _nameController, decoration: const InputDecoration( hintText: '(Optional) Suggest File Name', ), ), ), SizedBox( width: 300, child: TextField( minLines: 1, maxLines: 12, controller: _contentController, decoration: const InputDecoration( hintText: 'Enter File Contents', ), ), ), const SizedBox(height: 10), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, ), onPressed: _saveFile, child: const Text('Press to save a text file'), ), ], ), ), ); } }
packages/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart", "repo_id": "packages", "token_count": 1470 }
996
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "include/file_selector_windows/file_selector_windows.h" #include <flutter/plugin_registrar_windows.h> #include "file_selector_plugin.h" void FileSelectorWindowsRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { file_selector_windows::FileSelectorPlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar<flutter::PluginRegistrarWindows>(registrar)); }
packages/packages/file_selector/file_selector_windows/windows/file_selector_windows.cpp/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/windows/file_selector_windows.cpp", "repo_id": "packages", "token_count": 193 }
997
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_adaptive_scaffold/src/breakpoints.dart'; class TestBreakpoint0 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width >= 0 && MediaQuery.of(context).size.width < 800; } } class TestBreakpoint400 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width > 400; } } class TestBreakpoint800 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width >= 800 && MediaQuery.of(context).size.width < 1000; } } class TestBreakpoint1000 extends Breakpoint { @override bool isActive(BuildContext context) { return MediaQuery.of(context).size.width >= 1000; } } class NeverOnBreakpoint extends Breakpoint { @override bool isActive(BuildContext context) { return false; } } class AppBarAlwaysOnBreakpoint extends Breakpoint { @override bool isActive(BuildContext context) { return true; } }
packages/packages/flutter_adaptive_scaffold/test/test_breakpoints.dart/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/test/test_breakpoints.dart", "repo_id": "packages", "token_count": 401 }
998
# Recommended lints for Flutter apps, packages, and plugins. include: package:lints/recommended.yaml linter: rules: - avoid_print - avoid_unnecessary_containers - avoid_web_libraries_in_flutter - no_logic_in_create_state - prefer_const_constructors - prefer_const_constructors_in_immutables - prefer_const_declarations - prefer_const_literals_to_create_immutables - sized_box_for_whitespace - sort_child_properties_last - use_build_context_synchronously - use_full_hex_values_for_flutter_colors - use_key_in_widget_constructors
packages/packages/flutter_lints/lib/flutter.yaml/0
{ "file_path": "packages/packages/flutter_lints/lib/flutter.yaml", "repo_id": "packages", "token_count": 222 }
999
# Markdown Test Page # Basic Syntax ## Headings --- # Heading One Sint sit cillum pariatur eiusmod nulla pariatur ipsum. Sit laborum anim qui mollit tempor pariatur nisi minim dolor. Aliquip et adipisicing sit sit fugiat commodo id sunt. Nostrud enim ad commodo incididunt cupidatat in ullamco ullamco Lorem cupidatat velit enim et Lorem. ## Heading Two Aute officia nulla deserunt do deserunt cillum velit magna. Officia veniam culpa anim minim dolore labore pariatur voluptate id ad est duis quis velit dolor pariatur enim. Incididunt enim excepteur do veniam consequat culpa do voluptate dolor fugiat ad adipisicing sit. ### Heading Three Voluptate cupidatat cillum elit quis ipsum eu voluptate fugiat consectetur enim. Quis ut voluptate culpa ex anim aute consectetur dolore proident voluptate exercitation eiusmod. Esse in do anim magna minim culpa sint. #### Heading Four Commodo fugiat aliqua minim quis pariatur mollit id tempor. Non occaecat minim esse enim aliqua adipisicing nostrud duis consequat eu adipisicing qui. Minim aliquip sit excepteur ipsum consequat laborum pariatur excepteur. ##### Heading Five Veniam enim esse amet veniam deserunt laboris amet enim consequat. Minim nostrud deserunt cillum consectetur commodo eu enim nostrud ullamco occaecat excepteur. Aliquip et ut est commodo enim dolor amet sint excepteur. ###### Heading Six Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ## Paragraphs --- Incididunt ex adipisicing ea ullamco consectetur in voluptate proident fugiat tempor deserunt reprehenderit ullamco id dolore laborum. Do laboris laboris minim incididunt qui consectetur exercitation adipisicing dolore et magna consequat magna anim sunt. Officia fugiat Lorem sunt pariatur incididunt Lorem reprehenderit proident irure. Officia dolore laborum aute incididunt commodo nisi velit est est elit et dolore elit exercitation. Enim aliquip magna id ipsum aliquip consectetur ad nulla quis. Incididunt pariatur dolor consectetur cillum enim velit cupidatat laborum quis ex. Officia irure in non voluptate adipisicing sit amet tempor duis dolore deserunt enim ut. Reprehenderit incididunt in ad anim et deserunt deserunt Lorem laborum quis. Enim aute anim labore proident laboris voluptate elit excepteur in. ## Inline Emphasis - Bold and Italic --- Sint ea do **exercitation** incididunt et minim ad labore sunt. Minim deserunt labore laboris velit nulla incididunt ipsum nulla. **Consequat commodo** reprehenderit duis esse esse ex**ercita**tion minim enim Lorem dolore duis irure. Et ad ipsum labore enim ipsum **cupidatat consequat**. Commodo non ea __cupidatat magna__ deserunt dolore ipsum velit nulla elit veniam nulla eiusmod proident officia. *"Proident sit veniam in est proident officia adipisicing"* ea tempor cillum non cillum velit deserunt. Sit tempor ad*ipisic*ing ea laboris anim aute reprehenderit id eu ea. Aute Lorem minim _adipisicing nostrud mollit_ ad ut voluptate do nulla esse occaecat aliqua sint anim. ## Blockquotes --- Ad nisi laborum aute cupidatat magna deserunt eu id laboris id. Aliquip nulla cupidatat sint ex Lorem mollit laborum dolor amet est ut esse aute. Nostrud ex consequat id incididunt proident ipsum minim duis aliqua ut ex et ad quis. > Ipsum et cupidatat mollit exercitation enim duis sunt irure aliqua reprehenderit mollit. Pariatur Lorem pariatur laboris do culpa do elit irure. Labore ea magna Lorem consequat aliquip consectetur cillum duis dolore. Et veniam dolor qui incididunt minim amet laboris sit. > Qui est sit et reprehenderit aute est esse enim aliqua id aliquip ea anim. Pariatur sint reprehenderit mollit velit voluptate enim consectetur sint enim. Quis exercitation proident elit non id qui culpa dolore esse aliquip consequat. ## Lists --- ### Ordered List 1. Longan 2. Lychee 3. Excepteur ad cupidatat do elit laborum amet cillum reprehenderit consequat quis. Deserunt officia esse aliquip consectetur duis ut labore laborum commodo aliquip aliquip velit pariatur dolore. 4. Marionberry 4. Melon - Cantaloupe - Honeydew - Watermelon 6. Miracle fruit 7. Mulberry 9. Strawberry 12. Plum ### Unordered List - Olive - Orange - Blood orange - Clementine - Papaya - Ut aute ipsum occaecat nisi culpa Lorem id occaecat cupidatat id id magna laboris ad duis. Fugiat cillum dolore veniam nostrud proident sint consectetur eiusmod irure adipisicing. - Passionfruit ## Inline Code --- Duis duis est `code in text` velit velit aute culpa ex quis pariatur pariatur laborum aute pariatur duis tempor sunt ad. Irure magna voluptate dolore consectetur consectetur irure esse. Anim magna `md.ExtensionSet.GitHub` dolor. ## Horizontal Rule --- In dolore velit aliquip labore mollit minim tempor veniam eu veniam ad in sint aliquip mollit mollit. Ex occaecat non deserunt elit laborum sunt tempor sint consequat culpa culpa qui sit. *** or --- or ____________ In laboris eiusmod reprehenderit aliquip sit proident occaecat. Non sit labore anim elit veniam Lorem minim commodo eiusmod irure do minim nisi. ## Link --- [Google]: https://www.google.com Excepteur ad cupidatat do elit laborum amet cillum reprehenderit consequat quis. Deserunt officia esse [Flutter](https://www.flutter.dev) aliquip consectetur duis ut labore laborum commodo aliquip aliquip velit pariatur dolore. [Flutter](https://www.flutter.dev) Excepteur ad cupidatat do *[Flutter](https://www.flutter.dev)* elit laborum amet cillum reprehenderit **[Dart](https://www.dart.dev)** aliquip sit proident occaecat. Non sit labore anim elit veniam Lorem minim commodo eiusmod irure do minim nisi. In laboris eiusmod reprehenderit aliquip sit proident occaecat. Non sit labore anim elit veniam Lorem minim commodo eiusmod irure do minim nisi [Google's Home Page][Google]. ## Image --- Minim id consequat adipisicing cupidatat laborum culpa veniam non consectetur et duis pariatur reprehenderit eu ex consectetur. Sunt nisi qui eiusmod ut cillum laborum Lorem officia aliquip laboris ullamco nostrud laboris non irure laboris. ![Super wide](https://picsum.photos/id/15/1280/800) In laboris eiusmod reprehenderit aliquip sit proident occaecat. Non sit labore anim elit veniam Lorem minim commodo eiusmod irure do minim nisi. ![Flutter logo](/dart-lang/site-shared/master/src/_assets/image/flutter/icon/64.png) Officia irure in non voluptate adipisicing sit amet tempor duis dolore deserunt enim ut. Reprehenderit incididunt in ad anim et deserunt deserunt Lorem laborum quis. Enim aute anim labore proident laboris voluptate elit excepteur in. ![Not so big](https://picsum.photos/id/180/480/400) In laboris eiusmod reprehenderit aliquip sit proident occaecat. Non sit labore anim elit veniam Lorem minim commodo eiusmod irure do minim nisi. ![alt](resource:assets/logo.png) # Extended Syntax # Table --- Duis sunt ut pariatur reprehenderit mollit mollit magna dolore in pariatur nulla commodo sit dolor ad fugiat. | Table Heading 1 | Table Heading 2 | Table Heading 3 | | --------------- | --------------- | --------------- | | Item 1 | Item 2 | Item 3 | | Item 1 | Item 2 | Item 3 | | Item 1 | Item 2 | Item 3 | Ex amet id ex aliquip id do laborum excepteur exercitation elit sint commodo occaecat nostrud est. Nostrud pariatur esse veniam laborum non sint magna sit laboris minim in id. ## Fenced Code Block --- Et fugiat ad nisi amet magna labore do cillum fugiat occaecat cillum Lorem proident. In sint dolor ullamco ad do adipisicing amet. ``` import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:markdown/markdown.dart' as md; const String _markdownData = """ # Markdown Example Markdown allows you to easily include formatted text, images, and even formatted Dart code in your app. """; void main() { runApp( MaterialApp( title: "Markdown Demo", home: Scaffold( appBar: AppBar( title: const Text('Markdown Demo'), ), body: SafeArea( child: Markdown( data: _markdownData, ), ), ), ), ); } ``` ## Strikethrough --- ~~Voluptate cupidatat cillum elit quis ipsum eu voluptate fugiat consectetur enim. Quis ut voluptate culpa ex anim aute consectetur dolore proident voluptate exercitation eiusmod. Esse in do anim magna minim culpa sint.~~ Commodo ***~~fugiat aliqua minim quis pariatur mollit~~*** id tempor. Non occaecat **~~minim~~** anim aute ~~**consectetur esse**~~ enim aliqua *~~adipisicing~~* nostrud duis consequat eu ~~*adipisicing*~~ qui. Minim aliquip ~~***sit excepteur ipsum consequat***~~ laborum pariatur excepteur. ## Task List --- Officia irure in non voluptate adipisicing sit amet tempor duis dolore deserunt enim ut. Reprehenderit incididunt in ad anim et deserunt deserunt Lorem laborum quis. Enim aute anim labore proident laboris voluptate elit excepteur in. - [ ] laboris voluptate - [x] consectetur - [ ] eiusmod irure do Labore ea magna Lorem consequat aliquip consectetur cillum duis dolore. Et veniam dolor qui incididunt minim amet laboris sit.
packages/packages/flutter_markdown/example/assets/markdown_test_page.md/0
{ "file_path": "packages/packages/flutter_markdown/example/assets/markdown_test_page.md", "repo_id": "packages", "token_count": 3380 }
1,000
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// /// The simplest use case that illustrates how to make use of the /// flutter_markdown package is to include a Markdown widget in a widget tree /// and supply it with a character string of text containing Markdown formatting /// syntax. Here is a simple Flutter app that creates a Markdown widget that /// formats and displays the text in the string _markdownData. The resulting /// Flutter app demonstrates the use of headers, rules, and emphasis text from /// plain text Markdown syntax. /// /// import 'package:flutter/material.dart'; /// import 'package:flutter_markdown/flutter_markdown.dart'; /// /// const String _markdownData = """ /// # Minimal Markdown Test /// --- /// This is a simple Markdown test. Provide a text string with Markdown tags /// to the Markdown widget and it will display the formatted output in a /// scrollable widget. /// /// ## Section 1 /// Maecenas eget **arcu egestas**, mollis ex vitae, posuere magna. Nunc eget /// aliquam tortor. Vestibulum porta sodales efficitur. Mauris interdum turpis /// eget est condimentum, vitae porttitor diam ornare. /// /// ### Subsection A /// Sed et massa finibus, blandit massa vel, vulputate velit. Vestibulum vitae /// venenatis libero. **__Curabitur sem lectus, feugiat eu justo in, eleifend /// accumsan ante.__** Sed a fermentum elit. Curabitur sodales metus id mi /// ornare, in ullamcorper magna congue. /// """; /// /// void main() { /// runApp( /// MaterialApp( /// title: "Markdown Demo", /// home: Scaffold( /// appBar: AppBar( /// title: const Text('Simple Markdown Demo'), /// ), /// body: SafeArea( /// child: Markdown( /// data: _markdownData, /// ), /// ), /// ), /// ), /// ); /// } /// /// The flutter_markdown package has options for customizing and extending the /// parsing of Markdown syntax and building of the formatted output. The demos /// in this example app illustrate some of the potentials of the /// flutter_markdown package. library; import 'package:flutter/material.dart'; import 'screens/demo_screen.dart'; import 'screens/home_screen.dart'; import 'shared/markdown_demo_widget.dart'; void main() { runApp( MaterialApp( title: 'Markdown Demos', initialRoute: '/', home: HomeScreen(), onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (_) => DemoScreen( child: settings.arguments as MarkdownDemoWidget?, ), ); }, ), ); }
packages/packages/flutter_markdown/example/lib/main.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/main.dart", "repo_id": "packages", "token_count": 931 }
1,001
#include "ephemeral/Flutter-Generated.xcconfig"
packages/packages/flutter_markdown/example/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "packages/packages/flutter_markdown/example/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
1,002
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Header', () { testWidgets( 'level one', (WidgetTester tester) async { const String data = '# Header'; await tester.pumpWidget(boilerplate(const MarkdownBody(data: data))); final Iterable<Widget> widgets = selfAndDescendantWidgetsOf( find.byType(MarkdownBody), tester, ); expectWidgetTypes(widgets, <Type>[ MarkdownBody, Column, Wrap, Text, RichText, ]); expectTextStrings(widgets, <String>['Header']); }, ); }); }
packages/packages/flutter_markdown/test/header_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/header_test.dart", "repo_id": "packages", "token_count": 405 }
1,003
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Text Scaler', () { testWidgets( 'should use style textScaler in RichText', (WidgetTester tester) async { const TextScaler scaler = TextScaler.linear(2.0); const String data = 'Hello'; await tester.pumpWidget( boilerplate( MarkdownBody( styleSheet: MarkdownStyleSheet(textScaler: scaler), data: data, ), ), ); final RichText richText = tester.widget(find.byType(RichText)); expect(richText.textScaler, scaler); }, ); testWidgets( 'should use MediaQuery textScaler in RichText', (WidgetTester tester) async { const TextScaler scaler = TextScaler.linear(2.0); const String data = 'Hello'; await tester.pumpWidget( boilerplate( const MediaQuery( data: MediaQueryData(textScaler: scaler), child: MarkdownBody( data: data, ), ), ), ); final RichText richText = tester.widget(find.byType(RichText)); expect(richText.textScaler, scaler); }, ); testWidgets( 'should use MediaQuery textScaler in SelectableText.rich', (WidgetTester tester) async { const TextScaler scaler = TextScaler.linear(2.0); const String data = 'Hello'; await tester.pumpWidget( boilerplate( const MediaQuery( data: MediaQueryData(textScaler: scaler), child: MarkdownBody( data: data, selectable: true, ), ), ), ); final SelectableText selectableText = tester.widget(find.byType(SelectableText)); expect(selectableText.textScaler, scaler); }, ); }); }
packages/packages/flutter_markdown/test/text_scaler_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/text_scaler_test.dart", "repo_id": "packages", "token_count": 1043 }
1,004
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:file/file.dart'; import 'package:file/local.dart' as local_fs; import 'package:meta/meta.dart'; import 'common.dart'; import 'io.dart'; import 'logger.dart'; import 'signals.dart'; // package:file/local.dart must not be exported. This exposes LocalFileSystem, // which we override to ensure that temporary directories are cleaned up when // the tool is killed by a signal. export 'package:file/file.dart'; /// Exception indicating that a file that was expected to exist was not found. class FileNotFoundException implements IOException { const FileNotFoundException(this.path); final String path; @override String toString() => 'File not found: $path'; } /// Return a relative path if [fullPath] is contained by the cwd, else return an /// absolute path. String getDisplayPath(String fullPath, FileSystem fileSystem) { final String cwd = fileSystem.currentDirectory.path + fileSystem.path.separator; return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath; } /// This class extends [local_fs.LocalFileSystem] in order to clean up /// directories and files that the tool creates under the system temporary /// directory when the tool exits either normally or when killed by a signal. class LocalFileSystem extends local_fs.LocalFileSystem { LocalFileSystem(this._signals, this._fatalSignals, this.shutdownHooks); @visibleForTesting LocalFileSystem.test({ required Signals signals, List<ProcessSignal> fatalSignals = Signals.defaultExitSignals, }) : this(signals, fatalSignals, ShutdownHooks()); Directory? _systemTemp; final Map<ProcessSignal, Object> _signalTokens = <ProcessSignal, Object>{}; final ShutdownHooks shutdownHooks; Future<void> dispose() async { _tryToDeleteTemp(); for (final MapEntry<ProcessSignal, Object> signalToken in _signalTokens.entries) { await _signals.removeHandler(signalToken.key, signalToken.value); } _signalTokens.clear(); } final Signals _signals; final List<ProcessSignal> _fatalSignals; void _tryToDeleteTemp() { try { if (_systemTemp?.existsSync() ?? false) { _systemTemp?.deleteSync(recursive: true); } } on FileSystemException { // ignore } _systemTemp = null; } // This getter returns a fresh entry under /tmp, like // /tmp/flutter_tools.abcxyz, then the rest of the tool creates /tmp entries // under that, like /tmp/flutter_tools.abcxyz/flutter_build_stuff.123456. // Right before exiting because of a signal or otherwise, we delete // /tmp/flutter_tools.abcxyz, not the whole of /tmp. @override Directory get systemTempDirectory { if (_systemTemp == null) { if (!superSystemTempDirectory.existsSync()) { throwToolExit( 'Your system temp directory (${superSystemTempDirectory.path}) does not exist. ' 'Did you set an invalid override in your environment? See issue https://github.com/flutter/flutter/issues/74042 for more context.'); } _systemTemp = superSystemTempDirectory.createTempSync('flutter_tools.') ..createSync(recursive: true); // Make sure that the temporary directory is cleaned up if the tool is // killed by a signal. for (final ProcessSignal signal in _fatalSignals) { final Object token = _signals.addHandler( signal, (ProcessSignal _) { _tryToDeleteTemp(); }, ); _signalTokens[signal] = token; } // Make sure that the temporary directory is cleaned up when the tool // exits normally. shutdownHooks.addShutdownHook( _tryToDeleteTemp, ); } return _systemTemp!; } // This only exist because the memory file system does not support a systemTemp that does not exists #74042 @visibleForTesting Directory get superSystemTempDirectory => super.systemTempDirectory; } /// A function that will be run before the VM exits. typedef ShutdownHook = FutureOr<void> Function(); abstract class ShutdownHooks { factory ShutdownHooks() => _DefaultShutdownHooks(); /// Registers a [ShutdownHook] to be executed before the VM exits. void addShutdownHook(ShutdownHook shutdownHook); @visibleForTesting List<ShutdownHook> get registeredHooks; /// Runs all registered shutdown hooks and returns a future that completes when /// all such hooks have finished. /// /// Shutdown hooks will be run in groups by their [ShutdownStage]. All shutdown /// hooks within a given stage will be started in parallel and will be /// guaranteed to run to completion before shutdown hooks in the next stage are /// started. /// /// This class is constructed before the [Logger], so it cannot be direct /// injected in the constructor. Future<void> runShutdownHooks(Logger logger); } class _DefaultShutdownHooks implements ShutdownHooks { _DefaultShutdownHooks(); @override final List<ShutdownHook> registeredHooks = <ShutdownHook>[]; bool _shutdownHooksRunning = false; @override void addShutdownHook(ShutdownHook shutdownHook) { assert(!_shutdownHooksRunning); registeredHooks.add(shutdownHook); } @override Future<void> runShutdownHooks(Logger logger) async { logger.printTrace( 'Running ${registeredHooks.length} shutdown hook${registeredHooks.length == 1 ? '' : 's'}', ); _shutdownHooksRunning = true; try { final List<Future<dynamic>> futures = <Future<dynamic>>[]; for (final ShutdownHook shutdownHook in registeredHooks) { final FutureOr<dynamic> result = shutdownHook(); if (result is Future<dynamic>) { futures.add(result); } } await Future.wait<dynamic>(futures); } finally { _shutdownHooksRunning = false; } logger.printTrace('Shutdown hooks complete'); } }
packages/packages/flutter_migrate/lib/src/base/file_system.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/base/file_system.dart", "repo_id": "packages", "token_count": 1983 }
1,005
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'base/logger.dart'; import 'base/terminal.dart'; const int kDefaultStatusIndent = 2; class MigrateLogger { MigrateLogger({ required this.logger, this.verbose = false, this.silent = false, }) : status = logger.startSpinner(); final Logger logger; // We keep a spinner going and print periodic progress messages // to assure the developer that the command is still working due to // the long expected runtime. Status status; final bool verbose; final bool silent; void start() { status = logger.startSpinner(); } void stop() { status.stop(); } static final Map<String, String> _stepStringsMap = <String, String>{ 'start': 'Computing migration - this command may take a while to complete.', 'revisions': 'Obtaining revisions.', 'unmanaged': 'Parsing unmanagedFiles.', 'generating_base': 'Generating base reference app.', 'diff': 'Diffing base and target reference app.', 'new_files': 'Finding newly added files', 'merging': 'Merging changes with existing project.', 'cleaning': 'Cleaning up temp directories.', 'modified_count': 'Could not determine base revision, falling back on `v1.0.0`, revision 5391447fae6209bb21a89e6a5a6583cac1af9b4b', }; void printStatus(String message, {int indent = kDefaultStatusIndent}) { if (silent) { return; } status.pause(); logger.printStatus(message, indent: indent, color: TerminalColor.grey); status.resume(); } void printError(String message, {int indent = 0}) { status.pause(); logger.printError(message, indent: indent); status.resume(); } void logStep(String key) { if (!_stepStringsMap.containsKey(key)) { return; } printStatus(_stepStringsMap[key]!); } void printIfVerbose(String message, {int indent = kDefaultStatusIndent}) { if (verbose) { printStatus(message, indent: indent); } } }
packages/packages/flutter_migrate/lib/src/migrate_logger.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/migrate_logger.dart", "repo_id": "packages", "token_count": 715 }
1,006
// Copyright 2013 The Flutter 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/memory.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/flutter_project_metadata.dart'; import 'src/common.dart'; void main() { late FileSystem fileSystem; late BufferLogger logger; late File metadataFile; setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); metadataFile = fileSystem.file('.metadata'); }); testWithoutContext( 'project metadata fields are empty when file does not exist', () { final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect(logger.traceText, contains('No .metadata file found at .metadata')); }); testWithoutContext('project metadata fields are empty when file is empty', () { metadataFile.createSync(); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect(logger.traceText, contains('.metadata file at .metadata was empty or malformed.')); }); testWithoutContext( 'project metadata fields are empty when file is not valid yaml', () { metadataFile.writeAsStringSync(' channel: @something'); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect(logger.traceText, contains('.metadata file at .metadata was empty or malformed.')); }); testWithoutContext('projectType is populated when version is null', () { metadataFile ..createSync() ..writeAsStringSync(''' version: project_type: plugin '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect( logger.traceText, contains( 'The value of key `version` in .metadata was expected to be YamlMap but was Null')); }); testWithoutContext('projectType is populated when version is malformed', () { metadataFile ..createSync() ..writeAsStringSync(''' version: STRING INSTEAD OF MAP project_type: plugin '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull); expect( logger.traceText, contains( 'The value of key `version` in .metadata was expected to be YamlMap but was String')); }); testWithoutContext('version is populated when projectType is malformed', () { metadataFile ..createSync() ..writeAsStringSync(''' version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stable project_type: {} '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, 'stable'); expect(projectMetadata.versionRevision, 'b59b226a49391949247e3d6122e34bb001049ae4'); expect( logger.traceText, contains( 'The value of key `project_type` in .metadata was expected to be String but was YamlMap')); }); testWithoutContext('migrate config is populated when version is malformed', () { metadataFile ..createSync() ..writeAsStringSync(''' version: STRING INSTEAD OF MAP project_type: {} migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision unmanaged_files: - 'file1' '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.createRevision, 'abcdefg'); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.baseRevision, 'baserevision'); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1'); expect( logger.traceText, contains( 'The value of key `version` in .metadata was expected to be YamlMap but was String')); expect( logger.traceText, contains( 'The value of key `project_type` in .metadata was expected to be String but was YamlMap')); }); testWithoutContext( 'migrate config is populated when unmanaged_files is malformed', () { metadataFile ..createSync() ..writeAsStringSync(''' version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stable project_type: app migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision unmanaged_files: {} '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.app); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.createRevision, 'abcdefg'); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.baseRevision, 'baserevision'); // Tool uses default unamanged files list when malformed. expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'lib/main.dart'); expect( logger.traceText, contains( 'The value of key `unmanaged_files` in .metadata was expected to be YamlList but was YamlMap')); }); testWithoutContext('platforms is populated with a malformed entry', () { metadataFile ..createSync() ..writeAsStringSync(''' version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stable project_type: app migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision - platform: android base_revision: baserevision - platform: ios create_revision: abcdefg base_revision: baserevision unmanaged_files: - 'file1' '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.app); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.createRevision, 'abcdefg'); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.root]?.baseRevision, 'baserevision'); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.ios]?.createRevision, 'abcdefg'); expect( projectMetadata.migrateConfig .platformConfigs[FlutterProjectComponent.ios]?.baseRevision, 'baserevision'); expect( projectMetadata.migrateConfig.platformConfigs .containsKey(FlutterProjectComponent.android), false); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1'); expect( logger.traceText, contains('The key `create_revision` was not found')); }); }
packages/packages/flutter_migrate/test/flutter_project_metadata_test.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/flutter_project_metadata_test.dart", "repo_id": "packages", "token_count": 2971 }
1,007
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/flutter_plugin_android_lifecycle/example/android/gradle.properties/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,008
Flutter apps can use the hash fragment or URL path for navigation. To learn more about how to configure your app, visit the [URL strategy on the web](https://docs.flutter.dev/development/ui/navigation/url-strategies) page on flutter.dev.
packages/packages/go_router/doc/web.md/0
{ "file_path": "packages/packages/go_router/doc/web.md", "repo_id": "packages", "token_count": 65 }
1,009
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'src/auth.dart'; import 'src/data/author.dart'; import 'src/data/book.dart'; import 'src/data/library.dart'; import 'src/screens/author_details.dart'; import 'src/screens/authors.dart'; import 'src/screens/book_details.dart'; import 'src/screens/books.dart'; import 'src/screens/scaffold.dart'; import 'src/screens/settings.dart'; import 'src/screens/sign_in.dart'; void main() => runApp(Bookstore()); /// The book store view. class Bookstore extends StatelessWidget { /// Creates a [Bookstore]. Bookstore({super.key}); final ValueKey<String> _scaffoldKey = const ValueKey<String>('App scaffold'); @override Widget build(BuildContext context) => BookstoreAuthScope( notifier: _auth, child: MaterialApp.router( routerConfig: _router, ), ); final BookstoreAuth _auth = BookstoreAuth(); late final GoRouter _router = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', redirect: (_, __) => '/books', ), GoRoute( path: '/signin', pageBuilder: (BuildContext context, GoRouterState state) => FadeTransitionPage( key: state.pageKey, child: SignInScreen( onSignIn: (Credentials credentials) { BookstoreAuthScope.of(context) .signIn(credentials.username, credentials.password); }, ), ), ), GoRoute( path: '/books', redirect: (_, __) => '/books/popular', ), GoRoute( path: '/book/:bookId', redirect: (BuildContext context, GoRouterState state) => '/books/all/${state.pathParameters['bookId']}', ), GoRoute( path: '/books/:kind(new|all|popular)', pageBuilder: (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: BookstoreScaffold( selectedTab: ScaffoldTab.books, child: BooksScreen(state.pathParameters['kind']!), ), ), routes: <GoRoute>[ GoRoute( path: ':bookId', builder: (BuildContext context, GoRouterState state) { final String bookId = state.pathParameters['bookId']!; final Book? selectedBook = libraryInstance.allBooks .firstWhereOrNull((Book b) => b.id.toString() == bookId); return BookDetailsScreen(book: selectedBook); }, ), ], ), GoRoute( path: '/author/:authorId', redirect: (BuildContext context, GoRouterState state) => '/authors/${state.pathParameters['authorId']}', ), GoRoute( path: '/authors', pageBuilder: (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.authors, child: AuthorsScreen(), ), ), routes: <GoRoute>[ GoRoute( path: ':authorId', builder: (BuildContext context, GoRouterState state) { final int authorId = int.parse(state.pathParameters['authorId']!); final Author? selectedAuthor = libraryInstance.allAuthors .firstWhereOrNull((Author a) => a.id == authorId); return AuthorDetailsScreen(author: selectedAuthor); }, ), ], ), GoRoute( path: '/settings', pageBuilder: (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.settings, child: SettingsScreen(), ), ), ), ], redirect: _guard, refreshListenable: _auth, debugLogDiagnostics: true, ); String? _guard(BuildContext context, GoRouterState state) { final bool signedIn = _auth.signedIn; final bool signingIn = state.matchedLocation == '/signin'; // Go to /signin if the user is not signed in if (!signedIn && !signingIn) { return '/signin'; } // Go to /books if the user is signed in and tries to go to /signin. else if (signedIn && signingIn) { return '/books'; } // no redirect return null; } } /// A page that fades in an out. class FadeTransitionPage extends CustomTransitionPage<void> { /// Creates a [FadeTransitionPage]. FadeTransitionPage({ required LocalKey super.key, required super.child, }) : super( transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => FadeTransition( opacity: animation.drive(_curveTween), child: child, )); static final CurveTween _curveTween = CurveTween(curve: Curves.easeIn); }
packages/packages/go_router/example/lib/books/main.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/main.dart", "repo_id": "packages", "token_count": 2361 }
1,010
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; /// This sample app demonstrates how to provide a codec for complex extra data. void main() => runApp(const MyApp()); /// The router configuration. final GoRouter _router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ], extraCodec: const MyExtraCodec(), ); /// 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>[ const Text( "If running in web, use the browser's backward and forward button to test extra codec after setting extra several times."), Text( 'The extra for this page is: ${GoRouterState.of(context).extra}'), ElevatedButton( onPressed: () => context.go('/', extra: ComplexData1('data')), child: const Text('Set extra to ComplexData1'), ), ElevatedButton( onPressed: () => context.go('/', extra: ComplexData2('data')), child: const Text('Set extra to ComplexData2'), ), ], ), ), ); } } /// A complex class. class ComplexData1 { /// Create a complex object. ComplexData1(this.data); /// The data. final String data; @override String toString() => 'ComplexData1(data: $data)'; } /// A complex class. class ComplexData2 { /// Create a complex object. ComplexData2(this.data); /// The data. final String data; @override String toString() => 'ComplexData2(data: $data)'; } /// A codec that can serialize both [ComplexData1] and [ComplexData2]. class MyExtraCodec extends Codec<Object?, Object?> { /// Create a codec. const MyExtraCodec(); @override Converter<Object?, Object?> get decoder => const _MyExtraDecoder(); @override Converter<Object?, Object?> get encoder => const _MyExtraEncoder(); } class _MyExtraDecoder extends Converter<Object?, Object?> { const _MyExtraDecoder(); @override Object? convert(Object? input) { if (input == null) { return null; } final List<Object?> inputAsList = input as List<Object?>; if (inputAsList[0] == 'ComplexData1') { return ComplexData1(inputAsList[1]! as String); } if (inputAsList[0] == 'ComplexData2') { return ComplexData2(inputAsList[1]! as String); } throw FormatException('Unable to parse input: $input'); } } class _MyExtraEncoder extends Converter<Object?, Object?> { const _MyExtraEncoder(); @override Object? convert(Object? input) { if (input == null) { return null; } switch (input) { case ComplexData1 _: return <Object?>['ComplexData1', input.data]; case ComplexData2 _: return <Object?>['ComplexData2', input.data]; default: throw FormatException('Cannot encode type ${input.runtimeType}'); } } }
packages/packages/go_router/example/lib/extra_codec.dart/0
{ "file_path": "packages/packages/go_router/example/lib/extra_codec.dart", "repo_id": "packages", "token_count": 1403 }
1,011
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; // This scenario demonstrates how to use redirect to handle a sign-in flow. // // The GoRouter.redirect method is called before the app is navigate to a // new page. You can choose to redirect to a different page by returning a // non-null URL string. /// The login information. class LoginInfo extends ChangeNotifier { /// The username of login. String get userName => _userName; String _userName = ''; /// Whether a user has logged in. bool get loggedIn => _userName.isNotEmpty; /// Logs in a user. void login(String userName) { _userName = userName; notifyListeners(); } /// Logs out the current user. void logout() { _userName = ''; notifyListeners(); } } void main() => runApp(App()); /// The main app. class App extends StatelessWidget { /// Creates an [App]. App({super.key}); final LoginInfo _loginInfo = LoginInfo(); /// The title of the app. static const String title = 'GoRouter Example: Redirection'; // add the login info into the tree as app state that can change over time @override Widget build(BuildContext context) => ChangeNotifierProvider<LoginInfo>.value( value: _loginInfo, child: MaterialApp.router( routerConfig: _router, title: title, debugShowCheckedModeBanner: false, ), ); late final GoRouter _router = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], // redirect to the login page if the user is not logged in redirect: (BuildContext context, GoRouterState state) { // if the user is not logged in, they need to login final bool loggedIn = _loginInfo.loggedIn; final bool loggingIn = state.matchedLocation == '/login'; if (!loggedIn) { return '/login'; } // if the user is logged in but still on the login page, send them to // the home page if (loggingIn) { return '/'; } // no need to redirect at all return null; }, // changes on the listenable will cause the router to refresh it's route refreshListenable: _loginInfo, ); } /// The login screen. class LoginScreen extends StatelessWidget { /// Creates a [LoginScreen]. const LoginScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: ElevatedButton( onPressed: () { // log a user in, letting all the listeners know context.read<LoginInfo>().login('test-user'); // router will automatically redirect from /login to / using // refreshListenable }, child: const Text('Login'), ), ), ); } /// The home screen. class HomeScreen extends StatelessWidget { /// Creates a [HomeScreen]. const HomeScreen({super.key}); @override Widget build(BuildContext context) { final LoginInfo info = context.read<LoginInfo>(); return Scaffold( appBar: AppBar( title: const Text(App.title), actions: <Widget>[ IconButton( onPressed: info.logout, tooltip: 'Logout: ${info.userName}', icon: const Icon(Icons.logout), ) ], ), body: const Center( child: Text('HomeScreen'), ), ); } }
packages/packages/go_router/example/lib/redirection.dart/0
{ "file_path": "packages/packages/go_router/example/lib/redirection.dart", "repo_id": "packages", "token_count": 1490 }
1,012
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'configuration.dart'; import 'information_provider.dart'; import 'logging.dart'; import 'match.dart'; import 'router.dart'; /// The function signature of [GoRouteInformationParser.onParserException]. /// /// The `routeMatchList` parameter contains the exception explains the issue /// occurred. /// /// The returned [RouteMatchList] is used as parsed result for the /// [GoRouterDelegate]. typedef ParserExceptionHandler = RouteMatchList Function( BuildContext context, RouteMatchList routeMatchList, ); /// Converts between incoming URLs and a [RouteMatchList] using [RouteMatcher]. /// Also performs redirection using [RouteRedirector]. class GoRouteInformationParser extends RouteInformationParser<RouteMatchList> { /// Creates a [GoRouteInformationParser]. GoRouteInformationParser({ required this.configuration, required this.onParserException, }) : _routeMatchListCodec = RouteMatchListCodec(configuration); /// The route configuration used for parsing [RouteInformation]s. final RouteConfiguration configuration; /// The exception handler that is called when parser can't handle the incoming /// uri. /// /// This method must return a [RouteMatchList] for the parsed result. final ParserExceptionHandler? onParserException; final RouteMatchListCodec _routeMatchListCodec; final Random _random = Random(); /// The future of current route parsing. /// /// This is used for testing asynchronous redirection. @visibleForTesting Future<RouteMatchList>? debugParserFuture; /// Called by the [Router]. The @override Future<RouteMatchList> parseRouteInformationWithDependencies( RouteInformation routeInformation, BuildContext context, ) { assert(routeInformation.state != null); final Object state = routeInformation.state!; if (state is! RouteInformationState) { // This is a result of browser backward/forward button or state // restoration. In this case, the route match list is already stored in // the state. final RouteMatchList matchList = _routeMatchListCodec.decode(state as Map<Object?, Object?>); return debugParserFuture = _redirect(context, matchList) .then<RouteMatchList>((RouteMatchList value) { if (value.isError && onParserException != null) { return onParserException!(context, value); } return value; }); } late final RouteMatchList initialMatches; initialMatches = configuration.findMatch( routeInformation.uri.path.isEmpty ? '${routeInformation.uri}/' : routeInformation.uri.toString(), extra: state.extra); if (initialMatches.isError) { log('No initial matches: ${routeInformation.uri.path}'); } return debugParserFuture = _redirect( context, initialMatches, ).then<RouteMatchList>((RouteMatchList matchList) { if (matchList.isError && onParserException != null) { return onParserException!(context, matchList); } assert(() { if (matchList.isNotEmpty) { assert(!matchList.last.route.redirectOnly, 'A redirect-only route must redirect to location different from itself.\n The offending route: ${matchList.last.route}'); } return true; }()); return _updateRouteMatchList( matchList, baseRouteMatchList: state.baseRouteMatchList, completer: state.completer, type: state.type, ); }); } @override Future<RouteMatchList> parseRouteInformation( RouteInformation routeInformation) { throw UnimplementedError( 'use parseRouteInformationWithDependencies instead'); } /// for use by the Router architecture as part of the RouteInformationParser @override RouteInformation? restoreRouteInformation(RouteMatchList configuration) { if (configuration.isEmpty) { return null; } final String location; if (GoRouter.optionURLReflectsImperativeAPIs && configuration.matches.last is ImperativeRouteMatch) { location = (configuration.matches.last as ImperativeRouteMatch) .matches .uri .toString(); } else { location = configuration.uri.toString(); } return RouteInformation( uri: Uri.parse(location), state: _routeMatchListCodec.encode(configuration), ); } Future<RouteMatchList> _redirect( BuildContext context, RouteMatchList routeMatch) { final FutureOr<RouteMatchList> redirectedFuture = configuration .redirect(context, routeMatch, redirectHistory: <RouteMatchList>[]); if (redirectedFuture is RouteMatchList) { return SynchronousFuture<RouteMatchList>(redirectedFuture); } return redirectedFuture; } RouteMatchList _updateRouteMatchList( RouteMatchList newMatchList, { required RouteMatchList? baseRouteMatchList, required Completer<Object?>? completer, required NavigatingType type, }) { switch (type) { case NavigatingType.push: return baseRouteMatchList!.push( ImperativeRouteMatch( pageKey: _getUniqueValueKey(), completer: completer!, matches: newMatchList, ), ); case NavigatingType.pushReplacement: final RouteMatch routeMatch = baseRouteMatchList!.last; return baseRouteMatchList.remove(routeMatch).push( ImperativeRouteMatch( pageKey: _getUniqueValueKey(), completer: completer!, matches: newMatchList, ), ); case NavigatingType.replace: final RouteMatch routeMatch = baseRouteMatchList!.last; return baseRouteMatchList.remove(routeMatch).push( ImperativeRouteMatch( pageKey: routeMatch.pageKey, completer: completer!, matches: newMatchList, ), ); case NavigatingType.go: return newMatchList; case NavigatingType.restore: // Still need to consider redirection. return baseRouteMatchList!.uri.toString() != newMatchList.uri.toString() ? newMatchList : baseRouteMatchList; } } ValueKey<String> _getUniqueValueKey() { return ValueKey<String>(String.fromCharCodes( List<int>.generate(32, (_) => _random.nextInt(33) + 89))); } }
packages/packages/go_router/lib/src/parser.dart/0
{ "file_path": "packages/packages/go_router/lib/src/parser.dart", "repo_id": "packages", "token_count": 2416 }
1,013
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { testWidgets('router rebuild with extra codec works', (WidgetTester tester) async { const String initialString = 'some string'; const String empty = 'empty'; final GoRouter router = GoRouter( initialLocation: '/', extraCodec: ComplexDataCodec(), initialExtra: ComplexData(initialString), routes: <RouteBase>[ GoRoute( path: '/', builder: (_, GoRouterState state) { return Text((state.extra as ComplexData?)?.data ?? empty); }), ], redirect: (BuildContext context, _) { // Set up dependency. SimpleDependencyProvider.of(context); return null; }, ); addTearDown(router.dispose); final SimpleDependency dependency = SimpleDependency(); addTearDown(() => dependency.dispose()); await tester.pumpWidget( SimpleDependencyProvider( dependency: dependency, child: MaterialApp.router( routerConfig: router, ), ), ); expect(find.text(initialString), findsOneWidget); dependency.boolProperty = !dependency.boolProperty; await tester.pumpAndSettle(); expect(find.text(initialString), findsOneWidget); }); testWidgets('Restores state correctly', (WidgetTester tester) async { const String initialString = 'some string'; const String empty = 'empty'; final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/', builder: (_, GoRouterState state) { return Text((state.extra as ComplexData?)?.data ?? empty); }, ), ]; await createRouter( routes, tester, initialExtra: ComplexData(initialString), restorationScopeId: 'test', extraCodec: ComplexDataCodec(), ); expect(find.text(initialString), findsOneWidget); await tester.restartAndRestore(); await tester.pumpAndSettle(); expect(find.text(initialString), findsOneWidget); }); } class ComplexData { ComplexData(this.data); final String data; } class ComplexDataCodec extends Codec<ComplexData?, Object?> { @override Converter<Object?, ComplexData?> get decoder => ComplexDataDecoder(); @override Converter<ComplexData?, Object?> get encoder => ComplexDataEncoder(); } class ComplexDataDecoder extends Converter<Object?, ComplexData?> { @override ComplexData? convert(Object? input) { if (input == null) { return null; } return ComplexData(input as String); } } class ComplexDataEncoder extends Converter<ComplexData?, Object?> { @override Object? convert(ComplexData? input) { if (input == null) { return null; } return input.data; } }
packages/packages/go_router/test/extra_codec_test.dart/0
{ "file_path": "packages/packages/go_router/test/extra_codec_test.dart", "repo_id": "packages", "token_count": 1149 }
1,014
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { testWidgets('GoRouter.push does not trigger unnecessary rebuilds', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, __) => const HomePage()), GoRoute( path: '/1', builder: (BuildContext context, __) { return ElevatedButton( onPressed: () { context.push('/1'); }, child: const Text('/1'), ); }), ]; await createRouter(routes, tester); expect(find.text('/'), findsOneWidget); // first build expect(HomePage.built, isTrue); HomePage.built = false; // Should not be built again afterward. await tester.tap(find.text('/')); await tester.pumpAndSettle(); expect(find.text('/1'), findsOneWidget); expect(HomePage.built, isFalse); await tester.tap(find.text('/1')); await tester.pumpAndSettle(); expect(find.text('/1'), findsOneWidget); expect(HomePage.built, isFalse); await tester.tap(find.text('/1')); await tester.pumpAndSettle(); expect(find.text('/1'), findsOneWidget); expect(HomePage.built, isFalse); }); } class HomePage extends StatelessWidget { const HomePage({super.key}); static bool built = false; @override Widget build(BuildContext context) { built = true; return ElevatedButton( onPressed: () { context.push('/1'); }, child: const Text('/'), ); } }
packages/packages/go_router/test/rebuild_test.dart/0
{ "file_path": "packages/packages/go_router/test/rebuild_test.dart", "repo_id": "packages", "token_count": 755 }
1,015
test_on: vm
packages/packages/go_router_builder/dart_test.yaml/0
{ "file_path": "packages/packages/go_router_builder/dart_test.yaml", "repo_id": "packages", "token_count": 6 }
1,016
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_builder_example/main.dart'; void main() { testWidgets('Validate extra logic walkthrough', (WidgetTester tester) async { await tester.pumpWidget(App()); await tester.tap(find.text('Login')); await tester.pumpAndSettle(); await _openPopupMenu(tester); await tester.tap(find.text('Push w/o return value')); await tester.pumpAndSettle(); expect(find.text('Chris'), findsOneWidget); await tester.pageBack(); await tester.pumpAndSettle(); await _openPopupMenu(tester); await tester.tap(find.text('Push w/ return value')); await tester.pumpAndSettle(); expect(find.text('Family Count'), findsOneWidget); await tester.pageBack(); await tester.pumpAndSettle(); await tester.tap(find.text('Sells')); await tester.pumpAndSettle(); await tester.tap(find.text('Chris')); await tester.pumpAndSettle(); await tester.tap(find.text('hobbies - coding')); await tester.pumpAndSettle(); expect(find.text('No extra click!'), findsOneWidget); await tester.tap(find.byTooltip('Close')); await tester.pumpAndSettle(); await tester.tap(find.text('With extra...').first); await tester.pumpAndSettle(); expect(find.text('Extra click count: 1'), findsOneWidget); }); } Future<void> _openPopupMenu(WidgetTester tester) async { final Finder moreButton = find.byIcon(Icons.more_vert); expect(moreButton, findsOneWidget); await tester.tap(moreButton); await tester.pumpAndSettle(); }
packages/packages/go_router_builder/example/test/widget_test.dart/0
{ "file_path": "packages/packages/go_router_builder/example/test/widget_test.dart", "repo_id": "packages", "token_count": 631 }
1,017
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:analyzer/dart/element/element.dart'; import 'package:build/build.dart'; import 'package:build_test/build_test.dart'; import 'package:dart_style/dart_style.dart' as dart_style; import 'package:go_router_builder/src/go_router_generator.dart'; import 'package:path/path.dart' as p; import 'package:source_gen/source_gen.dart'; import 'package:test/test.dart'; const GoRouterGenerator generator = GoRouterGenerator(); Future<void> main() async { final dart_style.DartFormatter formatter = dart_style.DartFormatter(); final Directory dir = Directory('test_inputs'); final List<File> testFiles = dir .listSync() .whereType<File>() .where((File f) => f.path.endsWith('.dart')) .toList(); for (final File file in testFiles) { final String fileName = file.path.split('/').last; final File expectFile = File(p.join('${file.path}.expect')); if (!expectFile.existsSync()) { throw Exception('A text input must have a .expect file. ' 'Found test input $fileName with out an expect file.'); } final String expectResult = expectFile.readAsStringSync().trim(); test('verify $fileName', () async { final String targetLibraryAssetId = '__test__|${file.path}'; final LibraryElement element = await resolveSources<LibraryElement>( <String, String>{ targetLibraryAssetId: file.readAsStringSync(), }, (Resolver resolver) async { final AssetId assetId = AssetId.parse(targetLibraryAssetId); return resolver.libraryFor(assetId); }, ); final LibraryReader reader = LibraryReader(element); final Set<String> results = <String>{}; try { generator.generateForAnnotation(reader, results, <String>{}); } on InvalidGenerationSourceError catch (e) { expect(expectResult, e.message.trim()); return; } final String generated = formatter .format(results.join('\n\n')) .trim() .replaceAll('\r\n', '\n'); expect(generated, equals(expectResult.replaceAll('\r\n', '\n'))); }, timeout: const Timeout(Duration(seconds: 100))); } }
packages/packages/go_router_builder/tool/run_tests.dart/0
{ "file_path": "packages/packages/go_router_builder/tool/run_tests.dart", "repo_id": "packages", "token_count": 888 }
1,018
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Methods here are documented in the Google Identity authentication website, // but they don't really belong to either the authentication nor authorization // libraries. @JS() library id_load_callback; import 'dart:js_interop'; import 'shared.dart'; /* // Library load callback: onGoogleLibraryLoad // https://developers.google.com/identity/gsi/web/reference/js-reference#onGoogleLibraryLoad */ @JS('onGoogleLibraryLoad') @staticInterop external set _onGoogleLibraryLoad(JSFunction callback); /// Method called after the Sign In With Google JavaScript library is loaded. /// /// The [callback] parameter must be manually wrapped in [allowInterop] /// before being set to the [onGoogleLibraryLoad] property. set onGoogleLibraryLoad(VoidFn function) { _onGoogleLibraryLoad = function.toJS; }
packages/packages/google_identity_services_web/lib/src/js_interop/load_callback.dart/0
{ "file_path": "packages/packages/google_identity_services_web/lib/src/js_interop/load_callback.dart", "repo_id": "packages", "token_count": 257 }
1,019