code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example_api/api.dart';
import 'package:flutter_news_example_api/src/data/in_memory_news_data_source.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
class MyNewsDataSource extends NewsDataSource {
@override
Future<void> createSubscription({
required String userId,
required String subscriptionId,
}) {
throw UnimplementedError();
}
@override
Future<Article?> getArticle({
required String id,
int limit = 20,
int offset = 0,
bool preview = false,
}) {
throw UnimplementedError();
}
@override
Future<bool?> isPremiumArticle({required String id}) {
throw UnimplementedError();
}
@override
Future<Feed> getFeed({
Category category = Category.top,
int limit = 20,
int offset = 0,
}) {
throw UnimplementedError();
}
@override
Future<List<Category>> getCategories() => throw UnimplementedError();
@override
Future<RelatedArticles> getRelatedArticles({
required String id,
int limit = 20,
int offset = 0,
}) {
throw UnimplementedError();
}
@override
Future<List<NewsBlock>> getPopularArticles() {
throw UnimplementedError();
}
@override
Future<List<String>> getPopularTopics() {
throw UnimplementedError();
}
@override
Future<List<String>> getRelevantTopics({required String term}) {
throw UnimplementedError();
}
@override
Future<List<NewsBlock>> getRelevantArticles({required String term}) {
throw UnimplementedError();
}
@override
Future<List<Subscription>> getSubscriptions() {
throw UnimplementedError();
}
@override
Future<User?> getUser({required String userId}) {
throw UnimplementedError();
}
}
void main() {
Matcher articleHaving({required List<NewsBlock> blocks, int? totalBlocks}) {
return predicate<Article>(
(article) {
totalBlocks ??= article.totalBlocks;
if (blocks.length != article.blocks.length) return false;
if (totalBlocks != article.totalBlocks) return false;
for (var i = 0; i < blocks.length; i++) {
if (blocks[i] != article.blocks[i]) return false;
}
return true;
},
);
}
Matcher relatedArticlesHaving({
required List<NewsBlock> blocks,
int? totalBlocks,
}) {
return predicate<RelatedArticles>(
(relatedArticles) {
totalBlocks ??= relatedArticles.totalBlocks;
if (blocks.length != relatedArticles.blocks.length) return false;
if (totalBlocks != relatedArticles.totalBlocks) return false;
for (var i = 0; i < blocks.length; i++) {
if (blocks[i] != relatedArticles.blocks[i]) return false;
}
return true;
},
);
}
Matcher feedHaving({required List<NewsBlock> blocks, int? totalBlocks}) {
return predicate<Feed>(
(feed) {
totalBlocks ??= feed.totalBlocks;
if (blocks.length != feed.blocks.length) return false;
if (totalBlocks != feed.totalBlocks) return false;
for (var i = 0; i < blocks.length; i++) {
if (blocks[i] != feed.blocks[i]) return false;
}
return true;
},
);
}
Matcher isAnEmptyFeed() {
return predicate<Feed>(
(feed) => feed.blocks.isEmpty && feed.totalBlocks == 0,
);
}
group('NewsDataSource', () {
test('can be extended', () {
expect(MyNewsDataSource.new, returnsNormally);
});
});
group('InMemoryNewsDataSource', () {
late NewsDataSource newsDataSource;
setUp(() {
newsDataSource = InMemoryNewsDataSource();
});
group('createSubscription', () {
test('completes', () async {
expect(
newsDataSource.createSubscription(
userId: 'userId',
subscriptionId: 'subscriptionId',
),
completes,
);
});
});
group('getSubscriptions', () {
test('returns list of subscriptions', () async {
expect(
newsDataSource.getSubscriptions(),
completion(equals(subscriptions)),
);
});
});
group('getUser', () {
test(
'completes with empty user '
'when subscription does not exist', () async {
const userId = 'userId';
expect(
newsDataSource.getUser(userId: userId),
completion(User(id: userId, subscription: SubscriptionPlan.none)),
);
});
test('completes with user when user exists', () async {
const userId = 'userId';
final subscription = subscriptions.first;
await newsDataSource.createSubscription(
userId: userId,
subscriptionId: subscription.id,
);
expect(
newsDataSource.getUser(userId: userId),
completion(
equals(
User(id: userId, subscription: subscription.name),
),
),
);
});
});
group('getFeed', () {
test('returns stubbed feed (default category)', () {
expect(
newsDataSource.getFeed(limit: 100),
completion(feedHaving(blocks: topNewsFeedBlocks)),
);
});
test('returns stubbed feed (Category.technology)', () {
expect(
newsDataSource.getFeed(category: Category.technology),
completion(feedHaving(blocks: technologyFeedBlocks)),
);
});
test('returns stubbed feed (Category.sports)', () {
expect(
newsDataSource.getFeed(category: Category.sports),
completion(feedHaving(blocks: sportsFeedBlocks)),
);
});
test('returns empty feed for remaining categories', () async {
final emptyCategories = [
Category.business,
Category.entertainment,
];
for (final category in emptyCategories) {
await expectLater(
newsDataSource.getFeed(category: category),
completion(isAnEmptyFeed()),
);
}
});
test('returns correct feed when limit is specified', () {
expect(
newsDataSource.getFeed(limit: 0),
completion(
feedHaving(blocks: [], totalBlocks: topNewsFeedBlocks.length),
),
);
expect(
newsDataSource.getFeed(limit: 1),
completion(
feedHaving(
blocks: topNewsFeedBlocks.take(1).toList(),
totalBlocks: topNewsFeedBlocks.length,
),
),
);
expect(
newsDataSource.getFeed(limit: 100),
completion(
feedHaving(
blocks: topNewsFeedBlocks,
totalBlocks: topNewsFeedBlocks.length,
),
),
);
});
test('returns correct feed when offset is specified', () {
expect(
newsDataSource.getFeed(offset: 1, limit: 100),
completion(
feedHaving(
blocks: topNewsFeedBlocks.sublist(1),
totalBlocks: topNewsFeedBlocks.length,
),
),
);
expect(
newsDataSource.getFeed(offset: 2, limit: 100),
completion(
feedHaving(
blocks: topNewsFeedBlocks.sublist(2),
totalBlocks: topNewsFeedBlocks.length,
),
),
);
expect(
newsDataSource.getFeed(offset: 100, limit: 100),
completion(
feedHaving(
blocks: [],
totalBlocks: topNewsFeedBlocks.length,
),
),
);
});
});
group('getCategories', () {
test('returns stubbed categories', () {
expect(
newsDataSource.getCategories(),
completion([
Category.top,
Category.technology,
Category.sports,
Category.health,
Category.science,
]),
);
});
});
group('getArticle', () {
test('returns null when article id cannot be found', () {
expect(
newsDataSource.getArticle(id: '__invalid_article_id__'),
completion(isNull),
);
});
test(
'returns content when article exists '
'and preview is false', () {
final item = healthItems.first;
expect(
newsDataSource.getArticle(id: item.post.id),
completion(
articleHaving(
blocks: item.content,
totalBlocks: item.content.length,
),
),
);
});
test(
'returns content preview when article exists '
'and preview is true', () {
final item = healthItems.first;
expect(
newsDataSource.getArticle(id: item.post.id, preview: true),
completion(
articleHaving(
blocks: item.contentPreview,
totalBlocks: item.contentPreview.length,
),
),
);
});
test('supports limit if specified', () {
final item = healthItems.first;
expect(
newsDataSource.getArticle(id: item.post.id, limit: 1),
completion(
articleHaving(
blocks: item.content.take(1).toList(),
totalBlocks: item.content.length,
),
),
);
});
test('supports offset if specified', () {
final item = healthItems.first;
expect(
newsDataSource.getArticle(id: item.post.id, offset: 1),
completion(
articleHaving(
blocks: item.content.sublist(1).toList(),
totalBlocks: item.content.length,
),
),
);
});
});
group('isPremiumArticle', () {
test('returns null when article id cannot be found', () {
expect(
newsDataSource.isPremiumArticle(id: '__invalid_article_id__'),
completion(isNull),
);
});
test(
'returns true when article exists '
'and isPremium is true', () {
final item = technologySmallItems.last;
expect(
newsDataSource.isPremiumArticle(id: item.post.id),
completion(isTrue),
);
});
test(
'returns false when article exists '
'and isPremium is false', () {
final item = healthItems.last;
expect(
newsDataSource.isPremiumArticle(id: item.post.id),
completion(isFalse),
);
});
});
group('getPopularArticles', () {
test('returns correct list of articles', () async {
expect(
newsDataSource.getPopularArticles(),
completion(equals(popularArticles.map((item) => item.post).toList())),
);
});
});
group('getPopularTopics', () {
test('returns correct list of topics', () async {
expect(
newsDataSource.getPopularTopics(),
completion(equals(popularTopics)),
);
});
});
group('getRelevantArticles', () {
test('returns correct list of articles', () async {
expect(
newsDataSource.getRelevantArticles(term: 'term'),
completion(
equals(relevantArticles.map((item) => item.post).toList()),
),
);
});
});
group('getRelevantTopics', () {
test('returns correct list of topics', () async {
expect(
newsDataSource.getRelevantTopics(term: 'term'),
completion(equals(relevantTopics)),
);
});
});
group('getRelatedArticles', () {
test('returns empty when article id cannot be found', () {
expect(
newsDataSource.getRelatedArticles(id: '__invalid_article_id__'),
completion(equals(RelatedArticles.empty())),
);
});
test('returns null when related articles cannot be found', () {
expect(
newsDataSource.getRelatedArticles(id: scienceVideoItems.last.post.id),
completion(equals(RelatedArticles.empty())),
);
});
test('returns related articles when article exists', () {
final item = healthItems.first;
final relatedArticles = item.relatedArticles;
expect(
newsDataSource.getRelatedArticles(id: item.post.id),
completion(
relatedArticlesHaving(
blocks: relatedArticles,
totalBlocks: relatedArticles.length,
),
),
);
});
test('supports limit if specified', () {
final item = healthItems.first;
final relatedArticles = item.relatedArticles;
expect(
newsDataSource.getRelatedArticles(id: item.post.id, limit: 1),
completion(
relatedArticlesHaving(
blocks: relatedArticles.take(1).toList(),
totalBlocks: relatedArticles.length,
),
),
);
});
test('supports offset if specified', () {
final item = healthSmallItems.first;
final relatedArticles = item.relatedArticles;
expect(
newsDataSource.getRelatedArticles(id: item.post.id, offset: 1),
completion(
relatedArticlesHaving(
blocks: relatedArticles.sublist(1).toList(),
totalBlocks: relatedArticles.length,
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/api/test/src/data/news_data_source_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/api/test/src/data/news_data_source_test.dart', 'repo_id': 'news_toolkit', 'token_count': 6055} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:notifications_repository/notifications_repository.dart';
import 'package:user_repository/user_repository.dart';
part 'app_event.dart';
part 'app_state.dart';
class AppBloc extends Bloc<AppEvent, AppState> {
AppBloc({
required UserRepository userRepository,
required NotificationsRepository notificationsRepository,
required User user,
}) : _userRepository = userRepository,
_notificationsRepository = notificationsRepository,
super(
user == User.anonymous
? const AppState.unauthenticated()
: AppState.authenticated(user),
) {
on<AppUserChanged>(_onUserChanged);
on<AppOnboardingCompleted>(_onOnboardingCompleted);
on<AppLogoutRequested>(_onLogoutRequested);
on<AppOpened>(_onAppOpened);
_userSubscription = _userRepository.user.listen(_userChanged);
}
/// The number of app opens after which the login overlay is shown
/// for an unauthenticated user.
static const _appOpenedCountForLoginOverlay = 5;
final UserRepository _userRepository;
final NotificationsRepository _notificationsRepository;
late StreamSubscription<User> _userSubscription;
void _userChanged(User user) => add(AppUserChanged(user));
void _onUserChanged(AppUserChanged event, Emitter<AppState> emit) {
final user = event.user;
switch (state.status) {
case AppStatus.onboardingRequired:
case AppStatus.authenticated:
case AppStatus.unauthenticated:
return user != User.anonymous && user.isNewUser
? emit(AppState.onboardingRequired(user))
: user == User.anonymous
? emit(const AppState.unauthenticated())
: emit(AppState.authenticated(user));
}
}
void _onOnboardingCompleted(
AppOnboardingCompleted event,
Emitter<AppState> emit,
) {
if (state.status == AppStatus.onboardingRequired) {
return state.user == User.anonymous
? emit(const AppState.unauthenticated())
: emit(AppState.authenticated(state.user));
}
}
void _onLogoutRequested(AppLogoutRequested event, Emitter<AppState> emit) {
// We are disabling notifications when a user logs out because
// the user should not receive any notifications when logged out.
unawaited(_notificationsRepository.toggleNotifications(enable: false));
unawaited(_userRepository.logOut());
}
Future<void> _onAppOpened(AppOpened event, Emitter<AppState> emit) async {
if (state.user.isAnonymous) {
final appOpenedCount = await _userRepository.fetchAppOpenedCount();
if (appOpenedCount == _appOpenedCountForLoginOverlay - 1) {
emit(state.copyWith(showLoginOverlay: true));
}
if (appOpenedCount < _appOpenedCountForLoginOverlay + 1) {
await _userRepository.incrementAppOpenedCount();
}
}
}
@override
Future<void> close() {
_userSubscription.cancel();
return super.close();
}
}
| news_toolkit/flutter_news_example/lib/app/bloc/app_bloc.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/app/bloc/app_bloc.dart', 'repo_id': 'news_toolkit', 'token_count': 1139} |
import 'package:flutter/material.dart' hide Image, Spacer;
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/newsletter/newsletter.dart';
import 'package:flutter_news_example/slideshow/slideshow.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
class ArticleContentItem extends StatelessWidget {
const ArticleContentItem({
required this.block,
this.onSharePressed,
super.key,
});
/// The associated [NewsBlock] instance.
final NewsBlock block;
/// An optional callback which is invoked when the share button is pressed.
final VoidCallback? onSharePressed;
@override
Widget build(BuildContext context) {
final newsBlock = block;
if (newsBlock is DividerHorizontalBlock) {
return DividerHorizontal(block: newsBlock);
} else if (newsBlock is SpacerBlock) {
return Spacer(block: newsBlock);
} else if (newsBlock is ImageBlock) {
return Image(block: newsBlock);
} else if (newsBlock is VideoBlock) {
return Video(block: newsBlock);
} else if (newsBlock is TextCaptionBlock) {
final articleThemeColors =
Theme.of(context).extension<ArticleThemeColors>()!;
return TextCaption(
block: newsBlock,
colorValues: {
TextCaptionColor.normal: articleThemeColors.captionNormal,
TextCaptionColor.light: articleThemeColors.captionLight,
},
);
} else if (newsBlock is TextHeadlineBlock) {
return TextHeadline(block: newsBlock);
} else if (newsBlock is TextLeadParagraphBlock) {
return TextLeadParagraph(block: newsBlock);
} else if (newsBlock is TextParagraphBlock) {
return TextParagraph(block: newsBlock);
} else if (newsBlock is ArticleIntroductionBlock) {
return ArticleIntroduction(
block: newsBlock,
premiumText: context.l10n.newsBlockPremiumText,
);
} else if (newsBlock is VideoIntroductionBlock) {
return VideoIntroduction(block: newsBlock);
} else if (newsBlock is BannerAdBlock) {
return BannerAd(
block: newsBlock,
adFailedToLoadTitle: context.l10n.adLoadFailure,
);
} else if (newsBlock is NewsletterBlock) {
return const Newsletter();
} else if (newsBlock is HtmlBlock) {
return Html(block: newsBlock);
} else if (newsBlock is TrendingStoryBlock) {
return TrendingStory(
block: newsBlock,
title: context.l10n.trendingStoryTitle,
);
} else if (newsBlock is SlideshowIntroductionBlock) {
return SlideshowIntroduction(
block: newsBlock,
slideshowText: context.l10n.slideshow,
onPressed: (action) => _onContentItemAction(context, action),
);
} else {
// Render an empty widget for the unsupported block type.
return const SizedBox();
}
}
/// Handles actions triggered by tapping on article content items.
Future<void> _onContentItemAction(
BuildContext context,
BlockAction action,
) async {
if (action is NavigateToSlideshowAction) {
await Navigator.of(context).push<void>(
SlideshowPage.route(
slideshow: action.slideshow,
articleId: action.articleId,
),
);
}
}
}
| news_toolkit/flutter_news_example/lib/article/widgets/article_content_item.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/article/widgets/article_content_item.dart', 'repo_id': 'news_toolkit', 'token_count': 1232} |
export 'bloc/feed_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| news_toolkit/flutter_news_example/lib/feed/feed.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/feed/feed.dart', 'repo_id': 'news_toolkit', 'token_count': 36} |
part of 'login_bloc.dart';
abstract class LoginEvent extends Equatable {
const LoginEvent();
}
class LoginEmailChanged extends LoginEvent {
const LoginEmailChanged(this.email);
final String email;
@override
List<Object> get props => [email];
}
class SendEmailLinkSubmitted extends LoginEvent with AnalyticsEventMixin {
@override
AnalyticsEvent get event => const AnalyticsEvent('SendEmailLinkSubmitted');
}
class LoginGoogleSubmitted extends LoginEvent with AnalyticsEventMixin {
@override
AnalyticsEvent get event => const AnalyticsEvent('LoginGoogleSubmitted');
}
class LoginAppleSubmitted extends LoginEvent with AnalyticsEventMixin {
@override
AnalyticsEvent get event => const AnalyticsEvent('LoginAppleSubmitted');
}
class LoginTwitterSubmitted extends LoginEvent with AnalyticsEventMixin {
@override
AnalyticsEvent get event => const AnalyticsEvent('LoginTwitterSubmitted');
}
class LoginFacebookSubmitted extends LoginEvent with AnalyticsEventMixin {
@override
AnalyticsEvent get event => const AnalyticsEvent('LoginFacebookSubmitted');
}
| news_toolkit/flutter_news_example/lib/login/bloc/login_event.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/login/bloc/login_event.dart', 'repo_id': 'news_toolkit', 'token_count': 274} |
import 'dart:developer';
import 'package:analytics_repository/analytics_repository.dart';
import 'package:bloc/bloc.dart';
class AppBlocObserver extends BlocObserver {
AppBlocObserver({
required AnalyticsRepository analyticsRepository,
}) : _analyticsRepository = analyticsRepository;
final AnalyticsRepository _analyticsRepository;
@override
void onTransition(
Bloc<dynamic, dynamic> bloc,
Transition<dynamic, dynamic> transition,
) {
super.onTransition(bloc, transition);
log('onTransition ${bloc.runtimeType}: $transition');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
super.onError(bloc, error, stackTrace);
log('onError ${bloc.runtimeType}', error: error, stackTrace: stackTrace);
}
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
final dynamic state = change.nextState;
if (state is AnalyticsEventMixin) _analyticsRepository.track(state.event);
}
@override
void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
super.onEvent(bloc, event);
if (event is AnalyticsEventMixin) _analyticsRepository.track(event.event);
}
}
| news_toolkit/flutter_news_example/lib/main/bootstrap/app_bloc_observer.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/main/bootstrap/app_bloc_observer.dart', 'repo_id': 'news_toolkit', 'token_count': 420} |
part of 'newsletter_bloc.dart';
enum NewsletterStatus {
initial,
loading,
success,
failure,
}
class NewsletterState extends Equatable {
const NewsletterState({
this.status = NewsletterStatus.initial,
this.isValid = false,
this.email = const Email.pure(),
});
final NewsletterStatus status;
final bool isValid;
final Email email;
@override
List<Object> get props => [status, email, isValid];
NewsletterState copyWith({
NewsletterStatus? status,
Email? email,
bool? isValid,
}) =>
NewsletterState(
status: status ?? this.status,
email: email ?? this.email,
isValid: isValid ?? this.isValid,
);
}
| news_toolkit/flutter_news_example/lib/newsletter/bloc/newsletter_state.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/newsletter/bloc/newsletter_state.dart', 'repo_id': 'news_toolkit', 'token_count': 240} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/onboarding/onboarding.dart';
class OnboardingView extends StatefulWidget {
const OnboardingView({super.key});
@override
State<OnboardingView> createState() => _OnboardingViewState();
}
class _OnboardingViewState extends State<OnboardingView> {
final _controller = PageController();
static const _onboardingItemSwitchDuration = Duration(milliseconds: 500);
static const _onboardingPageTwo = 1;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return BlocListener<OnboardingBloc, OnboardingState>(
listener: (context, state) {
if ((state is EnablingAdTrackingSucceeded ||
state is EnablingAdTrackingFailed) &&
_controller.page != _onboardingPageTwo) {
_controller.animateToPage(
_onboardingPageTwo,
duration: _onboardingItemSwitchDuration,
curve: Curves.easeInOut,
);
} else if (state is EnablingNotificationsSucceeded) {
context.read<AppBloc>().add(const AppOnboardingCompleted());
}
},
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Column(
key: const Key('onboarding_scrollableColumn'),
mainAxisSize: MainAxisSize.min,
children: [
const _OnboardingTitle(),
const _OnboardingSubtitle(),
SizedBox(
height: MediaQuery.of(context).size.height * .59,
child: PageView(
key: const Key('onboarding_pageView'),
controller: _controller,
physics: const NeverScrollableScrollPhysics(),
children: [
OnboardingViewItem(
key: const Key('onboarding_pageOne'),
pageNumberTitle: l10n.onboardingItemFirstNumberTitle,
title: l10n.onboardingItemFirstTitle,
subtitle: l10n.onboardingItemFirstSubtitleTitle,
primaryButton: AppButton.darkAqua(
key:
const Key('onboardingItem_primaryButton_pageOne'),
onPressed: () => context
.read<OnboardingBloc>()
.add(const EnableAdTrackingRequested()),
child: Text(l10n.onboardingItemFirstButtonTitle),
),
secondaryButton: AppButton.smallTransparent(
key: const Key(
'onboardingItem_secondaryButton_pageOne',
),
onPressed: () => _controller.animateToPage(
_onboardingPageTwo,
duration: _onboardingItemSwitchDuration,
curve: Curves.easeInOut,
),
child: Text(
context.l10n.onboardingItemSecondaryButtonTitle,
),
),
),
OnboardingViewItem(
key: const Key('onboarding_pageTwo'),
pageNumberTitle: l10n.onboardingItemSecondNumberTitle,
title: l10n.onboardingItemSecondTitle,
subtitle: l10n.onboardingItemSecondSubtitleTitle,
primaryButton: AppButton.darkAqua(
key:
const Key('onboardingItem_primaryButton_pageTwo'),
onPressed: () => context
.read<OnboardingBloc>()
.add(const EnableNotificationsRequested()),
child: Text(l10n.onboardingItemSecondButtonTitle),
),
secondaryButton: AppButton.smallTransparent(
key: const Key(
'onboardingItem_secondaryButton_pageTwo',
),
onPressed: () => context
.read<AppBloc>()
.add(const AppOnboardingCompleted()),
child: Text(
context.l10n.onboardingItemSecondaryButtonTitle,
),
),
),
],
),
),
],
),
),
],
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
class _OnboardingTitle extends StatelessWidget {
const _OnboardingTitle();
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Padding(
key: const Key('onboardingView_onboardingTitle'),
padding: const EdgeInsets.only(
top: AppSpacing.xxxlg + AppSpacing.sm,
bottom: AppSpacing.xxs,
),
child: Text(
context.l10n.onboardingWelcomeTitle,
style: theme.textTheme.displayLarge?.apply(
color: AppColors.white,
),
textAlign: TextAlign.center,
),
);
}
}
class _OnboardingSubtitle extends StatelessWidget {
const _OnboardingSubtitle();
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Padding(
key: const Key('onboardingView_onboardingSubtitle'),
padding: const EdgeInsets.only(
top: AppSpacing.xlg,
),
child: Text(
context.l10n.onboardingSubtitle,
style: theme.textTheme.titleMedium?.apply(
color: AppColors.white,
),
textAlign: TextAlign.center,
),
);
}
}
| news_toolkit/flutter_news_example/lib/onboarding/view/onboarding_view.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/onboarding/view/onboarding_view.dart', 'repo_id': 'news_toolkit', 'token_count': 3261} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
class SlideshowView extends StatelessWidget {
const SlideshowView({required this.block, super.key});
final SlideshowBlock block;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final isSubscriber =
context.select<AppBloc, bool>((bloc) => bloc.state.isUserSubscribed);
final uri = context.select((ArticleBloc bloc) => bloc.state.uri);
return Scaffold(
appBar: AppBar(
leading: const AppBackButton.light(),
actions: [
Row(
children: [
if (uri != null && uri.toString().isNotEmpty)
Padding(
key: const Key('slideshowPage_shareButton'),
padding: const EdgeInsets.only(right: AppSpacing.lg),
child: ShareButton(
shareText: context.l10n.shareText,
color: AppColors.white,
onPressed: () {
context.read<ArticleBloc>().add(ShareRequested(uri: uri));
},
),
),
if (!isSubscriber) const ArticleSubscribeButton()
],
)
],
),
backgroundColor: AppColors.darkBackground,
body: Slideshow(
block: block,
categoryTitle: l10n.slideshow.toUpperCase(),
navigationLabel: l10n.slideshow_of_title,
),
);
}
}
| news_toolkit/flutter_news_example/lib/slideshow/view/slideshow_view.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/slideshow/view/slideshow_view.dart', 'repo_id': 'news_toolkit', 'token_count': 844} |
part of 'widgets/terms_of_service_body.dart';
const String termsOfServiceMockText =
'Curabitur vel volutpat eros, in interdum eros.Pellentesque lorem magna, '
'facilisis vel diam nec, sagittis fermentum purus. '
'Maecenas placerat urna ullamcorper ultrices elementum. '
'Quisque maximus lectus ac posuere posuere. Fusce eu molestie libero. '
'Nulla fringilla enim et elit facilisis blandit. '
'\n\nEtiam tincidunt porta vulputate. '
'Maecenas congue convallis odio sit amet pharetra. '
'\nPhasellus sagittis dapibus erat non sagittis. '
'Praesent imperdiet lectus urna, a sagittis sapien pulvinar vel. '
'Orci varius natoque penatibus et magnis dis parturient montes, '
'nascetur ridiculus mus. Proin eget neque turpis. '
'Quisque a lectus feugiat, sollicitudin massa ac, ultricies tellus. '
'Proin rutrum neque nec vehicula ultrices. Suspendisse venenatis odio mi. '
'Sed dictum congue nisi id finibus. '
'\n\nMorbi malesuada lorem est '
'Phasellus eget mi risus. Nulla facilisi . '
'Aliquam fermentum malesuada metus, nec pretium odio efficitur in. '
'In condimentum semper ipsum quis cursus. '
'Aenean in ex at leo porta ultrices. '
'Curabitur vel volutpat eros, in interdum eros. '
'\n\nPellentesque lorem magna, facilisis vel diam nec, '
'sagittis fermentum purus. '
'Maecenas placerat urna ullamcorper ultrices elementum. '
'Quisque maximus lectus ac posuere posuere. '
'Fusce eu molestie libero. Nulla fringilla enim et elit facilisis blandit. '
'Etiam tincidunt porta vulputate. '
'Maecenas congue convallis odio sit amet pharetra. '
'Phasellus sagittis dapibus erat non sagittis. '
'Praesent imperdiet lectus urna, a sagittis sapien pulvinar vel. '
'Orci varius natoque penatibus et magnis dis parturient montes, '
'nascetur ridiculus mus. Proin eget neque turpis. '
'Quisque a lectus feugiat, sollicitudin massa ac, ultricies tellus. '
'Proin rutrum neque nec vehicula ultrices. '
'Suspendisse venenatis odio mi. Sed dictum congue nisi id finibus. '
'Morbi malesuada lorem est, id efficitur mauris ultrices sit amet. '
'Phasellus eget mi risus. Nulla facilisi. '
'Aliquam fermentum malesuada metus, nec pretium odio efficitur in. '
'In condimentum semper ipsum quis cursus. '
'Aenean in ex at leo porta ultrices. ';
| news_toolkit/flutter_news_example/lib/terms_of_service/terms_of_service_mock_text.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/terms_of_service/terms_of_service_mock_text.dart', 'repo_id': 'news_toolkit', 'token_count': 985} |
import 'package:app_ui/app_ui.dart' show AppSpacing, Assets, showAppModal;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/user_profile/user_profile.dart';
/// A user profile button which displays a [LoginButton]
/// for the unauthenticated user or an [OpenProfileButton]
/// for the authenticated user.
class UserProfileButton extends StatelessWidget {
const UserProfileButton({super.key});
@override
Widget build(BuildContext context) {
final isAnonymous = context.select<AppBloc, bool>(
(bloc) => bloc.state.user.isAnonymous,
);
return isAnonymous ? const LoginButton() : const OpenProfileButton();
}
}
@visibleForTesting
class LoginButton extends StatelessWidget {
const LoginButton({super.key});
@override
Widget build(BuildContext context) {
return IconButton(
icon: Assets.icons.logInIcon.svg(),
iconSize: 24,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.sm,
),
onPressed: () => showAppModal<void>(
context: context,
builder: (context) => const LoginModal(),
routeSettings: const RouteSettings(name: LoginModal.name),
),
tooltip: context.l10n.loginTooltip,
);
}
}
@visibleForTesting
class OpenProfileButton extends StatelessWidget {
const OpenProfileButton({super.key});
@override
Widget build(BuildContext context) {
return IconButton(
icon: Assets.icons.profileIcon.svg(),
iconSize: 24,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.sm,
),
onPressed: () => Navigator.of(context).push(UserProfilePage.route()),
tooltip: context.l10n.openProfileTooltip,
);
}
}
| news_toolkit/flutter_news_example/lib/user_profile/widgets/user_profile_button.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/lib/user_profile/widgets/user_profile_button.dart', 'repo_id': 'news_toolkit', 'token_count': 722} |
name: analytics_repository
description: Package which manages the analytics domain.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
equatable: ^2.0.0
firebase_analytics: ^10.0.3
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.2
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/analytics_repository/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/analytics_repository/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 141} |
export 'app_back_button_page.dart';
export 'app_button_page.dart';
export 'app_logo_page.dart';
export 'app_switch_page.dart';
export 'app_text_field_page.dart';
export 'show_app_modal_page.dart';
export 'widgets_page.dart';
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/widgets.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/widgets.dart', 'repo_id': 'news_toolkit', 'token_count': 91} |
name: app_ui
description: App UI Component Library
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
flutter:
sdk: flutter
flutter_svg: ^2.0.5
intl: ^0.19.0
mockingjay: ^0.4.0
dev_dependencies:
build_runner: ^2.0.3
flutter_gen_runner: ^5.2.0
flutter_test:
sdk: flutter
very_good_analysis: ^5.1.0
flutter:
uses-material-design: true
assets:
- assets/icons/
- assets/images/
fonts:
- family: NotoSerif
fonts:
- asset: assets/fonts/NotoSerif-Bold.ttf
weight: 700
- asset: assets/fonts/NotoSerif-SemiBold.ttf
weight: 600
- asset: assets/fonts/NotoSerif-Medium.ttf
weight: 500
- asset: assets/fonts/NotoSerif-Regular.ttf
weight: 400
- family: NotoSansDisplay
fonts:
- asset: assets/fonts/NotoSansDisplay-Regular.ttf
weight: 400
- asset: assets/fonts/NotoSansDisplay-SemiBold.ttf
weight: 600
- family: Montserrat
fonts:
- asset: assets/fonts/Montserrat-Medium.ttf
weight: 500
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/app_ui/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 604} |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/article_repository/analysis_options.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/article_repository/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 23} |
// ignore_for_file: prefer_const_constructors
import 'package:authentication_client/authentication_client.dart';
import 'package:test/test.dart';
void main() {
group('AuthenticationUser', () {
test('supports value equality', () {
final userA = AuthenticationUser(id: 'A');
final secondUserA = AuthenticationUser(id: 'A');
final userB = AuthenticationUser(id: 'B');
expect(userA, equals(secondUserA));
expect(userA, isNot(equals(userB)));
});
test('isAnonymous returns true for anonymous user', () {
expect(AuthenticationUser.anonymous.isAnonymous, isTrue);
});
});
}
| news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/test/src/models/authentication_user_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/test/src/models/authentication_user_test.dart', 'repo_id': 'news_toolkit', 'token_count': 219} |
export 'src/deep_link_client.dart';
| news_toolkit/flutter_news_example/packages/deep_link_client/lib/deep_link_client.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/deep_link_client/lib/deep_link_client.dart', 'repo_id': 'news_toolkit', 'token_count': 14} |
export 'package:formz/formz.dart';
export 'src/email.dart';
| news_toolkit/flutter_news_example/packages/form_inputs/lib/form_inputs.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/form_inputs/lib/form_inputs.dart', 'repo_id': 'news_toolkit', 'token_count': 25} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:news_blocks_ui/src/sliver_grid_custom_delegate.dart';
/// {@template post_grid}
/// A reusable post grid view.
/// {@endtemplate}
class PostGrid extends StatelessWidget {
/// {@macro post_grid}
const PostGrid({
required this.gridGroupBlock,
required this.premiumText,
this.isLocked = false,
this.onPressed,
super.key,
});
/// The associated [PostGridGroupBlock] instance.
final PostGridGroupBlock gridGroupBlock;
/// Text displayed when post is premium content.
final String premiumText;
/// Whether this post is a locked post.
final bool isLocked;
/// An optional callback which is invoked when the action is triggered.
/// A [Uri] from the associated [BlockAction] is provided to the callback.
final BlockActionCallback? onPressed;
@override
Widget build(BuildContext context) {
if (gridGroupBlock.tiles.isEmpty) {
return const SliverToBoxAdapter(child: SizedBox());
}
final deviceWidth = MediaQuery.of(context).size.width;
return SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
sliver: SliverGrid(
gridDelegate: CustomMaxCrossAxisDelegate(
maxCrossAxisExtent: deviceWidth / 2 - (AppSpacing.md / 2),
mainAxisSpacing: AppSpacing.md,
crossAxisSpacing: AppSpacing.md,
childAspectRatio: 3 / 2,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final block = gridGroupBlock.tiles[index];
if (index == 0) {
return PostLarge(
block: block.toPostLargeBlock(),
premiumText: premiumText,
isLocked: isLocked,
onPressed: onPressed,
);
}
return PostMedium(
block: block.toPostMediumBlock(),
onPressed: onPressed,
);
},
childCount: gridGroupBlock.tiles.length,
),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_grid.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_grid.dart', 'repo_id': 'news_toolkit', 'token_count': 909} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
/// {@template text_lead_paragraph}
/// A reusable text lead paragraph news block widget.
/// {@endtemplate}
class TextLeadParagraph extends StatelessWidget {
/// {@macro text_lead_paragraph}
const TextLeadParagraph({required this.block, super.key});
/// The associated [TextLeadParagraphBlock] instance.
final TextLeadParagraphBlock block;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: Text(
block.text,
style: Theme.of(context).textTheme.titleLarge,
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/text_lead_paragraph.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/text_lead_paragraph.dart', 'repo_id': 'news_toolkit', 'token_count': 252} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template progress_indicator}
/// A reusable progress indicator of news blocks.
/// {@endtemplate}
class ProgressIndicator extends StatelessWidget {
/// {@macro progress_indicator}
const ProgressIndicator({
super.key,
this.progress,
this.color = AppColors.gainsboro,
});
/// The current progress of this indicator (between 0 and 1).
final double? progress;
/// The color of this indicator.
///
/// Defaults to [AppColors.gainsboro].
final Color color;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: color,
child: Center(
child: CircularProgressIndicator(value: progress),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/progress_indicator.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/progress_indicator.dart', 'repo_id': 'news_toolkit', 'token_count': 258} |
// ignore_for_file: prefer_const_constructors
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart' as flutter_html;
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../helpers/helpers.dart';
class _MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
class _FakeLaunchOptions extends Fake implements LaunchOptions {}
void main() {
group('Html', () {
late UrlLauncherPlatform urlLauncher;
setUpAll(() {
registerFallbackValue(_FakeLaunchOptions());
});
setUp(() {
urlLauncher = _MockUrlLauncher();
UrlLauncherPlatform.instance = urlLauncher;
});
testWidgets('renders HTML text correctly', (tester) async {
const block = HtmlBlock(content: '<p>Hello</p>');
await tester.pumpApp(Html(block: block));
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html && widget.data == block.content,
),
findsOneWidget,
);
});
group('hyperlinks', () {
testWidgets('does not launch the url when it is empty', (tester) async {
const block = HtmlBlock(
content: '<a href="#">flutter.dev</a>',
);
await tester.pumpApp(Html(block: block));
await tester.tap(
find.textContaining('flutter.dev', findRichText: true),
);
verifyNever(() => urlLauncher.launchUrl(any(), any()));
});
testWidgets('does not launch the url when it is invalid', (tester) async {
const block = HtmlBlock(
content: '<a href="::Not valid URI::">flutter.dev</a>',
);
await tester.pumpApp(Html(block: block));
await tester.tap(
find.textContaining('flutter.dev', findRichText: true),
);
verifyNever(() => urlLauncher.launchUrl(any(), any()));
});
testWidgets('launches the url when it is a valid url', (tester) async {
const block = HtmlBlock(
content: '<a href="https://flutter.dev">flutter.dev</a>',
);
await tester.pumpApp(Html(block: block));
await tester.tap(
find.textContaining('flutter.dev', findRichText: true),
);
verify(
() => urlLauncher.launchUrl('https://flutter.dev', any()),
).called(1);
});
});
group('styles', () {
testWidgets('<p> tags correctly', (tester) async {
const block = HtmlBlock(content: '<p>Test</p>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['p']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(theme.textTheme.bodyLarge!)
.generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h1> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h1>Test</h1>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h1']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.displayLarge!,
).generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h2> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h2>Test</h2>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h2']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.displayMedium!,
).generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h3> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h3>Test</h3>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h3']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.displaySmall!,
).generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h4> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h4>Test</h4>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h4']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.headlineMedium!,
).generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h5> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h5>Test</h5>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h5']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.headlineSmall!,
).generateTextStyle(),
),
findsOneWidget,
);
});
testWidgets('<h6> tags correctly', (tester) async {
const block = HtmlBlock(content: '<h6>Test</h6>');
final theme = AppTheme().themeData;
await tester.pumpApp(
MaterialApp(
theme: theme,
home: Html(block: block),
),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is flutter_html.Html &&
widget.style['h6']!.generateTextStyle() ==
flutter_html.Style.fromTextStyle(
theme.textTheme.titleLarge!,
).generateTextStyle(),
),
findsOneWidget,
);
});
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/html_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/html_test.dart', 'repo_id': 'news_toolkit', 'token_count': 3795} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import '../helpers/helpers.dart';
void main() {
group('Video', () {
setUp(
() {
final fakeVideoPlayerPlatform = FakeVideoPlayerPlatform();
VideoPlayerPlatform.instance = fakeVideoPlayerPlatform;
},
);
testWidgets('renders InlineVideo with correct video', (tester) async {
const block = VideoBlock(videoUrl: 'videoUrl');
await tester.pumpApp(
Video(block: block),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is InlineVideo && widget.videoUrl == block.videoUrl,
),
findsOneWidget,
);
});
testWidgets('renders ProgressIndicator when loading', (tester) async {
const block = VideoBlock(videoUrl: 'videoUrl');
await tester.pumpWidget(
Video(block: block),
);
expect(
find.byType(ProgressIndicator, skipOffstage: false),
findsOneWidget,
);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/video_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/video_test.dart', 'repo_id': 'news_toolkit', 'token_count': 523} |
name: firebase_notifications_client
description: A Firebase Cloud Messaging notifications client.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
firebase_messaging: ^14.0.3
flutter:
sdk: flutter
notifications_client:
path: ../notifications_client
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.2
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 162} |
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:storage/storage.dart';
/// {@template secure_storage}
/// A Secure Storage client which implements the base [Storage] interface.
/// [SecureStorage] uses `FlutterSecureStorage` internally.
///
/// ```dart
/// // Create a `SecureStorage` instance.
/// final storage = const SecureStorage();
///
/// // Write a key/value pair.
/// await storage.write(key: 'my_key', value: 'my_value');
///
/// // Read value for key.
/// final value = await storage.read(key: 'my_key'); // 'my_value'
/// ```
/// {@endtemplate}
class SecureStorage implements Storage {
/// {@macro secure_storage}
const SecureStorage([FlutterSecureStorage? secureStorage])
: _secureStorage = secureStorage ?? const FlutterSecureStorage();
final FlutterSecureStorage _secureStorage;
@override
Future<String?> read({required String key}) async {
try {
return await _secureStorage.read(key: key);
} on Exception catch (error, stackTrace) {
Error.throwWithStackTrace(StorageException(error), stackTrace);
}
}
@override
Future<void> write({required String key, required String value}) async {
try {
await _secureStorage.write(key: key, value: value);
} on Exception catch (error, stackTrace) {
Error.throwWithStackTrace(StorageException(error), stackTrace);
}
}
@override
Future<void> delete({required String key}) async {
try {
await _secureStorage.delete(key: key);
} on Exception catch (error, stackTrace) {
Error.throwWithStackTrace(StorageException(error), stackTrace);
}
}
@override
Future<void> clear() async {
try {
await _secureStorage.deleteAll();
} on Exception catch (error, stackTrace) {
Error.throwWithStackTrace(StorageException(error), stackTrace);
}
}
}
| news_toolkit/flutter_news_example/packages/storage/secure_storage/lib/src/secure_storage.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/storage/secure_storage/lib/src/secure_storage.dart', 'repo_id': 'news_toolkit', 'token_count': 603} |
name: user_repository
description: Dart package which manages the user domain.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
authentication_client:
path: ../authentication_client/authentication_client
deep_link_client:
path: ../deep_link_client
equatable: ^2.0.3
flutter_news_example_api:
path: ../../api
package_info_client:
path: ../package_info_client
rxdart: ^0.27.5
storage:
path: ../storage/storage
dev_dependencies:
mocktail: ^1.0.2
test: ^1.21.4
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/user_repository/pubspec.yaml/0 | {'file_path': 'news_toolkit/flutter_news_example/packages/user_repository/pubspec.yaml', 'repo_id': 'news_toolkit', 'token_count': 221} |
import 'package:flutter/material.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/home/home.dart';
import 'package:flutter_news_example/onboarding/onboarding.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('onGenerateAppViewPages', () {
test('returns [OnboardingPage] when onboardingRequired', () {
expect(
onGenerateAppViewPages(AppStatus.onboardingRequired, []),
[
isA<MaterialPage<void>>().having(
(p) => p.child,
'child',
isA<OnboardingPage>(),
)
],
);
});
test('returns [HomePage] when authenticated', () {
expect(
onGenerateAppViewPages(AppStatus.authenticated, []),
[
isA<MaterialPage<void>>().having(
(p) => p.child,
'child',
isA<HomePage>(),
)
],
);
});
test('returns [HomePage] when unauthenticated', () {
expect(
onGenerateAppViewPages(AppStatus.unauthenticated, []),
[
isA<MaterialPage<void>>().having(
(p) => p.child,
'child',
isA<HomePage>(),
)
],
);
});
});
}
| news_toolkit/flutter_news_example/test/app/routes/routes_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/app/routes/routes_test.dart', 'repo_id': 'news_toolkit', 'token_count': 614} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/categories/categories.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:news_repository/news_repository.dart';
void main() {
group('CategoriesState', () {
test('initial has correct status', () {
expect(
CategoriesState.initial().status,
equals(CategoriesStatus.initial),
);
});
test('supports value comparisons', () {
expect(
CategoriesState.initial(),
equals(CategoriesState.initial()),
);
});
group('copyWith', () {
test(
'returns same object '
'when no properties are passed', () {
expect(
CategoriesState.initial().copyWith(),
equals(CategoriesState.initial()),
);
});
test(
'returns object with updated status '
'when status is passed', () {
expect(
CategoriesState.initial().copyWith(
status: CategoriesStatus.loading,
),
equals(
CategoriesState(
status: CategoriesStatus.loading,
),
),
);
});
test(
'returns object with updated categories '
'when categories is passed', () {
final categories = [Category.top, Category.health];
expect(
CategoriesState(status: CategoriesStatus.populated)
.copyWith(categories: categories),
equals(
CategoriesState(
status: CategoriesStatus.populated,
categories: categories,
),
),
);
});
test(
'returns object with updated selectedCategory '
'when selectedCategory is passed', () {
const selectedCategory = Category.top;
expect(
CategoriesState(status: CategoriesStatus.populated)
.copyWith(selectedCategory: selectedCategory),
equals(
CategoriesState(
status: CategoriesStatus.populated,
selectedCategory: selectedCategory,
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/categories/bloc/categories_state_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/categories/bloc/categories_state_test.dart', 'repo_id': 'news_toolkit', 'token_count': 985} |
// ignore_for_file: prefer_const_constructors, avoid_redundant_argument_values
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'dart:async';
import 'package:app_ui/app_ui.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/categories/categories.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/home/home.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/navigation/navigation.dart';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_news_example/user_profile/user_profile.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_repository/news_repository.dart';
import '../../helpers/helpers.dart';
class MockHomeCubit extends MockCubit<HomeState> implements HomeCubit {}
class MockCategoriesBloc extends MockBloc<CategoriesEvent, CategoriesState>
implements CategoriesBloc {}
class MockFeedBloc extends MockBloc<FeedEvent, FeedState> implements FeedBloc {}
class MockNewsRepository extends Mock implements NewsRepository {}
class MockAppBloc extends Mock implements AppBloc {}
void main() {
initMockHydratedStorage();
late NewsRepository newsRepository;
late HomeCubit cubit;
late CategoriesBloc categoriesBloc;
late FeedBloc feedBloc;
late AppBloc appBloc;
const categories = [Category.top, Category.technology];
final feed = <Category, List<NewsBlock>>{
Category.top: [
SectionHeaderBlock(title: 'Top'),
DividerHorizontalBlock(),
SpacerBlock(spacing: Spacing.medium),
],
Category.technology: [
SectionHeaderBlock(title: 'Technology'),
DividerHorizontalBlock(),
SpacerBlock(spacing: Spacing.medium),
],
};
setUp(() {
newsRepository = MockNewsRepository();
categoriesBloc = MockCategoriesBloc();
feedBloc = MockFeedBloc();
cubit = MockHomeCubit();
appBloc = MockAppBloc();
when(() => appBloc.state).thenReturn(
AppState(
showLoginOverlay: false,
status: AppStatus.unauthenticated,
),
);
when(() => categoriesBloc.state).thenReturn(
CategoriesState(
categories: categories,
status: CategoriesStatus.populated,
),
);
when(() => feedBloc.state).thenReturn(
FeedState(
feed: feed,
status: FeedStatus.populated,
),
);
when(newsRepository.getCategories).thenAnswer(
(_) async => CategoriesResponse(
categories: [Category.top],
),
);
when(() => cubit.state).thenReturn(HomeState.topStories);
});
group('HomeView', () {
testWidgets('renders AppBar with AppLogo', (tester) async {
when(() => cubit.state).thenReturn(HomeState.topStories);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
expect(
find.byWidgetPredicate(
(widget) => widget is AppBar && widget.title is AppLogo,
),
findsOneWidget,
);
});
testWidgets('renders UserProfileButton', (tester) async {
when(() => cubit.state).thenReturn(HomeState.topStories);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
expect(find.byType(UserProfileButton), findsOneWidget);
});
testWidgets(
'renders NavDrawer '
'when menu icon is tapped', (tester) async {
when(() => cubit.state).thenReturn(HomeState.topStories);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
expect(find.byType(NavDrawer), findsNothing);
await tester.tap(find.byIcon(Icons.menu));
await tester.pump();
expect(find.byType(NavDrawer), findsOneWidget);
});
testWidgets('renders FeedView', (tester) async {
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
expect(find.byType(FeedView), findsOneWidget);
});
testWidgets('shows LoginOverlay when showLoginOverlay is true',
(tester) async {
whenListen(
appBloc,
Stream.fromIterable([
AppState(status: AppStatus.unauthenticated, showLoginOverlay: false),
AppState(status: AppStatus.unauthenticated, showLoginOverlay: true),
]),
);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
appBloc: appBloc,
);
expect(find.byType(LoginModal), findsOneWidget);
});
});
group('BottomNavigationBar', () {
testWidgets(
'has selected index to 0 by default.',
(tester) async {
when(() => cubit.state).thenReturn(HomeState.topStories);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
expect(find.byType(FeedView), findsOneWidget);
},
);
testWidgets(
'set tab to selected index 0 when top stories is tapped.',
(tester) async {
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
await tester.ensureVisible(find.byType(BottomNavBar));
await tester.tap(find.byIcon(Icons.home_outlined));
verify(() => cubit.setTab(0)).called(1);
},
);
testWidgets(
'set tab to selected index 1 when search is tapped.',
(tester) async {
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
await tester.ensureVisible(find.byType(BottomNavBar));
await tester.tap(find.byKey(Key('bottomNavBar_search')));
verify(() => cubit.setTab(1)).called(1);
},
);
testWidgets(
'unfocuses keyboard when tab is changed.',
(tester) async {
final controller = StreamController<HomeState>();
whenListen(
cubit,
controller.stream,
initialState: HomeState.topStories,
);
await pumpHomeView(
tester: tester,
cubit: cubit,
categoriesBloc: categoriesBloc,
feedBloc: feedBloc,
newsRepository: newsRepository,
);
await tester.ensureVisible(find.byType(BottomNavBar));
await tester.tap(find.byKey(Key('bottomNavBar_search')));
verify(() => cubit.setTab(1)).called(1);
controller.add(HomeState.search);
await tester.pump(kThemeAnimationDuration);
await tester.showKeyboard(find.byType(SearchTextField));
final initialFocus = tester.binding.focusManager.primaryFocus;
controller.add(HomeState.topStories);
await tester.pump();
expect(
tester.binding.focusManager.primaryFocus,
isNot(equals(initialFocus)),
);
},
);
});
}
Future<void> pumpHomeView({
required WidgetTester tester,
required HomeCubit cubit,
required CategoriesBloc categoriesBloc,
required FeedBloc feedBloc,
required NewsRepository newsRepository,
AppBloc? appBloc,
}) async {
await tester.pumpApp(
MultiBlocProvider(
providers: [
BlocProvider.value(
value: categoriesBloc,
),
BlocProvider.value(
value: feedBloc,
),
BlocProvider.value(
value: cubit,
),
],
child: HomeView(),
),
newsRepository: newsRepository,
appBloc: appBloc,
);
}
| news_toolkit/flutter_news_example/test/home/view/home_view_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/home/view/home_view_test.dart', 'repo_id': 'news_toolkit', 'token_count': 3577} |
// ignore_for_file: prefer_const_constructors
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/navigation/navigation.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
group('BottomNavBar', () {
testWidgets(
'renders with currentIndex to 0 by default.',
(tester) async {
await tester.pumpApp(
BottomNavBar(
currentIndex: 0,
onTap: (selectedIndex) {},
),
);
expect(find.byType(BottomNavBar), findsOneWidget);
},
);
});
testWidgets('calls onTap when navigation bar item is tapped', (tester) async {
final completer = Completer<void>();
await tester.pumpApp(
Scaffold(
body: Container(),
bottomNavigationBar: BottomNavBar(
currentIndex: 0,
onTap: (value) => completer.complete(),
),
),
);
await tester.ensureVisible(find.byType(BottomNavigationBar));
await tester.tap(find.byIcon(Icons.home_outlined));
expect(completer.isCompleted, isTrue);
});
testWidgets(
'renders BottomNavigationBar with currentIndex',
(tester) async {
const currentIndex = 1;
await tester.pumpApp(
BottomNavBar(
currentIndex: currentIndex,
onTap: (selectedIndex) {},
),
);
final bottomNavBar = tester.widget<BottomNavBar>(
find.byType(BottomNavBar),
);
expect(bottomNavBar.currentIndex, equals(currentIndex));
},
);
}
| news_toolkit/flutter_news_example/test/navigation/view/bottom_nav_bar_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/navigation/view/bottom_nav_bar_test.dart', 'repo_id': 'news_toolkit', 'token_count': 681} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/onboarding/onboarding.dart';
import 'package:test/test.dart';
void main() {
group('OnboardingState', () {
group('OnboardingInitial', () {
test('supports value comparisons', () {
final state1 = OnboardingInitial();
final state2 = OnboardingInitial();
expect(state1, equals(state2));
});
});
group('OnboardingInitial', () {
test('supports value comparisons', () {
final state1 = OnboardingInitial();
final state2 = OnboardingInitial();
expect(state1, equals(state2));
});
});
group('EnablingNotifications', () {
test('supports value comparisons', () {
final state1 = EnablingNotifications();
final state2 = EnablingNotifications();
expect(state1, equals(state2));
});
});
group('EnablingNotificationsSucceeded', () {
test('supports value comparisons', () {
final state1 = EnablingNotificationsSucceeded();
final state2 = EnablingNotificationsSucceeded();
expect(state1, equals(state2));
});
});
group('EnablingNotificationsFailed', () {
test('supports value comparisons', () {
final state1 = EnablingNotificationsFailed();
final state2 = EnablingNotificationsFailed();
expect(state1, equals(state2));
});
});
});
}
| news_toolkit/flutter_news_example/test/onboarding/bloc/onboarding_state_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/onboarding/bloc/onboarding_state_test.dart', 'repo_id': 'news_toolkit', 'token_count': 541} |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockingjay/mockingjay.dart';
import '../../helpers/helpers.dart';
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
void main() {
group('ManageSubscriptionPage', () {
test('has a route', () {
expect(ManageSubscriptionPage.route(), isA<MaterialPageRoute<void>>());
});
testWidgets('renders ManageSubscriptionView', (tester) async {
await tester.pumpApp(ManageSubscriptionPage());
expect(find.byType(ManageSubscriptionView), findsOneWidget);
});
});
group('ManageSubscriptionView', () {
final appBloc = MockAppBloc();
testWidgets(
'navigates back '
'when subscriptions ListTile tapped', (tester) async {
final navigator = MockNavigator();
when(navigator.maybePop).thenAnswer((_) async => true);
await tester.pumpApp(
ManageSubscriptionPage(),
appBloc: appBloc,
navigator: navigator,
);
await tester.tap(find.byKey(Key('manageSubscription_subscriptions')));
await tester.pumpAndSettle();
verify(navigator.maybePop).called(1);
});
});
}
| news_toolkit/flutter_news_example/test/subscriptions/view/manage_subscription_page_test.dart/0 | {'file_path': 'news_toolkit/flutter_news_example/test/subscriptions/view/manage_subscription_page_test.dart', 'repo_id': 'news_toolkit', 'token_count': 541} |
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:equatable/equatable.dart';
abstract class AuthState extends Equatable {}
class AuthInitial extends AuthState {
@override
List<Object> get props => [];
}
class AuthLoading extends AuthState {
@override
List<Object> get props => [];
}
class AuthAuthenticated extends AuthState {
@override
List<Object> get props => [];
}
class AuthUnauthenticated extends AuthState {
@override
List<Object> get props => [];
}
| notely/lib/app/cubits/auth/auth_state.dart/0 | {'file_path': 'notely/lib/app/cubits/auth/auth_state.dart', 'repo_id': 'notely', 'token_count': 154} |
import 'package:flutter/material.dart';
import '../../../src/utils/margins/y_margin.dart';
class NotelyFormField extends StatefulWidget {
const NotelyFormField({
super.key,
this.controller,
required this.hint,
required this.label,
});
final String label;
final String hint;
final TextEditingController? controller;
@override
State<NotelyFormField> createState() => _NotelyFormFieldState();
}
final _border = OutlineInputBorder(
borderSide: const BorderSide(
color: Color(0xFFF2E5D5),
width: 1,
),
borderRadius: BorderRadius.circular(12),
);
class _NotelyFormFieldState extends State<NotelyFormField> {
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.label,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Color(0xFF403B36),
),
),
const YMargin(8),
TextFormField(
controller: widget.controller,
decoration: InputDecoration(
filled: true,
fillColor: const Color(0xFFFFFDFA),
hintText: widget.hint,
enabledBorder: _border,
errorBorder: _border,
border: _border,
focusedBorder: _border,
disabledBorder: _border,
),
),
],
);
}
}
| notely/lib/app/ui/widgets/notely_form_field.dart/0 | {'file_path': 'notely/lib/app/ui/widgets/notely_form_field.dart', 'repo_id': 'notely', 'token_count': 643} |
import 'package:ovavue/domain.dart';
import 'theme_mode_storage.dart';
class PreferencesMockImpl implements PreferencesRepository {
PreferencesMockImpl(this._themeModeStorage);
final ThemeModeStorage _themeModeStorage;
@override
Future<int?> fetchThemeMode() async => _themeModeStorage.get();
@override
Future<bool> updateThemeMode(int themeMode) async {
await _themeModeStorage.set(themeMode);
return true;
}
}
| ovavue/lib/data/repositories/preferences/preferences_mock_impl.dart/0 | {'file_path': 'ovavue/lib/data/repositories/preferences/preferences_mock_impl.dart', 'repo_id': 'ovavue', 'token_count': 136} |
import '../entities/budget_metadata_value_entity.dart';
import '../entities/create_budget_metadata_data.dart';
import '../entities/reference_entity.dart';
import '../entities/update_budget_metadata_data.dart';
abstract class BudgetMetadataRepository {
Future<String> create(String userId, CreateBudgetMetadataData metadata);
Future<bool> update(String userId, UpdateBudgetMetadataData metadata);
Stream<BudgetMetadataValueEntityList> fetchAll(String userId);
Stream<BudgetMetadataValueEntityList> fetchAllByPlan({
required String userId,
required String planId,
});
Stream<List<ReferenceEntity>> fetchPlansByMetadata({
required String userId,
required String metadataId,
});
Future<bool> addMetadataToPlan({
required String userId,
required ReferenceEntity plan,
required ReferenceEntity metadata,
});
Future<bool> removeMetadataFromPlan({
required String userId,
required ReferenceEntity plan,
required ReferenceEntity metadata,
});
}
| ovavue/lib/domain/repositories/budget_metadata.dart/0 | {'file_path': 'ovavue/lib/domain/repositories/budget_metadata.dart', 'repo_id': 'ovavue', 'token_count': 299} |
import '../analytics/analytics.dart';
import '../analytics/analytics_event.dart';
import '../repositories/budgets.dart';
class DeleteBudgetUseCase {
const DeleteBudgetUseCase({
required BudgetsRepository budgets,
required Analytics analytics,
}) : _budgets = budgets,
_analytics = analytics;
final BudgetsRepository _budgets;
final Analytics _analytics;
Future<bool> call({
required String id,
required String path,
}) {
_analytics.log(AnalyticsEvent.deleteBudget(path)).ignore();
return _budgets.delete((id: id, path: path));
}
}
| ovavue/lib/domain/use_cases/delete_budget_use_case.dart/0 | {'file_path': 'ovavue/lib/domain/use_cases/delete_budget_use_case.dart', 'repo_id': 'ovavue', 'token_count': 202} |
import '../analytics/analytics.dart';
import '../analytics/analytics_event.dart';
import '../entities/update_budget_category_data.dart';
import '../repositories/budget_categories.dart';
class UpdateBudgetCategoryUseCase {
const UpdateBudgetCategoryUseCase({
required BudgetCategoriesRepository categories,
required Analytics analytics,
}) : _categories = categories,
_analytics = analytics;
final BudgetCategoriesRepository _categories;
final Analytics _analytics;
Future<bool> call(UpdateBudgetCategoryData category) {
_analytics.log(AnalyticsEvent.updateBudgetCategory(category.path)).ignore();
return _categories.update(category);
}
}
| ovavue/lib/domain/use_cases/update_budget_category_use_case.dart/0 | {'file_path': 'ovavue/lib/domain/use_cases/update_budget_category_use_case.dart', 'repo_id': 'ovavue', 'token_count': 207} |
import 'package:equatable/equatable.dart';
import 'package:ovavue/domain.dart';
import '../utils.dart';
class BudgetAllocationViewModel with EquatableMixin {
const BudgetAllocationViewModel({
required this.id,
required this.path,
required this.amount,
required this.createdAt,
required this.updatedAt,
});
final String id;
final String path;
final Money amount;
final DateTime createdAt;
final DateTime? updatedAt;
@override
List<Object?> get props => <Object?>[id, path, amount, createdAt, updatedAt];
}
extension BudgetAllocationViewModelExtension on BudgetAllocationEntity {
BudgetAllocationViewModel toViewModel() => BudgetAllocationViewModel(
id: id,
path: path,
amount: Money(amount),
createdAt: createdAt,
updatedAt: updatedAt,
);
}
| ovavue/lib/presentation/models/budget_allocation_view_model.dart/0 | {'file_path': 'ovavue/lib/presentation/models/budget_allocation_view_model.dart', 'repo_id': 'ovavue', 'token_count': 289} |
import '../../../models.dart';
import '../../../utils.dart';
typedef BudgetCategoryPlanViewModel = (BudgetPlanViewModel, Money?);
extension BudgetCategoryPlanViewModelExtension on BudgetPlanViewModel {
BudgetCategoryPlanViewModel toViewModel(Money? allocation) => (this, allocation);
}
| ovavue/lib/presentation/screens/budget_categories/providers/models.dart/0 | {'file_path': 'ovavue/lib/presentation/screens/budget_categories/providers/models.dart', 'repo_id': 'ovavue', 'token_count': 83} |
export 'widgets/action_button.dart';
export 'widgets/action_button_row.dart';
export 'widgets/amount_ratio_decorated_box.dart';
export 'widgets/amount_ratio_item.dart';
export 'widgets/app_crash_error_view.dart';
export 'widgets/app_icon.dart';
export 'widgets/budget_allocation_entry_form.dart';
export 'widgets/budget_category_avatar.dart';
export 'widgets/budget_category_entry_form.dart';
export 'widgets/budget_category_list_tile.dart';
export 'widgets/budget_duration_text.dart';
export 'widgets/budget_list_tile.dart';
export 'widgets/budget_plan_entry_form.dart';
export 'widgets/budget_plan_list_tile.dart';
export 'widgets/custom_app_bar.dart';
export 'widgets/date_picker_field.dart';
export 'widgets/dialog_page.dart';
export 'widgets/empty_view.dart';
export 'widgets/error_view.dart';
export 'widgets/loading_spinner.dart';
export 'widgets/loading_view.dart';
export 'widgets/primary_button.dart';
export 'widgets/sliver_expandable_group.dart';
export 'widgets/sliver_pinned_title_count_header.dart';
export 'widgets/snackbar/app_snack_bar.dart';
export 'widgets/snackbar/snack_bar_provider.dart';
| ovavue/lib/presentation/widgets.dart/0 | {'file_path': 'ovavue/lib/presentation/widgets.dart', 'repo_id': 'ovavue', 'token_count': 418} |
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import '../constants.dart';
import '../utils.dart';
class DatePickerField extends FormField<DateTime> {
DatePickerField({
super.key,
required super.initialValue,
required this.onChanged,
String? hintText,
String? selectButtonText,
}) : super(
builder: (FormFieldState<DateTime> fieldState) {
final DateTime? date = fieldState.value;
final BuildContext context = fieldState.context;
final ThemeData theme = Theme.of(context);
final MaterialLocalizations materialL10n = MaterialLocalizations.of(context);
hintText ??= materialL10n.dateInputLabel;
return InputDecorator(
decoration: InputDecoration(
hintText: hintText,
prefixIcon: const Icon(AppIcons.date),
),
child: Row(
children: <Widget>[
Expanded(
child: Text(
date != null ? date.format(DateTimeFormat.yearMonthDate) : hintText!,
style: theme.textTheme.bodyLarge,
),
),
const SizedBox(width: 4),
TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
onPressed: () async {
final DateTime? value = await showDatePicker(
context: context,
initialDate: date ?? clock.now(),
firstDate: DateTime(0),
lastDate: DateTime(clock.now().year + 10),
);
fieldState.didChange(value);
},
child: Text(selectButtonText ?? materialL10n.datePickerHelpText),
),
],
),
);
},
);
final ValueChanged<DateTime> onChanged;
@override
FormFieldState<DateTime> createState() => DatePickerState();
}
@visibleForTesting
class DatePickerState extends FormFieldState<DateTime> {
@override
void initState() {
// NOTE: Weird release mode bug on flutter web
setValue(widget.initialValue);
super.initState();
}
@override
void didChange(DateTime? value) {
if (value != null) {
(widget as DatePickerField).onChanged(value);
}
super.didChange(value);
}
}
| ovavue/lib/presentation/widgets/date_picker_field.dart/0 | {'file_path': 'ovavue/lib/presentation/widgets/date_picker_field.dart', 'repo_id': 'ovavue', 'token_count': 1329} |
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:ovavue/domain.dart';
import '../../utils.dart';
void main() {
group('UpdateBudgetAllocationUseCase', () {
final LogAnalytics analytics = LogAnalytics();
final UpdateBudgetAllocationUseCase useCase = UpdateBudgetAllocationUseCase(
allocations: mockRepositories.budgetAllocations,
analytics: analytics,
);
const UpdateBudgetAllocationData dummyData = UpdateBudgetAllocationData(
id: 'id',
path: 'path',
amount: 1,
);
setUpAll(() {
registerFallbackValue(dummyData);
});
tearDown(() {
analytics.reset();
mockRepositories.reset();
});
test('should create a budget allocation', () async {
when(() => mockRepositories.budgetAllocations.update(any())).thenAnswer((_) async => true);
await expectLater(useCase(dummyData), completion(true));
expect(analytics.events, containsOnce(AnalyticsEvent.updateBudgetAllocation('path')));
});
test('should bubble update errors', () {
when(() => mockRepositories.budgetAllocations.update(any())).thenThrow(Exception('an error'));
expect(() => useCase(dummyData), throwsException);
});
});
}
| ovavue/test/domain/use_cases/update_budget_allocation_use_case_test.dart/0 | {'file_path': 'ovavue/test/domain/use_cases/update_budget_allocation_use_case_test.dart', 'repo_id': 'ovavue', 'token_count': 449} |
class Colors {
static const Color black = Color(0x000000);
static const Color white = Color(0xFFFFFF);
static const Color red = Color(0xFF0000);
static const Color green = Color(0x00FF00);
static const Color blue = Color(0x0000FF);
const Colors._();
}
class Color {
final int value;
const Color(this.value);
String toRGB() {
final r = (value >> 16) & 255;
final g = (value >> 8) & 255;
final b = value & 255;
return '$r;$g;$b';
}
}
| oxygen/example/lib/utils/color.dart/0 | {'file_path': 'oxygen/example/lib/utils/color.dart', 'repo_id': 'oxygen', 'token_count': 170} |
part of oxygen;
/// A filter allows a [Query] to be able to filter down entities.
abstract class Filter<T extends Component> {
Filter() : assert(T != Component);
/// Unique identifier.
String get filterId;
Type get type => T;
/// Method for matching an [Entity] against this filter.
bool match(Entity entity);
}
class Has<T extends Component> extends Filter<T> {
@override
String get filterId => 'Has<$T>';
@override
bool match(Entity entity) => entity._componentTypes.contains(T);
}
class HasNot<T extends Component> extends Filter<T> {
@override
String get filterId => 'HasNot<$T>';
@override
bool match(Entity entity) => !entity._componentTypes.contains(T);
}
| oxygen/lib/src/query/filter.dart/0 | {'file_path': 'oxygen/lib/src/query/filter.dart', 'repo_id': 'oxygen', 'token_count': 213} |
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 Android debug
script: .ci/scripts/build_all_packages_app.sh
args: ["apk", "debug"]
- name: build all_packages for Android release
script: .ci/scripts/build_all_packages_app.sh
args: ["apk", "release"]
- name: create all_packages app - legacy version
script: .ci/scripts/create_all_packages_app_legacy.sh
# Output dir; must match the final argument to build_all_packages_app_legacy
# below.
args: ["legacy"]
# Only build legacy in one mode, to minimize extra CI time. Debug is chosen
# somewhat arbitrarily as likely being slightly faster.
- name: build all_packages for Android - legacy version
script: .ci/scripts/build_all_packages_app_legacy.sh
# The final argument here must match the output directory passed to
# create_all_packages_app_legacy above.
args: ["apk", "debug", "legacy"]
| packages/.ci/targets/android_build_all_packages.yaml/0 | {'file_path': 'packages/.ci/targets/android_build_all_packages.yaml', 'repo_id': 'packages', 'token_count': 388} |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: tool unit tests
script: .ci/scripts/plugin_tools_tests.sh
| packages/.ci/targets/repo_tools_tests.yaml/0 | {'file_path': 'packages/.ci/targets/repo_tools_tests.yaml', 'repo_id': 'packages', 'token_count': 77} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/animations/example/android/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/animations/example/android/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:animations/src/modal.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'showModal builds a new route with specified barrier properties',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
builder: (BuildContext context) {
return const _FlutterLogoModal();
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// New route containing _FlutterLogoModal is present.
expect(find.byType(_FlutterLogoModal), findsOneWidget);
final ModalBarrier topModalBarrier = tester.widget<ModalBarrier>(
find.byType(ModalBarrier).at(1),
);
// Verify new route's modal barrier properties are correct.
expect(topModalBarrier.color, Colors.green);
expect(topModalBarrier.barrierSemanticsDismissible, true);
expect(topModalBarrier.semanticsLabel, 'customLabel');
},
);
testWidgets(
'showModal forwards animation',
(WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
builder: (BuildContext context) {
return _FlutterLogoModal(key: key);
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
// Start forwards animation
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
// Opacity duration: Linear transition throughout 300ms
double topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 0.0);
// Halfway through forwards animation.
await tester.pump(const Duration(milliseconds: 150));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 0.5);
// The end of the transition.
await tester.pump(const Duration(milliseconds: 150));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.byType(_FlutterLogoModal), findsOneWidget);
},
);
testWidgets(
'showModal reverse animation',
(WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
builder: (BuildContext context) {
return _FlutterLogoModal(key: key);
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
// Start forwards animation
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byType(_FlutterLogoModal), findsOneWidget);
await tester.tapAt(Offset.zero);
await tester.pump();
// Opacity duration: Linear transition throughout 200ms
double topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 1.0);
// Halfway through forwards animation.
await tester.pump(const Duration(milliseconds: 100));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 0.5);
// The end of the transition.
await tester.pump(const Duration(milliseconds: 100));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.byType(_FlutterLogoModal), findsNothing);
},
);
testWidgets(
'showModal builds a new route with specified barrier properties '
'with default configuration(FadeScaleTransitionConfiguration)',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
builder: (BuildContext context) {
return const _FlutterLogoModal();
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// New route containing _FlutterLogoModal is present.
expect(find.byType(_FlutterLogoModal), findsOneWidget);
final ModalBarrier topModalBarrier = tester.widget<ModalBarrier>(
find.byType(ModalBarrier).at(1),
);
// Verify new route's modal barrier properties are correct.
expect(topModalBarrier.color, Colors.black54);
expect(topModalBarrier.barrierSemanticsDismissible, true);
expect(topModalBarrier.semanticsLabel, 'Dismiss');
},
);
testWidgets(
'showModal forwards animation '
'with default configuration(FadeScaleTransitionConfiguration)',
(WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
builder: (BuildContext context) {
return _FlutterLogoModal(key: key);
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
// Start forwards animation
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
// Opacity duration: First 30% of 150ms, linear transition
double topFadeTransitionOpacity = _getOpacity(key, tester);
double topScale = _getScale(key, tester);
expect(topFadeTransitionOpacity, 0.0);
expect(topScale, 0.80);
// 3/10 * 150ms = 45ms (total opacity animation duration)
// 1/2 * 45ms = ~23ms elapsed for halfway point of opacity
// animation
await tester.pump(const Duration(milliseconds: 23));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, closeTo(0.5, 0.05));
topScale = _getScale(key, tester);
expect(topScale, greaterThan(0.80));
expect(topScale, lessThan(1.0));
// End of opacity animation.
await tester.pump(const Duration(milliseconds: 22));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 1.0);
topScale = _getScale(key, tester);
expect(topScale, greaterThan(0.80));
expect(topScale, lessThan(1.0));
// 100ms into the animation
await tester.pump(const Duration(milliseconds: 55));
topScale = _getScale(key, tester);
expect(topScale, greaterThan(0.80));
expect(topScale, lessThan(1.0));
// Get to the end of the animation
await tester.pump(const Duration(milliseconds: 50));
topScale = _getScale(key, tester);
expect(topScale, 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.byType(_FlutterLogoModal), findsOneWidget);
},
);
testWidgets(
'showModal reverse animation '
'with default configuration(FadeScaleTransitionConfiguration)',
(WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
builder: (BuildContext context) {
return _FlutterLogoModal(key: key);
},
);
},
child: const Icon(Icons.add),
),
);
}),
),
),
);
// Start forwards animation
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byType(_FlutterLogoModal), findsOneWidget);
// Tap on modal barrier to start reverse animation.
await tester.tapAt(Offset.zero);
await tester.pump();
// Opacity duration: Linear transition throughout 75ms
// No scale animations on exit transition.
double topFadeTransitionOpacity = _getOpacity(key, tester);
double topScale = _getScale(key, tester);
expect(topFadeTransitionOpacity, 1.0);
expect(topScale, 1.0);
await tester.pump(const Duration(milliseconds: 25));
topFadeTransitionOpacity = _getOpacity(key, tester);
topScale = _getScale(key, tester);
expect(topFadeTransitionOpacity, closeTo(0.66, 0.05));
expect(topScale, 1.0);
await tester.pump(const Duration(milliseconds: 25));
topFadeTransitionOpacity = _getOpacity(key, tester);
topScale = _getScale(key, tester);
expect(topFadeTransitionOpacity, closeTo(0.33, 0.05));
expect(topScale, 1.0);
// End of opacity animation
await tester.pump(const Duration(milliseconds: 25));
topFadeTransitionOpacity = _getOpacity(key, tester);
expect(topFadeTransitionOpacity, 0.0);
topScale = _getScale(key, tester);
expect(topScale, 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.byType(_FlutterLogoModal), findsNothing);
},
);
testWidgets(
'State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey bottomKey = GlobalKey();
final GlobalKey topKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(builder: (BuildContext context) {
return Center(
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
builder: (BuildContext context) {
return _FlutterLogoModal(
key: topKey,
name: 'top route',
);
},
);
},
child: const Icon(Icons.add),
),
_FlutterLogoModal(
key: bottomKey,
name: 'bottom route',
),
],
),
);
}),
),
),
);
// The bottom route's state should already exist.
final _FlutterLogoModalState bottomState = tester.state(
find.byKey(bottomKey),
);
expect(bottomState.widget.name, 'bottom route');
// Start the enter transition of the modal route.
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
await tester.pump();
// The bottom route's state should be retained at the start of the
// transition.
expect(
tester.state(find.byKey(bottomKey)),
bottomState,
);
// The top route's state should be created.
final _FlutterLogoModalState topState = tester.state(
find.byKey(topKey),
);
expect(topState.widget.name, 'top route');
// Halfway point of forwards animation.
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(bottomKey)),
bottomState,
);
expect(
tester.state(find.byKey(topKey)),
topState,
);
// End the transition and see if top and bottom routes'
// states persist.
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
bottomKey,
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(topKey)),
topState,
);
// Start the reverse animation. Both top and bottom
// routes' states should persist.
await tester.tapAt(Offset.zero);
await tester.pump();
expect(
tester.state(find.byKey(bottomKey)),
bottomState,
);
expect(
tester.state(find.byKey(topKey)),
topState,
);
// Halfway point of the exit transition.
await tester.pump(const Duration(milliseconds: 100));
expect(
tester.state(find.byKey(bottomKey)),
bottomState,
);
expect(
tester.state(find.byKey(topKey)),
topState,
);
// End the exit transition. The bottom route's state should
// persist, whereas the top route's state should no longer
// be present.
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(bottomKey)),
bottomState,
);
expect(find.byKey(topKey), findsNothing);
},
);
testWidgets(
'showModal builds a new route with specified route settings',
(WidgetTester tester) async {
const RouteSettings routeSettings = RouteSettings(
name: 'route-name',
arguments: 'arguments',
);
final Widget button = Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
routeSettings: routeSettings,
builder: (BuildContext context) {
return const _FlutterLogoModal();
},
);
},
child: const Icon(Icons.add),
),
);
});
await tester.pumpWidget(_boilerplate(button));
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// New route containing _FlutterLogoModal is present.
expect(find.byType(_FlutterLogoModal), findsOneWidget);
// Expect the last route pushed to the navigator to contain RouteSettings
// equal to the RouteSettings passed to showModal
final ModalRoute<dynamic> modalRoute = ModalRoute.of(
tester.element(find.byType(_FlutterLogoModal)),
)!;
expect(modalRoute.settings, routeSettings);
},
);
testWidgets(
'showModal builds a new route with specified image filter',
(WidgetTester tester) async {
final ui.ImageFilter filter = ui.ImageFilter.blur(sigmaX: 1, sigmaY: 1);
final Widget button = Builder(builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
showModal<void>(
context: context,
configuration: _TestModalConfiguration(),
filter: filter,
builder: (BuildContext context) {
return const _FlutterLogoModal();
},
);
},
child: const Icon(Icons.add),
),
);
});
await tester.pumpWidget(_boilerplate(button));
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// New route containing _FlutterLogoModal is present.
expect(find.byType(_FlutterLogoModal), findsOneWidget);
final BackdropFilter backdropFilter = tester.widget<BackdropFilter>(
find.byType(BackdropFilter),
);
// Verify new route's backdrop filter has been applied
expect(backdropFilter.filter, filter);
},
);
}
Widget _boilerplate(Widget child) => MaterialApp(home: Scaffold(body: child));
double _getOpacity(GlobalKey key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(key),
matching: find.byType(FadeTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final FadeTransition transition = widget as FadeTransition;
return a * transition.opacity.value;
});
}
double _getScale(GlobalKey key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(key),
matching: find.byType(ScaleTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final ScaleTransition transition = widget as ScaleTransition;
return a * transition.scale.value;
});
}
class _FlutterLogoModal extends StatefulWidget {
const _FlutterLogoModal({
super.key,
this.name,
});
final String? name;
@override
_FlutterLogoModalState createState() => _FlutterLogoModalState();
}
class _FlutterLogoModalState extends State<_FlutterLogoModal> {
@override
Widget build(BuildContext context) {
return const Center(
child: SizedBox(
width: 250,
height: 250,
child: Material(
child: Center(
child: FlutterLogo(size: 250),
),
),
),
);
}
}
class _TestModalConfiguration extends ModalConfiguration {
_TestModalConfiguration()
: super(
barrierColor: Colors.green,
barrierDismissible: true,
barrierLabel: 'customLabel',
transitionDuration: const Duration(milliseconds: 300),
reverseTransitionDuration: const Duration(milliseconds: 200),
);
@override
Widget transitionBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: animation,
child: child,
);
}
}
| packages/packages/animations/test/modal_test.dart/0 | {'file_path': 'packages/packages/animations/test/modal_test.dart', 'repo_id': 'packages', 'token_count': 9177} |
// 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_example/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Test snackbar', (WidgetTester tester) async {
WidgetsFlutterBinding.ensureInitialized();
await tester.pumpWidget(const CameraApp());
await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsOneWidget);
});
}
| packages/packages/camera/camera/example/test/main_test.dart/0 | {'file_path': 'packages/packages/camera/camera/example/test/main_test.dart', 'repo_id': 'packages', 'token_count': 182} |
// 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} |
// 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} |
// 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/instance_manager.dart';
import 'package:camera_android_camerax/src/metering_point.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'metering_point_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi, TestMeteringPointHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('MeteringPoint', () {
tearDown(() => TestMeteringPointHostApi.setup(null));
test('detached create does not call create on the Java side', () async {
final MockTestMeteringPointHostApi mockApi =
MockTestMeteringPointHostApi();
TestMeteringPointHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
MeteringPoint.detached(
x: 0,
y: 0.3,
size: 4,
instanceManager: instanceManager,
);
verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()),
argThat(isA<int>()), argThat(isA<int>())));
});
test('create calls create on the Java side', () async {
final MockTestMeteringPointHostApi mockApi =
MockTestMeteringPointHostApi();
TestMeteringPointHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const double x = 0.5;
const double y = 0.6;
const double size = 3;
MeteringPoint(
x: x,
y: y,
size: size,
instanceManager: instanceManager,
);
verify(mockApi.create(argThat(isA<int>()), x, y, size));
});
test('getDefaultPointSize returns expected size', () async {
final MockTestMeteringPointHostApi mockApi =
MockTestMeteringPointHostApi();
TestMeteringPointHostApi.setup(mockApi);
const double defaultPointSize = 6;
when(mockApi.getDefaultPointSize()).thenAnswer((_) => defaultPointSize);
expect(
await MeteringPoint.getDefaultPointSize(), equals(defaultPointSize));
verify(mockApi.getDefaultPointSize());
});
});
}
| packages/packages/camera/camera_android_camerax/test/metering_point_test.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/metering_point_test.dart', 'repo_id': 'packages', 'token_count': 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:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/recording.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'recording_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestRecordingHostApi, TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('Recording', () {
tearDown(() => TestRecorderHostApi.setup(null));
test('close calls close on Java side', () async {
final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi();
TestRecordingHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Recording recording =
Recording.detached(instanceManager: instanceManager);
const int recordingId = 0;
when(mockApi.close(recordingId)).thenAnswer((_) {});
instanceManager.addHostCreatedInstance(recording, recordingId,
onCopy: (_) => Recording.detached(instanceManager: instanceManager));
await recording.close();
verify(mockApi.close(recordingId));
});
test('pause calls pause on Java side', () async {
final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi();
TestRecordingHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Recording recording =
Recording.detached(instanceManager: instanceManager);
const int recordingId = 0;
when(mockApi.pause(recordingId)).thenAnswer((_) {});
instanceManager.addHostCreatedInstance(recording, recordingId,
onCopy: (_) => Recording.detached(instanceManager: instanceManager));
await recording.pause();
verify(mockApi.pause(recordingId));
});
test('resume calls resume on Java side', () async {
final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi();
TestRecordingHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Recording recording =
Recording.detached(instanceManager: instanceManager);
const int recordingId = 0;
when(mockApi.resume(recordingId)).thenAnswer((_) {});
instanceManager.addHostCreatedInstance(recording, recordingId,
onCopy: (_) => Recording.detached(instanceManager: instanceManager));
await recording.resume();
verify(mockApi.resume(recordingId));
});
test('stop calls stop on Java side', () async {
final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi();
TestRecordingHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Recording recording =
Recording.detached(instanceManager: instanceManager);
const int recordingId = 0;
when(mockApi.stop(recordingId)).thenAnswer((_) {});
instanceManager.addHostCreatedInstance(recording, recordingId,
onCopy: (_) => Recording.detached(instanceManager: instanceManager));
await recording.stop();
verify(mockApi.stop(recordingId));
});
test('flutterApiCreateTest', () async {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final RecordingFlutterApi flutterApi = RecordingFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(instanceManager.getInstanceWithWeakReference(0), isA<Recording>());
});
});
}
| packages/packages/camera/camera_android_camerax/test/recording_test.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/recording_test.dart', 'repo_id': 'packages', 'token_count': 1477} |
name: camera_example
description: Demonstrates how to use the camera plugin.
publish_to: none
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
dependencies:
camera_avfoundation:
# When depending on this package from a real application you should use:
# camera_avfoundation: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
camera_platform_interface: ^2.7.0
flutter:
sdk: flutter
path_provider: ^2.0.0
video_player: ^2.7.0
dev_dependencies:
build_runner: ^2.1.10
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/camera/camera_avfoundation/example/pubspec.yaml/0 | {'file_path': 'packages/packages/camera/camera_avfoundation/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 289} |
// 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/services.dart';
import 'package:flutter/widgets.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../../camera_platform_interface.dart';
import '../method_channel/method_channel_camera.dart';
/// The interface that implementations of camera must implement.
///
/// Platform implementations should extend this class rather than implement it as `camera`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [CameraPlatform] methods.
abstract class CameraPlatform extends PlatformInterface {
/// Constructs a CameraPlatform.
CameraPlatform() : super(token: _token);
static final Object _token = Object();
static CameraPlatform _instance = MethodChannelCamera();
/// The default instance of [CameraPlatform] to use.
///
/// Defaults to [MethodChannelCamera].
static CameraPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [CameraPlatform] when they register themselves.
static set instance(CameraPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
/// Completes with a list of available cameras.
///
/// This method returns an empty list when no cameras are available.
Future<List<CameraDescription>> availableCameras() {
throw UnimplementedError('availableCameras() is not implemented.');
}
/// Creates an uninitialized camera instance and returns the cameraId.
Future<int> createCamera(
CameraDescription cameraDescription,
ResolutionPreset? resolutionPreset, {
bool enableAudio = false,
}) {
throw UnimplementedError('createCamera() is not implemented.');
}
/// Creates an uninitialized camera instance and returns the cameraId.
///
/// Pass MediaSettings() for defaults
Future<int> createCameraWithSettings(
CameraDescription cameraDescription,
MediaSettings mediaSettings,
) {
return createCamera(
cameraDescription,
mediaSettings.resolutionPreset,
enableAudio: mediaSettings.enableAudio,
);
}
/// Initializes the camera on the device.
///
/// [imageFormatGroup] is used to specify the image formatting used.
/// On Android this defaults to ImageFormat.YUV_420_888 and applies only to the imageStream.
/// On iOS this defaults to kCVPixelFormatType_32BGRA.
/// On Web this parameter is currently not supported.
Future<void> initializeCamera(
int cameraId, {
ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown,
}) {
throw UnimplementedError('initializeCamera() is not implemented.');
}
/// The camera has been initialized.
Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) {
throw UnimplementedError('onCameraInitialized() is not implemented.');
}
/// The camera's resolution has changed.
/// On Web this returns an empty stream.
Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) {
throw UnimplementedError('onResolutionChanged() is not implemented.');
}
/// The camera started to close.
Stream<CameraClosingEvent> onCameraClosing(int cameraId) {
throw UnimplementedError('onCameraClosing() is not implemented.');
}
/// The camera experienced an error.
Stream<CameraErrorEvent> onCameraError(int cameraId) {
throw UnimplementedError('onCameraError() is not implemented.');
}
/// The camera finished recording a video.
Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) {
throw UnimplementedError('onCameraTimeLimitReached() is not implemented.');
}
/// The ui orientation changed.
///
/// Implementations for this:
/// - Should support all 4 orientations.
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
throw UnimplementedError(
'onDeviceOrientationChanged() is not implemented.');
}
/// Locks the capture orientation.
Future<void> lockCaptureOrientation(
int cameraId, DeviceOrientation orientation) {
throw UnimplementedError('lockCaptureOrientation() is not implemented.');
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation(int cameraId) {
throw UnimplementedError('unlockCaptureOrientation() is not implemented.');
}
/// Captures an image and returns the file where it was saved.
Future<XFile> takePicture(int cameraId) {
throw UnimplementedError('takePicture() is not implemented.');
}
/// Prepare the capture session for video recording.
Future<void> prepareForVideoRecording() {
throw UnimplementedError('prepareForVideoRecording() is not implemented.');
}
/// Starts a video recording.
///
/// The length of the recording can be limited by specifying the [maxVideoDuration].
/// By default no maximum duration is specified,
/// meaning the recording will continue until manually stopped.
/// With [maxVideoDuration] set the video is returned in a [VideoRecordedEvent]
/// through the [onVideoRecordedEvent] stream when the set duration is reached.
///
/// This method is deprecated in favour of [startVideoCapturing].
Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) {
throw UnimplementedError('startVideoRecording() is not implemented.');
}
/// Starts a video recording and/or streaming session.
///
/// Please see [VideoCaptureOptions] for documentation on the
/// configuration options.
Future<void> startVideoCapturing(VideoCaptureOptions options) {
return startVideoRecording(options.cameraId,
maxVideoDuration: options.maxDuration);
}
/// Stops the video recording and returns the file where it was saved.
Future<XFile> stopVideoRecording(int cameraId) {
throw UnimplementedError('stopVideoRecording() is not implemented.');
}
/// Pause video recording.
Future<void> pauseVideoRecording(int cameraId) {
throw UnimplementedError('pauseVideoRecording() is not implemented.');
}
/// Resume video recording after pausing.
Future<void> resumeVideoRecording(int cameraId) {
throw UnimplementedError('resumeVideoRecording() is not implemented.');
}
/// A new streamed frame is available.
///
/// Listening to this stream will start streaming, and canceling will stop.
/// Pausing will throw a [CameraException], as pausing the stream would cause
/// very high memory usage; to temporarily stop receiving frames, cancel, then
/// listen again later.
///
///
// TODO(bmparr): Add options to control streaming settings (e.g.,
// resolution and FPS).
Stream<CameraImageData> onStreamedFrameAvailable(int cameraId,
{CameraImageStreamOptions? options}) {
throw UnimplementedError('onStreamedFrameAvailable() is not implemented.');
}
/// Sets the flash mode for the selected camera.
/// On Web [FlashMode.auto] corresponds to [FlashMode.always].
Future<void> setFlashMode(int cameraId, FlashMode mode) {
throw UnimplementedError('setFlashMode() is not implemented.');
}
/// Sets the exposure mode for taking pictures.
Future<void> setExposureMode(int cameraId, ExposureMode mode) {
throw UnimplementedError('setExposureMode() is not implemented.');
}
/// Sets the exposure point for automatically determining the exposure values.
///
/// Supplying `null` for the [point] argument will result in resetting to the
/// original exposure point value.
Future<void> setExposurePoint(int cameraId, Point<double>? point) {
throw UnimplementedError('setExposurePoint() is not implemented.');
}
/// Gets the minimum supported exposure offset for the selected camera in EV units.
Future<double> getMinExposureOffset(int cameraId) {
throw UnimplementedError('getMinExposureOffset() is not implemented.');
}
/// Gets the maximum supported exposure offset for the selected camera in EV units.
Future<double> getMaxExposureOffset(int cameraId) {
throw UnimplementedError('getMaxExposureOffset() is not implemented.');
}
/// Gets the supported step size for exposure offset for the selected camera in EV units.
///
/// Returns 0 when the camera supports using a free value without stepping.
Future<double> getExposureOffsetStepSize(int cameraId) {
throw UnimplementedError('getMinExposureOffset() is not implemented.');
}
/// Sets the exposure offset for the selected camera.
///
/// The supplied [offset] value should be in EV units. 1 EV unit represents a
/// doubling in brightness. It should be between the minimum and maximum offsets
/// obtained through `getMinExposureOffset` and `getMaxExposureOffset` respectively.
/// Throws a `CameraException` when an illegal offset is supplied.
///
/// When the supplied [offset] value does not align with the step size obtained
/// through `getExposureStepSize`, it will automatically be rounded to the nearest step.
///
/// Returns the (rounded) offset value that was set.
Future<double> setExposureOffset(int cameraId, double offset) {
throw UnimplementedError('setExposureOffset() is not implemented.');
}
/// Sets the focus mode for taking pictures.
Future<void> setFocusMode(int cameraId, FocusMode mode) {
throw UnimplementedError('setFocusMode() is not implemented.');
}
/// Sets the focus point for automatically determining the focus values.
///
/// Supplying `null` for the [point] argument will result in resetting to the
/// original focus point value.
Future<void> setFocusPoint(int cameraId, Point<double>? point) {
throw UnimplementedError('setFocusPoint() is not implemented.');
}
/// Gets the maximum supported zoom level for the selected camera.
Future<double> getMaxZoomLevel(int cameraId) {
throw UnimplementedError('getMaxZoomLevel() is not implemented.');
}
/// Gets the minimum supported zoom level for the selected camera.
Future<double> getMinZoomLevel(int cameraId) {
throw UnimplementedError('getMinZoomLevel() is not implemented.');
}
/// Set the zoom level for the selected camera.
///
/// The supplied [zoom] value should be between the minimum and the maximum supported
/// zoom level returned by `getMinZoomLevel` and `getMaxZoomLevel`. Throws a `CameraException`
/// when an illegal zoom level is supplied.
Future<void> setZoomLevel(int cameraId, double zoom) {
throw UnimplementedError('setZoomLevel() is not implemented.');
}
/// Pause the active preview on the current frame for the selected camera.
Future<void> pausePreview(int cameraId) {
throw UnimplementedError('pausePreview() is not implemented.');
}
/// Resume the paused preview for the selected camera.
Future<void> resumePreview(int cameraId) {
throw UnimplementedError('pausePreview() is not implemented.');
}
/// Sets the active camera while recording.
Future<void> setDescriptionWhileRecording(CameraDescription description) {
throw UnimplementedError(
'setDescriptionWhileRecording() is not implemented.');
}
/// Returns a widget showing a live camera preview.
Widget buildPreview(int cameraId) {
throw UnimplementedError('buildView() has not been implemented.');
}
/// Releases the resources of this camera.
Future<void> dispose(int cameraId) {
throw UnimplementedError('dispose() is not implemented.');
}
/// Sets the output image file format for the selected camera.
///
// TODO(bmparr): This is only supported on iOS. See
// https://github.com/flutter/flutter/issues/139588
Future<void> setImageFileFormat(int cameraId, ImageFileFormat format) {
throw UnimplementedError('setImageFileFormat() is not implemented.');
}
}
| packages/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart/0 | {'file_path': 'packages/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart', 'repo_id': 'packages', 'token_count': 3299} |
// 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_platform_interface/camera_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CameraInitializedEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(event.cameraId, 1);
expect(event.previewWidth, 1024);
expect(event.previewHeight, 640);
expect(event.exposureMode, ExposureMode.auto);
expect(event.focusMode, FocusMode.auto);
expect(event.exposurePointSupported, true);
expect(event.focusPointSupported, true);
});
test('fromJson should initialize all properties', () {
final CameraInitializedEvent event =
CameraInitializedEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
'previewWidth': 1024.0,
'previewHeight': 640.0,
'exposureMode': 'auto',
'exposurePointSupported': true,
'focusMode': 'auto',
'focusPointSupported': true,
});
expect(event.cameraId, 1);
expect(event.previewWidth, 1024);
expect(event.previewHeight, 640);
expect(event.exposureMode, ExposureMode.auto);
expect(event.exposurePointSupported, true);
expect(event.focusMode, FocusMode.auto);
expect(event.focusPointSupported, true);
});
test('toJson should return a map with all fields', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 7);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['previewWidth'], 1024);
expect(jsonMap['previewHeight'], 640);
expect(jsonMap['exposureMode'], 'auto');
expect(jsonMap['exposurePointSupported'], true);
expect(jsonMap['focusMode'], 'auto');
expect(jsonMap['focusPointSupported'], true);
});
test('equals should return true if objects are the same', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
2, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if previewWidth is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 2048, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if previewHeight is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 980, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if exposureMode is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.locked, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if exposurePointSupported is different',
() {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, false, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if focusMode is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.locked, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if focusPointSupported is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, false);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
final int expectedHashCode = Object.hash(
event.cameraId.hashCode,
event.previewWidth,
event.previewHeight,
event.exposureMode,
event.exposurePointSupported,
event.focusMode,
event.focusPointSupported);
expect(event.hashCode, expectedHashCode);
});
});
group('CameraResolutionChangesEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
expect(event.cameraId, 1);
expect(event.captureWidth, 1024);
expect(event.captureHeight, 640);
});
test('fromJson should initialize all properties', () {
final CameraResolutionChangedEvent event =
CameraResolutionChangedEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
'captureWidth': 1024.0,
'captureHeight': 640.0,
});
expect(event.cameraId, 1);
expect(event.captureWidth, 1024);
expect(event.captureHeight, 640);
});
test('toJson should return a map with all fields', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 3);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['captureWidth'], 1024);
expect(jsonMap['captureHeight'], 640);
});
test('equals should return true if objects are the same', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 1024, 640);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(2, 1024, 640);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if captureWidth is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 2048, 640);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if captureHeight is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 1024, 980);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
final int expectedHashCode = Object.hash(
event.cameraId.hashCode,
event.captureWidth,
event.captureHeight,
);
expect(event.hashCode, expectedHashCode);
});
});
group('CameraClosingEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraClosingEvent event = CameraClosingEvent(1);
expect(event.cameraId, 1);
});
test('fromJson should initialize all properties', () {
final CameraClosingEvent event =
CameraClosingEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
});
expect(event.cameraId, 1);
});
test('toJson should return a map with all fields', () {
const CameraClosingEvent event = CameraClosingEvent(1);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 1);
expect(jsonMap['cameraId'], 1);
});
test('equals should return true if objects are the same', () {
const CameraClosingEvent firstEvent = CameraClosingEvent(1);
const CameraClosingEvent secondEvent = CameraClosingEvent(1);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraClosingEvent firstEvent = CameraClosingEvent(1);
const CameraClosingEvent secondEvent = CameraClosingEvent(2);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraClosingEvent event = CameraClosingEvent(1);
final int expectedHashCode = event.cameraId.hashCode;
expect(event.hashCode, expectedHashCode);
});
});
group('CameraErrorEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
expect(event.cameraId, 1);
expect(event.description, 'Error');
});
test('fromJson should initialize all properties', () {
final CameraErrorEvent event = CameraErrorEvent.fromJson(
const <String, dynamic>{'cameraId': 1, 'description': 'Error'});
expect(event.cameraId, 1);
expect(event.description, 'Error');
});
test('toJson should return a map with all fields', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 2);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['description'], 'Error');
});
test('equals should return true if objects are the same', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Error');
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(2, 'Error');
expect(firstEvent == secondEvent, false);
});
test('equals should return false if description is different', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Ooops');
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
final int expectedHashCode =
Object.hash(event.cameraId.hashCode, event.description);
expect(event.hashCode, expectedHashCode);
});
});
}
| packages/packages/camera/camera_platform_interface/test/events/camera_event_test.dart/0 | {'file_path': 'packages/packages/camera/camera_platform_interface/test/events/camera_event_test.dart', 'repo_id': 'packages', 'token_count': 4317} |
name: camera_web_integration_tests
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
camera_platform_interface: ^2.1.0
camera_web:
path: ../
flutter:
sdk: flutter
dev_dependencies:
async: ^2.5.0
cross_file: ^0.3.1
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mocktail: 0.3.0
| packages/packages/camera/camera_web/example/pubspec.yaml/0 | {'file_path': 'packages/packages/camera/camera_web/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 173} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:web/helpers.dart';
/// Create anchor element with download attribute
HTMLAnchorElement createAnchorElement(String href, String? suggestedName) =>
(document.createElement('a') as HTMLAnchorElement)
..href = href
..download = suggestedName ?? 'download';
/// Add an element to a container and click it
void addElementToContainerAndClick(Element container, HTMLElement element) {
// Add the element and click it
// All previous elements will be removed before adding the new one
container.appendChild(element);
element.click();
}
/// Initializes a DOM container where elements can be injected.
Element ensureInitialized(String id) {
Element? target = querySelector('#$id');
if (target == null) {
final Element targetElement = document.createElement('flt-x-file')..id = id;
querySelector('body')!.appendChild(targetElement);
target = targetElement;
}
return target;
}
/// Determines if the browser is Safari from its vendor string.
/// (This is the same check used in flutter/engine)
bool isSafari() {
return window.navigator.vendor == 'Apple Computer, Inc.';
}
| packages/packages/cross_file/lib/src/web_helpers/web_helpers.dart/0 | {'file_path': 'packages/packages/cross_file/lib/src/web_helpers/web_helpers.dart', 'repo_id': 'packages', 'token_count': 366} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'staggered_layout_example.dart';
import 'wrap_layout_example.dart';
void main() {
runApp(const MyApp());
}
/// Main example
class MyApp extends StatelessWidget {
/// Main example constructor.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
/// The home page
class MyHomePage extends StatelessWidget {
/// The home page constructor.
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Demo App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => const WrapExample(),
),
),
child: const Text('Wrap Demo'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => const StaggeredExample(),
),
),
child: const Text('Staggered Demo'),
),
],
),
),
);
}
}
| packages/packages/dynamic_layouts/example/lib/main.dart/0 | {'file_path': 'packages/packages/dynamic_layouts/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 800} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'render_dynamic_grid.dart';
import 'staggered_layout.dart';
import 'wrap_layout.dart';
/// A scrollable grid of widgets, capable of dynamically positioning tiles based
/// on different aspects of the children's size when laid out with loose
/// constraints.
///
/// Three [SliverGridDelegate]s support wrapping or staggering the dynamically
/// sized children of the grid. Staggering children can use
/// [SliverGridDelegateWithFixedCrossAxisCount] or
/// [SliverGridDelegateWithMaxCrossAxisExtent], while wrapping uses its own
/// [SliverGridDelegateWithWrapping].
///
/// {@macro dynamicLayouts.garbageCollection}
///
/// The following example shows how to use the [DynamicGridView.wrap]
/// constructor.
///
/// ```dart
/// DynamicGridView.wrap(
/// mainAxisSpacing: 10,
/// crossAxisSpacing: 20,
/// children: [
/// Container(
/// height: 100,
/// width: 200,
/// color: Colors.amberAccent[100],
/// child: const Center(child: Text('Item 1')
/// ),
/// ),
/// Container(
/// height: 50,
/// width: 70,
/// color: Colors.blue[100],
/// child: const Center(child: Text('Item 2'),
/// ),
/// ),
/// Container(
/// height: 82,
/// width: 300,
/// color: Colors.pink[100],
/// child: const Center(child: Text('Item 3'),
/// ),
/// ),
/// Container(
/// color: Colors.green[100],
/// child: const Center(child: Text('Item 3'),
/// ),
/// ),
/// ],
/// ),
/// ```
///
/// This sample code shows how to use the [DynamicGridView.staggered]
/// constructor with a [maxCrossAxisExtent]:
///
/// ```dart
/// DynamicGridView.staggered(
/// maxCrossAxisExtent: 100,
/// crossAxisSpacing: 2,
/// mainAxisSpacing: 2,
/// children: List.generate(
/// 50,
/// (int index) => Container(
/// height: index % 3 * 50 + 20,
/// color: Colors.amber[index % 9 * 100],
/// child: Center(child: Text("Index $index")),
/// ),
/// ),
/// );
/// ```
class DynamicGridView extends GridView {
/// Creates a scrollable, 2D array of widgets with a custom
/// [SliverGridDelegate].
DynamicGridView({
super.key,
super.scrollDirection,
super.reverse,
required super.gridDelegate,
// This creates a SliverChildListDelegate in the super class.
super.children = const <Widget>[],
});
/// Creates a scrollable, 2D array of widgets that are created on demand.
DynamicGridView.builder({
super.key,
super.scrollDirection,
super.reverse,
required super.gridDelegate,
// This creates a SliverChildBuilderDelegate in the super class.
required super.itemBuilder,
super.itemCount,
}) : super.builder();
/// Creates a scrollable, 2D array of widgets with tiles where each tile can
/// have its own size.
///
/// Uses a [SliverGridDelegateWithWrapping] as the [gridDelegate].
///
/// The following example shows how to use the DynamicGridView.wrap constructor.
///
/// ```dart
/// DynamicGridView.wrap(
/// mainAxisSpacing: 10,
/// crossAxisSpacing: 20,
/// children: [
/// Container(
/// height: 100,
/// width: 200,
/// color: Colors.amberAccent[100],
/// child: const Center(child: Text('Item 1')
/// ),
/// ),
/// Container(
/// height: 50,
/// width: 70,
/// color: Colors.blue[100],
/// child: const Center(child: Text('Item 2'),
/// ),
/// ),
/// Container(
/// height: 82,
/// width: 300,
/// color: Colors.pink[100],
/// child: const Center(child: Text('Item 3'),
/// ),
/// ),
/// Container(
/// color: Colors.green[100],
/// child: const Center(child: Text('Item 3'),
/// ),
/// ),
/// ],
/// ),
/// ```
///
/// See also:
///
/// * [SliverGridDelegateWithWrapping] to see a more detailed explanation of
/// how the wrapping works.
DynamicGridView.wrap({
super.key,
super.scrollDirection,
super.reverse,
double mainAxisSpacing = 0.0,
double crossAxisSpacing = 0.0,
double childCrossAxisExtent = double.infinity,
double childMainAxisExtent = double.infinity,
super.children = const <Widget>[],
}) : super(
gridDelegate: SliverGridDelegateWithWrapping(
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
childCrossAxisExtent: childCrossAxisExtent,
childMainAxisExtent: childMainAxisExtent,
),
);
/// Creates a scrollable, 2D array of widgets where each tile's main axis
/// extent will be determined by the child's corresponding finite size and
/// the cross axis extent will be fixed, generating a staggered layout.
///
/// Either a [crossAxisCount] or a [maxCrossAxisExtent] must be provided.
/// The constructor will then use a
/// [DynamicSliverGridDelegateWithFixedCrossAxisCount] or a
/// [DynamicSliverGridDelegateWithMaxCrossAxisExtent] as its [gridDelegate],
/// respectively.
///
/// This sample code shows how to use the constructor with a
/// [maxCrossAxisExtent] and a simple layout:
///
/// ```dart
/// DynamicGridView.staggered(
/// maxCrossAxisExtent: 100,
/// crossAxisSpacing: 2,
/// mainAxisSpacing: 2,
/// children: List.generate(
/// 50,
/// (int index) => Container(
/// height: index % 3 * 50 + 20,
/// color: Colors.amber[index % 9 * 100],
/// child: Center(child: Text("Index $index")),
/// ),
/// ),
/// );
/// ```
DynamicGridView.staggered({
super.key,
super.scrollDirection,
super.reverse,
int? crossAxisCount,
double? maxCrossAxisExtent,
double mainAxisSpacing = 0.0,
double crossAxisSpacing = 0.0,
super.children = const <Widget>[],
}) : assert(crossAxisCount != null || maxCrossAxisExtent != null),
assert(crossAxisCount == null || maxCrossAxisExtent == null),
super(
gridDelegate: crossAxisCount != null
? DynamicSliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
)
: DynamicSliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: maxCrossAxisExtent!,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
),
);
@override
Widget buildChildLayout(BuildContext context) {
return DynamicSliverGrid(
delegate: childrenDelegate,
gridDelegate: gridDelegate,
);
}
}
/// A sliver that places multiple box children in a two dimensional arrangement.
class DynamicSliverGrid extends SliverMultiBoxAdaptorWidget {
/// Creates a sliver that places multiple box children in a two dimensional
/// arrangement.
const DynamicSliverGrid({
super.key,
required super.delegate,
required this.gridDelegate,
});
/// The delegate that manages the size and position of the children.
final SliverGridDelegate gridDelegate;
@override
RenderDynamicSliverGrid createRenderObject(BuildContext context) {
final SliverMultiBoxAdaptorElement element =
context as SliverMultiBoxAdaptorElement;
return RenderDynamicSliverGrid(
childManager: element, gridDelegate: gridDelegate);
}
@override
void updateRenderObject(
BuildContext context,
RenderDynamicSliverGrid renderObject,
) {
renderObject.gridDelegate = gridDelegate;
}
}
| packages/packages/dynamic_layouts/lib/src/dynamic_grid.dart/0 | {'file_path': 'packages/packages/dynamic_layouts/lib/src/dynamic_grid.dart', 'repo_id': 'packages', 'token_count': 3148} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
/// Screen that shows an example of openFile
class OpenTextPage extends StatelessWidget {
/// Default Constructor
const OpenTextPage({super.key});
Future<void> _openTextFile(BuildContext context) async {
const XTypeGroup typeGroup = XTypeGroup(
label: 'text',
extensions: <String>['txt', 'json'],
);
// This demonstrates using an initial directory for the prompt, which should
// only be done in cases where the application can likely predict where the
// file would be. In most cases, this parameter should not be provided.
final String? initialDirectory =
kIsWeb ? null : (await getApplicationDocumentsDirectory()).path;
final XFile? file = await openFile(
acceptedTypeGroups: <XTypeGroup>[typeGroup],
initialDirectory: initialDirectory,
);
if (file == null) {
// Operation was canceled by the user.
return;
}
final String fileName = file.name;
final String fileContent = await file.readAsString();
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => TextDisplay(fileName, fileContent),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open a text file'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
child: const Text('Press to open a text file (json, txt)'),
onPressed: () => _openTextFile(context),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog
class TextDisplay extends StatelessWidget {
/// Default Constructor
const TextDisplay(this.fileName, this.fileContent, {super.key});
/// File's name
final String fileName;
/// File to display
final String fileContent;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(fileContent),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| packages/packages/file_selector/file_selector/example/lib/open_text_page.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector/example/lib/open_text_page.dart', 'repo_id': 'packages', 'token_count': 1081} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:file_selector_android/src/file_selector_android.dart';
import 'package:file_selector_android/src/file_selector_api.g.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'file_selector_android_test.mocks.dart';
@GenerateMocks(<Type>[FileSelectorApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FileSelectorAndroid plugin;
late MockFileSelectorApi mockApi;
setUp(() {
mockApi = MockFileSelectorApi();
plugin = FileSelectorAndroid(api: mockApi);
});
test('registered instance', () {
FileSelectorAndroid.registerWith();
expect(FileSelectorPlatform.instance, isA<FileSelectorAndroid>());
});
group('openFile', () {
test('passes the accepted type groups correctly', () async {
when(
mockApi.openFile(
'some/path/',
argThat(
isA<FileTypes>().having(
(FileTypes types) => types.mimeTypes,
'mimeTypes',
<String>['text/plain', 'image/jpg'],
).having(
(FileTypes types) => types.extensions,
'extensions',
<String>['txt', 'jpg'],
),
),
),
).thenAnswer(
(_) => Future<FileResponse?>.value(
FileResponse(
path: 'some/path.txt',
size: 30,
bytes: Uint8List(0),
name: 'name',
mimeType: 'text/plain',
),
),
);
const XTypeGroup group = XTypeGroup(
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup group2 = XTypeGroup(
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
final XFile? file = await plugin.openFile(
acceptedTypeGroups: <XTypeGroup>[group, group2],
initialDirectory: 'some/path/',
);
expect(file?.path, 'some/path.txt');
expect(file?.mimeType, 'text/plain');
expect(await file?.length(), 30);
expect(await file?.readAsBytes(), Uint8List(0));
});
});
group('openFiles', () {
test('passes the accepted type groups correctly', () async {
when(
mockApi.openFiles(
'some/path/',
argThat(
isA<FileTypes>().having(
(FileTypes types) => types.mimeTypes,
'mimeTypes',
<String>['text/plain', 'image/jpg'],
).having(
(FileTypes types) => types.extensions,
'extensions',
<String>['txt', 'jpg'],
),
),
),
).thenAnswer(
(_) => Future<List<FileResponse>>.value(
<FileResponse>[
FileResponse(
path: 'some/path.txt',
size: 30,
bytes: Uint8List(0),
name: 'name',
mimeType: 'text/plain',
),
FileResponse(
path: 'other/dir.jpg',
size: 40,
bytes: Uint8List(0),
mimeType: 'image/jpg',
),
],
),
);
const XTypeGroup group = XTypeGroup(
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup group2 = XTypeGroup(
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
final List<XFile> files = await plugin.openFiles(
acceptedTypeGroups: <XTypeGroup>[group, group2],
initialDirectory: 'some/path/',
);
expect(files[0].path, 'some/path.txt');
expect(files[0].mimeType, 'text/plain');
expect(await files[0].length(), 30);
expect(await files[0].readAsBytes(), Uint8List(0));
expect(files[1].path, 'other/dir.jpg');
expect(files[1].mimeType, 'image/jpg');
expect(await files[1].length(), 40);
expect(await files[1].readAsBytes(), Uint8List(0));
});
});
test('getDirectoryPath', () async {
when(mockApi.getDirectoryPath('some/path'))
.thenAnswer((_) => Future<String?>.value('some/path/chosen/'));
final String? path = await plugin.getDirectoryPath(
initialDirectory: 'some/path',
);
expect(path, 'some/path/chosen/');
});
}
| packages/packages/file_selector/file_selector_android/test/file_selector_android_test.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_android/test/file_selector_android_test.dart', 'repo_id': 'packages', 'token_count': 2169} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../../file_selector_platform_interface.dart';
import '../method_channel/method_channel_file_selector.dart';
/// The interface that implementations of file_selector must implement.
///
/// Platform implementations should extend this class rather than implement it as `file_selector`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [FileSelectorPlatform] methods.
abstract class FileSelectorPlatform extends PlatformInterface {
/// Constructs a FileSelectorPlatform.
FileSelectorPlatform() : super(token: _token);
static final Object _token = Object();
static FileSelectorPlatform _instance = MethodChannelFileSelector();
/// The default instance of [FileSelectorPlatform] to use.
///
/// Defaults to [MethodChannelFileSelector].
static FileSelectorPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [FileSelectorPlatform] when they register themselves.
static set instance(FileSelectorPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
/// Opens a file dialog for loading files and returns a file path.
///
/// Returns `null` if the user cancels the operation.
// TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to
// duplicate this to add a parameter.
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('openFile() has not been implemented.');
}
/// Opens a file dialog for loading files and returns a list of file paths.
///
/// Returns an empty list if the user cancels the operation.
// TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to
// duplicate this to add a parameter.
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('openFiles() has not been implemented.');
}
/// Opens a file dialog for saving files and returns a file path at which to
/// save.
///
/// Returns `null` if the user cancels the operation.
// TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to
// duplicate this to add a parameter.
@Deprecated('Use getSaveLocation instead')
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) {
throw UnimplementedError('getSavePath() has not been implemented.');
}
/// Opens a file dialog for saving files and returns a file location at which
/// to save.
///
/// Returns `null` if the user cancels the operation.
Future<FileSaveLocation?> getSaveLocation({
List<XTypeGroup>? acceptedTypeGroups,
SaveDialogOptions options = const SaveDialogOptions(),
}) async {
final String? path = await getSavePath(
acceptedTypeGroups: acceptedTypeGroups,
initialDirectory: options.initialDirectory,
suggestedName: options.suggestedName,
confirmButtonText: options.confirmButtonText,
);
return path == null ? null : FileSaveLocation(path);
}
/// Opens a file dialog for loading directories and returns a directory path.
///
/// Returns `null` if the user cancels the operation.
// TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to
// duplicate this to add a parameter.
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('getDirectoryPath() has not been implemented.');
}
/// Opens a file dialog for loading directories and returns multiple directory
/// paths.
///
/// Returns an empty list if the user cancels the operation.
// TODO(stuartmorgan): Switch to FileDialogOptions if we ever need to
// duplicate this to add a parameter.
Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('getDirectoryPaths() has not been implemented.');
}
}
| packages/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart', 'repo_id': 'packages', 'token_count': 1279} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:file_selector_web/file_selector_web.dart';
import 'package:file_selector_web/src/dom_helper.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/helpers.dart';
void main() {
group('FileSelectorWeb', () {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('openFile', () {
testWidgets('works', (WidgetTester _) async {
final XFile mockFile = createXFile('1001', 'identity.png');
final MockDomHelper mockDomHelper = MockDomHelper(
files: <XFile>[mockFile],
expectAccept: '.jpg,.jpeg,image/png,image/*');
final FileSelectorWeb plugin =
FileSelectorWeb(domHelper: mockDomHelper);
const XTypeGroup typeGroup = XTypeGroup(
label: 'images',
extensions: <String>['jpg', 'jpeg'],
mimeTypes: <String>['image/png'],
webWildCards: <String>['image/*'],
);
final XFile? file =
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
expect(file, isNotNull);
expect(file!.name, mockFile.name);
expect(await file.length(), 4);
expect(await file.readAsString(), '1001');
expect(await file.lastModified(), isNotNull);
});
testWidgets('returns null when getFiles returns an empty list',
(WidgetTester _) async {
// Simulate returning an empty list of files from the DomHelper...
final MockDomHelper mockDomHelper = MockDomHelper(
files: <XFile>[],
);
final FileSelectorWeb plugin =
FileSelectorWeb(domHelper: mockDomHelper);
final XFile? file = await plugin.openFile();
expect(file, isNull);
});
});
group('openFiles', () {
testWidgets('works', (WidgetTester _) async {
final XFile mockFile1 = createXFile('123456', 'file1.txt');
final XFile mockFile2 = createXFile('', 'file2.txt');
final MockDomHelper mockDomHelper = MockDomHelper(
files: <XFile>[mockFile1, mockFile2],
expectAccept: '.txt',
expectMultiple: true);
final FileSelectorWeb plugin =
FileSelectorWeb(domHelper: mockDomHelper);
const XTypeGroup typeGroup = XTypeGroup(
label: 'files',
extensions: <String>['.txt'],
);
final List<XFile> files =
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
expect(files.length, 2);
expect(files[0].name, mockFile1.name);
expect(await files[0].length(), 6);
expect(await files[0].readAsString(), '123456');
expect(await files[0].lastModified(), isNotNull);
expect(files[1].name, mockFile2.name);
expect(await files[1].length(), 0);
expect(await files[1].readAsString(), '');
expect(await files[1].lastModified(), isNotNull);
});
});
group('getSavePath', () {
testWidgets('returns non-null', (WidgetTester _) async {
final FileSelectorWeb plugin = FileSelectorWeb();
final Future<String?> savePath = plugin.getSavePath();
expect(await savePath, isNotNull);
});
});
});
}
class MockDomHelper implements DomHelper {
MockDomHelper({
List<XFile> files = const <XFile>[],
String expectAccept = '',
bool expectMultiple = false,
}) : _files = files,
_expectedAccept = expectAccept,
_expectedMultiple = expectMultiple;
final List<XFile> _files;
final String _expectedAccept;
final bool _expectedMultiple;
@override
Future<List<XFile>> getFiles({
String accept = '',
bool multiple = false,
HTMLInputElement? input,
}) {
expect(accept, _expectedAccept,
reason: 'Expected "accept" value does not match.');
expect(multiple, _expectedMultiple,
reason: 'Expected "multiple" value does not match.');
return Future<List<XFile>>.value(_files);
}
}
XFile createXFile(String content, String name) {
final Uint8List data = Uint8List.fromList(content.codeUnits);
return XFile.fromData(data, name: name, lastModified: DateTime.now());
}
| packages/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart', 'repo_id': 'packages', 'token_count': 1792} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
cppOptions: CppOptions(namespace: 'file_selector_windows'),
cppHeaderOut: 'windows/messages.g.h',
cppSourceOut: 'windows/messages.g.cpp',
copyrightHeader: 'pigeons/copyright.txt',
))
class TypeGroup {
TypeGroup(this.label, {required this.extensions});
String label;
// TODO(stuartmorgan): Make the generic type non-nullable once supported.
// https://github.com/flutter/flutter/issues/97848
// The C++ code treats all of it as non-nullable.
List<String?> extensions;
}
class SelectionOptions {
SelectionOptions({
this.allowMultiple = false,
this.selectFolders = false,
this.allowedTypes = const <TypeGroup?>[],
});
bool allowMultiple;
bool selectFolders;
// TODO(stuartmorgan): Make the generic type non-nullable once supported.
// https://github.com/flutter/flutter/issues/97848
// The C++ code treats the values as non-nullable.
List<TypeGroup?> allowedTypes;
}
/// The result from an open or save dialog.
class FileDialogResult {
FileDialogResult({required this.paths, this.typeGroupIndex});
/// The selected paths.
///
/// Empty if the dialog was canceled.
// TODO(stuartmorgan): Make the generic type non-nullable once supported.
// https://github.com/flutter/flutter/issues/97848
// The Dart code treats the values as non-nullable.
List<String?> paths;
/// The type group index (into the list provided in [SelectionOptions]) of
/// the group that was selected when the dialog was confirmed.
///
/// Null if no type groups were provided, or the dialog was canceled.
int? typeGroupIndex;
}
@HostApi(dartHostTestHandler: 'TestFileSelectorApi')
abstract class FileSelectorApi {
FileDialogResult showOpenDialog(
SelectionOptions options,
String? initialDirectory,
String? confirmButtonText,
);
FileDialogResult showSaveDialog(
SelectionOptions options,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
);
}
| packages/packages/file_selector/file_selector_windows/pigeons/messages.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_windows/pigeons/messages.dart', 'repo_id': 'packages', 'token_count': 717} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_image/flutter_image.dart';
/// Demonstrates loading an image for the README.
Image networkImageWithRetry() {
// #docregion NetworkImageWithRetry
const Image avatar = Image(
image: NetworkImageWithRetry('http://example.com/avatars/123.jpg'),
);
// #enddocregion NetworkImageWithRetry
return avatar;
}
| packages/packages/flutter_image/example/lib/readme_excerpts.dart/0 | {'file_path': 'packages/packages/flutter_image/example/lib/readme_excerpts.dart', 'repo_id': 'packages', 'token_count': 161} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
// ignore_for_file: public_member_api_docs
class DropdownMenu<T> extends StatelessWidget {
DropdownMenu({
super.key,
required this.items,
required this.initialValue,
required this.label,
this.labelStyle,
Color? background,
EdgeInsetsGeometry? padding,
Color? menuItemBackground,
EdgeInsetsGeometry? menuItemMargin,
this.onChanged,
}) : assert(
items.isNotEmpty, 'The items map must contain at least one entry'),
background = background ?? Colors.black12,
padding =
padding ?? const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
menuItemBackground = menuItemBackground ?? Colors.white,
menuItemMargin = menuItemMargin ?? const EdgeInsets.only(left: 4);
final Map<String, T> items;
final T initialValue;
final String label;
final TextStyle? labelStyle;
final ValueChanged<T?>? onChanged;
final Color background;
final EdgeInsetsGeometry padding;
final Color menuItemBackground;
final EdgeInsetsGeometry menuItemMargin;
@override
Widget build(BuildContext context) {
return Container(
color: background,
padding: padding,
child: Row(
children: <Widget>[
Text(
label,
style: labelStyle ?? Theme.of(context).textTheme.titleMedium,
),
Container(
color: menuItemBackground,
margin: menuItemMargin,
child: DropdownButton<T>(
isDense: true,
value: initialValue,
items: <DropdownMenuItem<T>>[
for (final String item in items.keys)
DropdownMenuItem<T>(
value: items[item],
child: Container(
padding: const EdgeInsets.only(left: 4),
child: Text(item),
),
),
],
onChanged: (T? value) => onChanged!(value),
),
),
],
),
);
}
}
| packages/packages/flutter_markdown/example/lib/shared/dropdown_menu.dart/0 | {'file_path': 'packages/packages/flutter_markdown/example/lib/shared/dropdown_menu.dart', 'repo_id': 'packages', 'token_count': 980} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Defines which [TextStyle] objects to use for which Markdown elements.
class MarkdownStyleSheet {
/// Creates an explicit mapping of [TextStyle] objects to Markdown elements.
MarkdownStyleSheet({
this.a,
this.p,
this.pPadding,
this.code,
this.h1,
this.h1Padding,
this.h2,
this.h2Padding,
this.h3,
this.h3Padding,
this.h4,
this.h4Padding,
this.h5,
this.h5Padding,
this.h6,
this.h6Padding,
this.em,
this.strong,
this.del,
this.blockquote,
this.img,
this.checkbox,
this.blockSpacing,
this.listIndent,
this.listBullet,
this.listBulletPadding,
this.tableHead,
this.tableBody,
this.tableHeadAlign,
this.tableBorder,
this.tableColumnWidth,
this.tableCellsPadding,
this.tableCellsDecoration,
this.tableVerticalAlignment = TableCellVerticalAlignment.middle,
this.blockquotePadding,
this.blockquoteDecoration,
this.codeblockPadding,
this.codeblockDecoration,
this.horizontalRuleDecoration,
this.textAlign = WrapAlignment.start,
this.h1Align = WrapAlignment.start,
this.h2Align = WrapAlignment.start,
this.h3Align = WrapAlignment.start,
this.h4Align = WrapAlignment.start,
this.h5Align = WrapAlignment.start,
this.h6Align = WrapAlignment.start,
this.unorderedListAlign = WrapAlignment.start,
this.orderedListAlign = WrapAlignment.start,
this.blockquoteAlign = WrapAlignment.start,
this.codeblockAlign = WrapAlignment.start,
this.textScaleFactor,
}) : _styles = <String, TextStyle?>{
'a': a,
'p': p,
'li': p,
'code': code,
'pre': p,
'h1': h1,
'h2': h2,
'h3': h3,
'h4': h4,
'h5': h5,
'h6': h6,
'em': em,
'strong': strong,
'del': del,
'blockquote': blockquote,
'img': img,
'table': p,
'th': tableHead,
'tr': tableBody,
'td': tableBody,
};
/// Creates a [MarkdownStyleSheet] from the [TextStyle]s in the provided [ThemeData].
factory MarkdownStyleSheet.fromTheme(ThemeData theme) {
assert(theme.textTheme.bodyMedium?.fontSize != null);
return MarkdownStyleSheet(
a: const TextStyle(color: Colors.blue),
p: theme.textTheme.bodyMedium,
pPadding: EdgeInsets.zero,
code: theme.textTheme.bodyMedium!.copyWith(
backgroundColor: theme.cardTheme.color ?? theme.cardColor,
fontFamily: 'monospace',
fontSize: theme.textTheme.bodyMedium!.fontSize! * 0.85,
),
h1: theme.textTheme.headlineSmall,
h1Padding: EdgeInsets.zero,
h2: theme.textTheme.titleLarge,
h2Padding: EdgeInsets.zero,
h3: theme.textTheme.titleMedium,
h3Padding: EdgeInsets.zero,
h4: theme.textTheme.bodyLarge,
h4Padding: EdgeInsets.zero,
h5: theme.textTheme.bodyLarge,
h5Padding: EdgeInsets.zero,
h6: theme.textTheme.bodyLarge,
h6Padding: EdgeInsets.zero,
em: const TextStyle(fontStyle: FontStyle.italic),
strong: const TextStyle(fontWeight: FontWeight.bold),
del: const TextStyle(decoration: TextDecoration.lineThrough),
blockquote: theme.textTheme.bodyMedium,
img: theme.textTheme.bodyMedium,
checkbox: theme.textTheme.bodyMedium!.copyWith(
color: theme.primaryColor,
),
blockSpacing: 8.0,
listIndent: 24.0,
listBullet: theme.textTheme.bodyMedium,
listBulletPadding: const EdgeInsets.only(right: 4),
tableHead: const TextStyle(fontWeight: FontWeight.w600),
tableBody: theme.textTheme.bodyMedium,
tableHeadAlign: TextAlign.center,
tableBorder: TableBorder.all(
color: theme.dividerColor,
),
tableColumnWidth: const FlexColumnWidth(),
tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
tableCellsDecoration: const BoxDecoration(),
blockquotePadding: const EdgeInsets.all(8.0),
blockquoteDecoration: BoxDecoration(
color: Colors.blue.shade100,
borderRadius: BorderRadius.circular(2.0),
),
codeblockPadding: const EdgeInsets.all(8.0),
codeblockDecoration: BoxDecoration(
color: theme.cardTheme.color ?? theme.cardColor,
borderRadius: BorderRadius.circular(2.0),
),
horizontalRuleDecoration: BoxDecoration(
border: Border(
top: BorderSide(
width: 5.0,
color: theme.dividerColor,
),
),
),
);
}
/// Creates a [MarkdownStyleSheet] from the [TextStyle]s in the provided [CupertinoThemeData].
factory MarkdownStyleSheet.fromCupertinoTheme(CupertinoThemeData theme) {
assert(theme.textTheme.textStyle.fontSize != null);
return MarkdownStyleSheet(
a: theme.textTheme.textStyle.copyWith(
color: theme.brightness == Brightness.dark
? CupertinoColors.link.darkColor
: CupertinoColors.link.color,
),
p: theme.textTheme.textStyle,
pPadding: EdgeInsets.zero,
code: theme.textTheme.textStyle.copyWith(
backgroundColor: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey6.darkColor
: CupertinoColors.systemGrey6.color,
fontFamily: 'monospace',
fontSize: theme.textTheme.textStyle.fontSize! * 0.85,
),
h1: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
fontSize: theme.textTheme.textStyle.fontSize! + 10,
),
h1Padding: EdgeInsets.zero,
h2: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
fontSize: theme.textTheme.textStyle.fontSize! + 8,
),
h2Padding: EdgeInsets.zero,
h3: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
fontSize: theme.textTheme.textStyle.fontSize! + 6,
),
h3Padding: EdgeInsets.zero,
h4: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
fontSize: theme.textTheme.textStyle.fontSize! + 4,
),
h4Padding: EdgeInsets.zero,
h5: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
fontSize: theme.textTheme.textStyle.fontSize! + 2,
),
h5Padding: EdgeInsets.zero,
h6: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w500,
),
h6Padding: EdgeInsets.zero,
em: theme.textTheme.textStyle.copyWith(
fontStyle: FontStyle.italic,
),
strong: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.bold,
),
del: theme.textTheme.textStyle.copyWith(
decoration: TextDecoration.lineThrough,
),
blockquote: theme.textTheme.textStyle,
img: theme.textTheme.textStyle,
checkbox: theme.textTheme.textStyle.copyWith(
color: theme.primaryColor,
),
blockSpacing: 8,
listIndent: 24,
listBullet: theme.textTheme.textStyle,
listBulletPadding: const EdgeInsets.only(right: 4),
tableHead: theme.textTheme.textStyle.copyWith(
fontWeight: FontWeight.w600,
),
tableBody: theme.textTheme.textStyle,
tableHeadAlign: TextAlign.center,
tableBorder: TableBorder.all(color: CupertinoColors.separator, width: 0),
tableColumnWidth: const FlexColumnWidth(),
tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
tableCellsDecoration: BoxDecoration(
color: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey6.darkColor
: CupertinoColors.systemGrey6.color,
),
blockquotePadding: const EdgeInsets.all(16),
blockquoteDecoration: BoxDecoration(
color: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey6.darkColor
: CupertinoColors.systemGrey6.color,
border: Border(
left: BorderSide(
color: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey4.darkColor
: CupertinoColors.systemGrey4.color,
width: 4,
),
),
),
codeblockPadding: const EdgeInsets.all(8),
codeblockDecoration: BoxDecoration(
color: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey6.darkColor
: CupertinoColors.systemGrey6.color,
),
horizontalRuleDecoration: BoxDecoration(
border: Border(
top: BorderSide(
color: theme.brightness == Brightness.dark
? CupertinoColors.systemGrey4.darkColor
: CupertinoColors.systemGrey4.color,
),
),
),
);
}
/// Creates a [MarkdownStyle] from the [TextStyle]s in the provided [ThemeData].
///
/// This constructor uses larger fonts for the headings than in
/// [MarkdownStyle.fromTheme].
factory MarkdownStyleSheet.largeFromTheme(ThemeData theme) {
return MarkdownStyleSheet(
a: const TextStyle(color: Colors.blue),
p: theme.textTheme.bodyMedium,
pPadding: EdgeInsets.zero,
code: theme.textTheme.bodyMedium!.copyWith(
backgroundColor: theme.cardTheme.color ?? theme.cardColor,
fontFamily: 'monospace',
fontSize: theme.textTheme.bodyMedium!.fontSize! * 0.85,
),
h1: theme.textTheme.displayMedium,
h1Padding: EdgeInsets.zero,
h2: theme.textTheme.displaySmall,
h2Padding: EdgeInsets.zero,
h3: theme.textTheme.headlineMedium,
h3Padding: EdgeInsets.zero,
h4: theme.textTheme.headlineSmall,
h4Padding: EdgeInsets.zero,
h5: theme.textTheme.titleLarge,
h5Padding: EdgeInsets.zero,
h6: theme.textTheme.titleMedium,
h6Padding: EdgeInsets.zero,
em: const TextStyle(fontStyle: FontStyle.italic),
strong: const TextStyle(fontWeight: FontWeight.bold),
del: const TextStyle(decoration: TextDecoration.lineThrough),
blockquote: theme.textTheme.bodyMedium,
img: theme.textTheme.bodyMedium,
checkbox: theme.textTheme.bodyMedium!.copyWith(
color: theme.primaryColor,
),
blockSpacing: 8.0,
listIndent: 24.0,
listBullet: theme.textTheme.bodyMedium,
listBulletPadding: const EdgeInsets.only(right: 4),
tableHead: const TextStyle(fontWeight: FontWeight.w600),
tableBody: theme.textTheme.bodyMedium,
tableHeadAlign: TextAlign.center,
tableBorder: TableBorder.all(
color: theme.dividerColor,
),
tableColumnWidth: const FlexColumnWidth(),
tableCellsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
tableCellsDecoration: const BoxDecoration(),
blockquotePadding: const EdgeInsets.all(8.0),
blockquoteDecoration: BoxDecoration(
color: Colors.blue.shade100,
borderRadius: BorderRadius.circular(2.0),
),
codeblockPadding: const EdgeInsets.all(8.0),
codeblockDecoration: BoxDecoration(
color: theme.cardTheme.color ?? theme.cardColor,
borderRadius: BorderRadius.circular(2.0),
),
horizontalRuleDecoration: BoxDecoration(
border: Border(
top: BorderSide(
width: 5.0,
color: theme.dividerColor,
),
),
),
);
}
/// Creates a [MarkdownStyleSheet] based on the current style, with the
/// provided parameters overridden.
MarkdownStyleSheet copyWith({
TextStyle? a,
TextStyle? p,
EdgeInsets? pPadding,
TextStyle? code,
TextStyle? h1,
EdgeInsets? h1Padding,
TextStyle? h2,
EdgeInsets? h2Padding,
TextStyle? h3,
EdgeInsets? h3Padding,
TextStyle? h4,
EdgeInsets? h4Padding,
TextStyle? h5,
EdgeInsets? h5Padding,
TextStyle? h6,
EdgeInsets? h6Padding,
TextStyle? em,
TextStyle? strong,
TextStyle? del,
TextStyle? blockquote,
TextStyle? img,
TextStyle? checkbox,
double? blockSpacing,
double? listIndent,
TextStyle? listBullet,
EdgeInsets? listBulletPadding,
TextStyle? tableHead,
TextStyle? tableBody,
TextAlign? tableHeadAlign,
TableBorder? tableBorder,
TableColumnWidth? tableColumnWidth,
EdgeInsets? tableCellsPadding,
Decoration? tableCellsDecoration,
TableCellVerticalAlignment? tableVerticalAlignment,
EdgeInsets? blockquotePadding,
Decoration? blockquoteDecoration,
EdgeInsets? codeblockPadding,
Decoration? codeblockDecoration,
Decoration? horizontalRuleDecoration,
WrapAlignment? textAlign,
WrapAlignment? h1Align,
WrapAlignment? h2Align,
WrapAlignment? h3Align,
WrapAlignment? h4Align,
WrapAlignment? h5Align,
WrapAlignment? h6Align,
WrapAlignment? unorderedListAlign,
WrapAlignment? orderedListAlign,
WrapAlignment? blockquoteAlign,
WrapAlignment? codeblockAlign,
double? textScaleFactor,
}) {
return MarkdownStyleSheet(
a: a ?? this.a,
p: p ?? this.p,
pPadding: pPadding ?? this.pPadding,
code: code ?? this.code,
h1: h1 ?? this.h1,
h1Padding: h1Padding ?? this.h1Padding,
h2: h2 ?? this.h2,
h2Padding: h2Padding ?? this.h2Padding,
h3: h3 ?? this.h3,
h3Padding: h3Padding ?? this.h3Padding,
h4: h4 ?? this.h4,
h4Padding: h4Padding ?? this.h4Padding,
h5: h5 ?? this.h5,
h5Padding: h5Padding ?? this.h5Padding,
h6: h6 ?? this.h6,
h6Padding: h6Padding ?? this.h6Padding,
em: em ?? this.em,
strong: strong ?? this.strong,
del: del ?? this.del,
blockquote: blockquote ?? this.blockquote,
img: img ?? this.img,
checkbox: checkbox ?? this.checkbox,
blockSpacing: blockSpacing ?? this.blockSpacing,
listIndent: listIndent ?? this.listIndent,
listBullet: listBullet ?? this.listBullet,
listBulletPadding: listBulletPadding ?? this.listBulletPadding,
tableHead: tableHead ?? this.tableHead,
tableBody: tableBody ?? this.tableBody,
tableHeadAlign: tableHeadAlign ?? this.tableHeadAlign,
tableBorder: tableBorder ?? this.tableBorder,
tableColumnWidth: tableColumnWidth ?? this.tableColumnWidth,
tableCellsPadding: tableCellsPadding ?? this.tableCellsPadding,
tableCellsDecoration: tableCellsDecoration ?? this.tableCellsDecoration,
tableVerticalAlignment:
tableVerticalAlignment ?? this.tableVerticalAlignment,
blockquotePadding: blockquotePadding ?? this.blockquotePadding,
blockquoteDecoration: blockquoteDecoration ?? this.blockquoteDecoration,
codeblockPadding: codeblockPadding ?? this.codeblockPadding,
codeblockDecoration: codeblockDecoration ?? this.codeblockDecoration,
horizontalRuleDecoration:
horizontalRuleDecoration ?? this.horizontalRuleDecoration,
textAlign: textAlign ?? this.textAlign,
h1Align: h1Align ?? this.h1Align,
h2Align: h2Align ?? this.h2Align,
h3Align: h3Align ?? this.h3Align,
h4Align: h4Align ?? this.h4Align,
h5Align: h5Align ?? this.h5Align,
h6Align: h6Align ?? this.h6Align,
unorderedListAlign: unorderedListAlign ?? this.unorderedListAlign,
orderedListAlign: orderedListAlign ?? this.orderedListAlign,
blockquoteAlign: blockquoteAlign ?? this.blockquoteAlign,
codeblockAlign: codeblockAlign ?? this.codeblockAlign,
textScaleFactor: textScaleFactor ?? this.textScaleFactor,
);
}
/// Returns a new text style that is a combination of this style and the given
/// [other] style.
MarkdownStyleSheet merge(MarkdownStyleSheet? other) {
if (other == null) {
return this;
}
return copyWith(
a: a!.merge(other.a),
p: p!.merge(other.p),
pPadding: other.pPadding,
code: code!.merge(other.code),
h1: h1!.merge(other.h1),
h1Padding: other.h1Padding,
h2: h2!.merge(other.h2),
h2Padding: other.h2Padding,
h3: h3!.merge(other.h3),
h3Padding: other.h3Padding,
h4: h4!.merge(other.h4),
h4Padding: other.h4Padding,
h5: h5!.merge(other.h5),
h5Padding: other.h5Padding,
h6: h6!.merge(other.h6),
h6Padding: other.h6Padding,
em: em!.merge(other.em),
strong: strong!.merge(other.strong),
del: del!.merge(other.del),
blockquote: blockquote!.merge(other.blockquote),
img: img!.merge(other.img),
checkbox: checkbox!.merge(other.checkbox),
blockSpacing: other.blockSpacing,
listIndent: other.listIndent,
listBullet: listBullet!.merge(other.listBullet),
listBulletPadding: other.listBulletPadding,
tableHead: tableHead!.merge(other.tableHead),
tableBody: tableBody!.merge(other.tableBody),
tableHeadAlign: other.tableHeadAlign,
tableBorder: other.tableBorder,
tableColumnWidth: other.tableColumnWidth,
tableCellsPadding: other.tableCellsPadding,
tableCellsDecoration: other.tableCellsDecoration,
tableVerticalAlignment: other.tableVerticalAlignment,
blockquotePadding: other.blockquotePadding,
blockquoteDecoration: other.blockquoteDecoration,
codeblockPadding: other.codeblockPadding,
codeblockDecoration: other.codeblockDecoration,
horizontalRuleDecoration: other.horizontalRuleDecoration,
textAlign: other.textAlign,
h1Align: other.h1Align,
h2Align: other.h2Align,
h3Align: other.h3Align,
h4Align: other.h4Align,
h5Align: other.h5Align,
h6Align: other.h6Align,
unorderedListAlign: other.unorderedListAlign,
orderedListAlign: other.orderedListAlign,
blockquoteAlign: other.blockquoteAlign,
codeblockAlign: other.codeblockAlign,
textScaleFactor: other.textScaleFactor,
);
}
/// The [TextStyle] to use for `a` elements.
final TextStyle? a;
/// The [TextStyle] to use for `p` elements.
final TextStyle? p;
/// The padding to use for `p` elements.
final EdgeInsets? pPadding;
/// The [TextStyle] to use for `code` elements.
final TextStyle? code;
/// The [TextStyle] to use for `h1` elements.
final TextStyle? h1;
/// The padding to use for `h1` elements.
final EdgeInsets? h1Padding;
/// The [TextStyle] to use for `h2` elements.
final TextStyle? h2;
/// The padding to use for `h2` elements.
final EdgeInsets? h2Padding;
/// The [TextStyle] to use for `h3` elements.
final TextStyle? h3;
/// The padding to use for `h3` elements.
final EdgeInsets? h3Padding;
/// The [TextStyle] to use for `h4` elements.
final TextStyle? h4;
/// The padding to use for `h4` elements.
final EdgeInsets? h4Padding;
/// The [TextStyle] to use for `h5` elements.
final TextStyle? h5;
/// The padding to use for `h5` elements.
final EdgeInsets? h5Padding;
/// The [TextStyle] to use for `h6` elements.
final TextStyle? h6;
/// The padding to use for `h6` elements.
final EdgeInsets? h6Padding;
/// The [TextStyle] to use for `em` elements.
final TextStyle? em;
/// The [TextStyle] to use for `strong` elements.
final TextStyle? strong;
/// The [TextStyle] to use for `del` elements.
final TextStyle? del;
/// The [TextStyle] to use for `blockquote` elements.
final TextStyle? blockquote;
/// The [TextStyle] to use for `img` elements.
final TextStyle? img;
/// The [TextStyle] to use for `input` elements.
final TextStyle? checkbox;
/// The amount of vertical space to use between block-level elements.
final double? blockSpacing;
/// The amount of horizontal space to indent list items.
final double? listIndent;
/// The [TextStyle] to use for bullets.
final TextStyle? listBullet;
/// The padding to use for bullets.
final EdgeInsets? listBulletPadding;
/// The [TextStyle] to use for `th` elements.
final TextStyle? tableHead;
/// The [TextStyle] to use for `td` elements.
final TextStyle? tableBody;
/// The [TextAlign] to use for `th` elements.
final TextAlign? tableHeadAlign;
/// The [TableBorder] to use for `table` elements.
final TableBorder? tableBorder;
/// The [TableColumnWidth] to use for `th` and `td` elements.
final TableColumnWidth? tableColumnWidth;
/// The padding to use for `th` and `td` elements.
final EdgeInsets? tableCellsPadding;
/// The decoration to use for `th` and `td` elements.
final Decoration? tableCellsDecoration;
/// The [TableCellVerticalAlignment] to use for `th` and `td` elements.
final TableCellVerticalAlignment tableVerticalAlignment;
/// The padding to use for `blockquote` elements.
final EdgeInsets? blockquotePadding;
/// The decoration to use behind `blockquote` elements.
final Decoration? blockquoteDecoration;
/// The padding to use for `pre` elements.
final EdgeInsets? codeblockPadding;
/// The decoration to use behind for `pre` elements.
final Decoration? codeblockDecoration;
/// The decoration to use for `hr` elements.
final Decoration? horizontalRuleDecoration;
/// The [WrapAlignment] to use for normal text. Defaults to start.
final WrapAlignment textAlign;
/// The [WrapAlignment] to use for h1 text. Defaults to start.
final WrapAlignment h1Align;
/// The [WrapAlignment] to use for h2 text. Defaults to start.
final WrapAlignment h2Align;
/// The [WrapAlignment] to use for h3 text. Defaults to start.
final WrapAlignment h3Align;
/// The [WrapAlignment] to use for h4 text. Defaults to start.
final WrapAlignment h4Align;
/// The [WrapAlignment] to use for h5 text. Defaults to start.
final WrapAlignment h5Align;
/// The [WrapAlignment] to use for h6 text. Defaults to start.
final WrapAlignment h6Align;
/// The [WrapAlignment] to use for an unordered list. Defaults to start.
final WrapAlignment unorderedListAlign;
/// The [WrapAlignment] to use for an ordered list. Defaults to start.
final WrapAlignment orderedListAlign;
/// The [WrapAlignment] to use for a blockquote. Defaults to start.
final WrapAlignment blockquoteAlign;
/// The [WrapAlignment] to use for a code block. Defaults to start.
final WrapAlignment codeblockAlign;
/// The text scale factor to use in textual elements
final double? textScaleFactor;
/// A [Map] from element name to the corresponding [TextStyle] object.
Map<String, TextStyle?> get styles => _styles;
Map<String, TextStyle?> _styles;
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != MarkdownStyleSheet) {
return false;
}
return other is MarkdownStyleSheet &&
other.a == a &&
other.p == p &&
other.pPadding == pPadding &&
other.code == code &&
other.h1 == h1 &&
other.h1Padding == h1Padding &&
other.h2 == h2 &&
other.h2Padding == h2Padding &&
other.h3 == h3 &&
other.h3Padding == h3Padding &&
other.h4 == h4 &&
other.h4Padding == h4Padding &&
other.h5 == h5 &&
other.h5Padding == h5Padding &&
other.h6 == h6 &&
other.h6Padding == h6Padding &&
other.em == em &&
other.strong == strong &&
other.del == del &&
other.blockquote == blockquote &&
other.img == img &&
other.checkbox == checkbox &&
other.blockSpacing == blockSpacing &&
other.listIndent == listIndent &&
other.listBullet == listBullet &&
other.listBulletPadding == listBulletPadding &&
other.tableHead == tableHead &&
other.tableBody == tableBody &&
other.tableHeadAlign == tableHeadAlign &&
other.tableBorder == tableBorder &&
other.tableColumnWidth == tableColumnWidth &&
other.tableCellsPadding == tableCellsPadding &&
other.tableCellsDecoration == tableCellsDecoration &&
other.tableVerticalAlignment == tableVerticalAlignment &&
other.blockquotePadding == blockquotePadding &&
other.blockquoteDecoration == blockquoteDecoration &&
other.codeblockPadding == codeblockPadding &&
other.codeblockDecoration == codeblockDecoration &&
other.horizontalRuleDecoration == horizontalRuleDecoration &&
other.textAlign == textAlign &&
other.h1Align == h1Align &&
other.h2Align == h2Align &&
other.h3Align == h3Align &&
other.h4Align == h4Align &&
other.h5Align == h5Align &&
other.h6Align == h6Align &&
other.unorderedListAlign == unorderedListAlign &&
other.orderedListAlign == orderedListAlign &&
other.blockquoteAlign == blockquoteAlign &&
other.codeblockAlign == codeblockAlign &&
other.textScaleFactor == textScaleFactor;
}
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode {
return Object.hashAll(<Object?>[
a,
p,
pPadding,
code,
h1,
h1Padding,
h2,
h2Padding,
h3,
h3Padding,
h4,
h4Padding,
h5,
h5Padding,
h6,
h6Padding,
em,
strong,
del,
blockquote,
img,
checkbox,
blockSpacing,
listIndent,
listBullet,
listBulletPadding,
tableHead,
tableBody,
tableHeadAlign,
tableBorder,
tableColumnWidth,
tableCellsPadding,
tableCellsDecoration,
tableVerticalAlignment,
blockquotePadding,
blockquoteDecoration,
codeblockPadding,
codeblockDecoration,
horizontalRuleDecoration,
textAlign,
h1Align,
h2Align,
h3Align,
h4Align,
h5Align,
h6Align,
unorderedListAlign,
orderedListAlign,
blockquoteAlign,
codeblockAlign,
textScaleFactor,
]);
}
}
| packages/packages/flutter_markdown/lib/src/style_sheet.dart/0 | {'file_path': 'packages/packages/flutter_markdown/lib/src/style_sheet.dart', 'repo_id': 'packages', 'token_count': 10867} |
// 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('Hard Line Breaks', () {
testWidgets(
// Example 654 from GFM.
'two spaces at end of line',
(WidgetTester tester) async {
const String data = 'foo \nbar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
},
);
testWidgets(
// Example 655 from GFM.
'backslash at end of line',
(WidgetTester tester) async {
const String data = 'foo\\\nbar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
},
);
testWidgets(
// Example 656 from GFM.
'more than two spaces at end of line',
(WidgetTester tester) async {
const String data = 'foo \nbar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
},
);
testWidgets(
// Example 657 from GFM.
'leading spaces at beginning of next line are ignored',
(WidgetTester tester) async {
const String data = 'foo \n bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
},
);
testWidgets(
// Example 658 from GFM.
'leading spaces at beginning of next line are ignored',
(WidgetTester tester) async {
const String data = 'foo\\\n bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
},
);
testWidgets(
// Example 659 from GFM.
'two spaces line break inside emphasis',
(WidgetTester tester) async {
const String data = '*foo \nbar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
// There should be three spans of text.
final TextSpan textSpan = richText.text as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan, FontStyle.italic, FontWeight.normal);
// Second span is just the newline character with no font style or weight.
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan, FontStyle.italic, FontWeight.normal);
},
);
testWidgets(
// Example 660 from GFM.
'backslash line break inside emphasis',
(WidgetTester tester) async {
const String data = '*foo\\\nbar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo\nbar');
// There should be three spans of text.
final TextSpan textSpan = richText.text as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan, FontStyle.italic, FontWeight.normal);
// Second span is just the newline character with no font style or weight.
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan, FontStyle.italic, FontWeight.normal);
},
);
testWidgets(
// Example 661 from GFM.
'two space line break does not occur in code span',
(WidgetTester tester) async {
const String data = '`code \nspan`';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'code span');
final TextSpan textSpan = richText.text as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.style, isNotNull);
expect(textSpan.style!.fontFamily == 'monospace', isTrue);
},
);
testWidgets(
// Example 662 from GFM.
'backslash line break does not occur in code span',
(WidgetTester tester) async {
const String data = '`code\\\nspan`';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, r'code\ span');
final TextSpan textSpan = richText.text as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.style, isNotNull);
expect(textSpan.style!.fontFamily == 'monospace', isTrue);
},
);
testWidgets(
// Example 665 from GFM.
'backslash at end of paragraph is ignored',
(WidgetTester tester) async {
const String data = r'foo\';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, r'foo\');
},
);
testWidgets(
// Example 666 from GFM.
'two spaces at end of paragraph is ignored',
(WidgetTester tester) async {
const String data = 'foo ';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo');
},
);
testWidgets(
// Example 667 from GFM.
'backslash at end of header is ignored',
(WidgetTester tester) async {
const String data = r'### foo\';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, r'foo\');
},
);
testWidgets(
// Example 668 from GFM.
'two spaces at end of header is ignored',
(WidgetTester tester) async {
const String data = '### foo ';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo');
},
);
});
group('Soft Line Breaks', () {
testWidgets(
// Example 669 from GFM.
'lines of text in paragraph',
(WidgetTester tester) async {
const String data = 'foo\nbaz';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo baz');
},
);
testWidgets(
// Example 670 from GFM.
'spaces at beginning and end of lines of text in paragraph are removed',
(WidgetTester tester) async {
const String data = 'foo \n baz';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder richTextFinder = find.byType(RichText);
expect(richTextFinder, findsOneWidget);
final RichText richText =
richTextFinder.evaluate().first.widget as RichText;
final String text = richText.text.toPlainText();
expect(text, 'foo baz');
},
);
});
}
| packages/packages/flutter_markdown/test/line_break_test.dart/0 | {'file_path': 'packages/packages/flutter_markdown/test/line_break_test.dart', 'repo_id': 'packages', 'token_count': 5068} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import '../base/command.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/project.dart';
import '../base/terminal.dart';
import '../utils.dart';
/// Abandons the existing migration by deleting the migrate working directory.
class MigrateAbandonCommand extends MigrateCommand {
MigrateAbandonCommand({
required this.logger,
required this.fileSystem,
required this.terminal,
required ProcessManager processManager,
this.standalone = false,
}) : migrateUtils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: processManager,
) {
argParser.addOption(
'staging-directory',
help: 'Specifies the custom migration working directory used to stage '
'and edit proposed changes. This path can be absolute or relative '
'to the flutter project root. This defaults to '
'`$kDefaultMigrateStagingDirectoryName`',
valueHelp: 'path',
);
argParser.addOption(
'project-directory',
help: 'The root directory of the flutter project. This defaults to the '
'current working directory if omitted.',
valueHelp: 'path',
);
argParser.addFlag(
'force',
abbr: 'f',
help:
'Delete the migrate working directory without asking for confirmation.',
);
argParser.addFlag(
'flutter-subcommand',
help:
'Enable when using the flutter tool as a subcommand. This changes the '
'wording of log messages to indicate the correct suggested commands to use.',
);
}
final Logger logger;
final FileSystem fileSystem;
final Terminal terminal;
final MigrateUtils migrateUtils;
final bool standalone;
@override
final String name = 'abandon';
@override
final String description =
'Deletes the current active migration working directory.';
@override
Future<CommandResult> runCommand() async {
final String? projectDirectory = stringArg('project-directory');
final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory();
final FlutterProject project = projectDirectory == null
? FlutterProject.current(fileSystem)
: flutterProjectFactory
.fromDirectory(fileSystem.directory(projectDirectory));
final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone;
if (!validateWorkingDirectory(project, logger)) {
return const CommandResult(ExitStatus.fail);
}
Directory stagingDirectory =
project.directory.childDirectory(kDefaultMigrateStagingDirectoryName);
final String? customStagingDirectoryPath = stringArg('staging-directory');
if (customStagingDirectoryPath != null) {
if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) {
stagingDirectory = fileSystem.directory(customStagingDirectoryPath);
} else {
stagingDirectory =
project.directory.childDirectory(customStagingDirectoryPath);
}
if (!stagingDirectory.existsSync()) {
logger.printError(
'Provided staging directory `$customStagingDirectoryPath` '
'does not exist or is not valid.');
return const CommandResult(ExitStatus.fail);
}
}
if (!stagingDirectory.existsSync()) {
logger
.printStatus('No migration in progress. Start a new migration with:');
printCommandText('start', logger, standalone: !isSubcommand);
return const CommandResult(ExitStatus.fail);
}
logger.printStatus('\nAbandoning the existing migration will delete the '
'migration staging directory at ${stagingDirectory.path}');
final bool force = boolArg('force') ?? false;
if (!force) {
String selection = 'y';
terminal.usesTerminalUi = true;
try {
selection = await terminal.promptForCharInput(
<String>['y', 'n'],
logger: logger,
prompt:
'Are you sure you wish to continue with abandoning? (y)es, (N)o',
defaultChoiceIndex: 1,
);
} on StateError catch (e) {
logger.printError(
e.message,
indent: 0,
);
}
if (selection != 'y') {
return const CommandResult(ExitStatus.success);
}
}
try {
stagingDirectory.deleteSync(recursive: true);
} on FileSystemException catch (e) {
logger.printError('Deletion failed with: $e');
logger.printError(
'Please manually delete the staging directory at `${stagingDirectory.path}`');
}
logger.printStatus('\nAbandon complete. Start a new migration with:');
printCommandText('start', logger, standalone: !isSubcommand);
return const CommandResult(ExitStatus.success);
}
}
| packages/packages/flutter_migrate/lib/src/commands/abandon.dart/0 | {'file_path': 'packages/packages/flutter_migrate/lib/src/commands/abandon.dart', 'repo_id': 'packages', 'token_count': 1782} |
// 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_migrate/src/base/context.dart';
import '../src/common.dart';
void main() {
group('AppContext', () {
group('global getter', () {
late bool called;
setUp(() {
called = false;
});
test('returns non-null context in the root zone', () {
expect(context, isNotNull);
});
test(
'returns root context in child of root zone if zone was manually created',
() {
final Zone rootZone = Zone.current;
final AppContext rootContext = context;
runZoned<void>(() {
expect(Zone.current, isNot(rootZone));
expect(Zone.current.parent, rootZone);
expect(context, rootContext);
called = true;
});
expect(called, isTrue);
});
test('returns child context after run', () async {
final AppContext rootContext = context;
await rootContext.run<void>(
name: 'child',
body: () {
expect(context, isNot(rootContext));
expect(context.name, 'child');
called = true;
});
expect(called, isTrue);
});
test('returns grandchild context after nested run', () async {
final AppContext rootContext = context;
await rootContext.run<void>(
name: 'child',
body: () async {
final AppContext childContext = context;
await childContext.run<void>(
name: 'grandchild',
body: () {
expect(context, isNot(rootContext));
expect(context, isNot(childContext));
expect(context.name, 'grandchild');
called = true;
});
});
expect(called, isTrue);
});
test('scans up zone hierarchy for first context', () async {
final AppContext rootContext = context;
await rootContext.run<void>(
name: 'child',
body: () {
final AppContext childContext = context;
runZoned<void>(() {
expect(context, isNot(rootContext));
expect(context, same(childContext));
expect(context.name, 'child');
called = true;
});
});
expect(called, isTrue);
});
});
group('operator[]', () {
test('still finds values if async code runs after body has finished',
() async {
final Completer<void> outer = Completer<void>();
final Completer<void> inner = Completer<void>();
String? value;
await context.run<void>(
body: () {
outer.future.then<void>((_) {
value = context.get<String>();
inner.complete();
});
},
fallbacks: <Type, Generator>{
String: () => 'value',
},
);
expect(value, isNull);
outer.complete();
await inner.future;
expect(value, 'value');
});
test('caches generated override values', () async {
int consultationCount = 0;
String? value;
await context.run<void>(
body: () async {
final StringBuffer buf = StringBuffer(context.get<String>()!);
buf.write(context.get<String>());
await context.run<void>(body: () {
buf.write(context.get<String>());
});
value = buf.toString();
},
overrides: <Type, Generator>{
String: () {
consultationCount++;
return 'v';
},
},
);
expect(value, 'vvv');
expect(consultationCount, 1);
});
test('caches generated fallback values', () async {
int consultationCount = 0;
String? value;
await context.run(
body: () async {
final StringBuffer buf = StringBuffer(context.get<String>()!);
buf.write(context.get<String>());
await context.run<void>(body: () {
buf.write(context.get<String>());
});
value = buf.toString();
},
fallbacks: <Type, Generator>{
String: () {
consultationCount++;
return 'v';
},
},
);
expect(value, 'vvv');
expect(consultationCount, 1);
});
test('returns null if generated value is null', () async {
final String? value = await context.run<String?>(
body: () => context.get<String>(),
overrides: <Type, Generator>{
String: () => null,
},
);
expect(value, isNull);
});
test('throws if generator has dependency cycle', () async {
final Future<String?> value = context.run<String?>(
body: () async {
return context.get<String>();
},
fallbacks: <Type, Generator>{
int: () => int.parse(context.get<String>() ?? ''),
String: () => '${context.get<double>()}',
double: () => context.get<int>()! * 1.0,
},
);
expect(
() => value,
throwsA(
isA<ContextDependencyCycleException>().having(
(ContextDependencyCycleException error) => error.cycle,
'cycle',
<Type>[String, double, int]).having(
(ContextDependencyCycleException error) => error.toString(),
'toString()',
'Dependency cycle detected: String -> double -> int',
),
),
);
});
});
group('run', () {
test('returns the value returned by body', () async {
expect(await context.run<int>(body: () => 123), 123);
expect(await context.run<String>(body: () => 'value'), 'value');
expect(await context.run<int>(body: () async => 456), 456);
});
test('passes name to child context', () async {
await context.run<void>(
name: 'child',
body: () {
expect(context.name, 'child');
});
});
group('fallbacks', () {
late bool called;
setUp(() {
called = false;
});
test('are applied after parent context is consulted', () async {
final String? value = await context.run<String?>(
body: () {
return context.run<String?>(
body: () {
called = true;
return context.get<String>();
},
fallbacks: <Type, Generator>{
String: () => 'child',
},
);
},
);
expect(called, isTrue);
expect(value, 'child');
});
test('are not applied if parent context supplies value', () async {
bool childConsulted = false;
final String? value = await context.run<String?>(
body: () {
return context.run<String?>(
body: () {
called = true;
return context.get<String>();
},
fallbacks: <Type, Generator>{
String: () {
childConsulted = true;
return 'child';
},
},
);
},
fallbacks: <Type, Generator>{
String: () => 'parent',
},
);
expect(called, isTrue);
expect(value, 'parent');
expect(childConsulted, isFalse);
});
test('may depend on one another', () async {
final String? value = await context.run<String?>(
body: () {
return context.get<String>();
},
fallbacks: <Type, Generator>{
int: () => 123,
String: () => '-${context.get<int>()}-',
},
);
expect(value, '-123-');
});
});
group('overrides', () {
test('intercept consultation of parent context', () async {
bool parentConsulted = false;
final String? value = await context.run<String?>(
body: () {
return context.run<String?>(
body: () => context.get<String>(),
overrides: <Type, Generator>{
String: () => 'child',
},
);
},
fallbacks: <Type, Generator>{
String: () {
parentConsulted = true;
return 'parent';
},
},
);
expect(value, 'child');
expect(parentConsulted, isFalse);
});
});
});
});
}
| packages/packages/flutter_migrate/test/base/context_test.dart/0 | {'file_path': 'packages/packages/flutter_migrate/test/base/context_test.dart', 'repo_id': 'packages', 'token_count': 4601} |
// 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:args/command_runner.dart';
import 'package:flutter_migrate/src/base/command.dart';
export 'package:test_api/test_api.dart' // ignore: deprecated_member_use
hide
isInstanceOf,
test;
CommandRunner<void> createTestCommandRunner([MigrateCommand? command]) {
final CommandRunner<void> runner = TestCommandRunner();
if (command != null) {
runner.addCommand(command);
}
return runner;
}
class TestCommandRunner extends CommandRunner<void> {
TestCommandRunner()
: super(
'flutter',
'Manage your Flutter app development.\n'
'\n'
'Common commands:\n'
'\n'
' flutter create <output directory>\n'
' Create a new Flutter project in the specified directory.\n'
'\n'
' flutter run [options]\n'
' Run your Flutter application on an attached device or in an emulator.',
);
}
| packages/packages/flutter_migrate/test/src/test_flutter_command_runner.dart/0 | {'file_path': 'packages/packages/flutter_migrate/test/src/test_flutter_command_runner.dart', 'repo_id': 'packages', 'token_count': 456} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../data.dart';
import '../widgets/author_list.dart';
/// A screen that displays a list of authors.
class AuthorsScreen extends StatelessWidget {
/// Creates an [AuthorsScreen].
const AuthorsScreen({super.key});
/// The title of the screen.
static const String title = 'Authors';
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: AuthorList(
authors: libraryInstance.allAuthors,
onTap: (Author author) {
context.go('/author/${author.id}');
},
),
);
}
| packages/packages/go_router/example/lib/books/src/screens/authors.dart/0 | {'file_path': 'packages/packages/go_router/example/lib/books/src/screens/authors.dart', 'repo_id': 'packages', 'token_count': 323} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(App());
/// The main app.
class App extends StatelessWidget {
/// Creates an [App].
App({super.key});
/// The title of the app.
static const String title = 'GoRouter Example: Initial Location';
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
);
final GoRouter _router = GoRouter(
initialLocation: '/page3',
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const Page1Screen(),
),
GoRoute(
path: '/page2',
builder: (BuildContext context, GoRouterState state) =>
const Page2Screen(),
),
GoRoute(
path: '/page3',
builder: (BuildContext context, GoRouterState state) =>
const Page3Screen(),
),
],
);
}
/// The screen of the first page.
class Page1Screen extends StatelessWidget {
/// Creates a [Page1Screen].
const Page1Screen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(App.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => context.go('/page2'),
child: const Text('Go to page 2'),
),
],
),
),
);
}
/// The screen of the second page.
class Page2Screen extends StatelessWidget {
/// Creates a [Page2Screen].
const Page2Screen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(App.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => context.go('/'),
child: const Text('Go to home page'),
),
],
),
),
);
}
/// The screen of the third page.
class Page3Screen extends StatelessWidget {
/// Creates a [Page3Screen].
const Page3Screen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(App.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => context.go('/page2'),
child: const Text('Go to page 2'),
),
],
),
),
);
}
| packages/packages/go_router/example/lib/others/init_loc.dart/0 | {'file_path': 'packages/packages/go_router/example/lib/others/init_loc.dart', 'repo_id': 'packages', 'token_count': 1300} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router_examples/push_with_shell_route.dart' as example;
void main() {
testWidgets('example works', (WidgetTester tester) async {
await tester.pumpWidget(example.PushWithShellRouteExampleApp());
expect(find.text('shell1'), findsOneWidget);
await tester.tap(find.text('push the same shell route /shell1'));
await tester.pumpAndSettle();
expect(find.text('shell1'), findsOneWidget);
expect(find.text('shell1 body'), findsOneWidget);
find.text('shell1 body').evaluate().first.pop();
await tester.pumpAndSettle();
expect(find.text('shell1'), findsOneWidget);
expect(find.text('shell1 body'), findsNothing);
await tester.tap(find.text('push the different shell route /shell2'));
await tester.pumpAndSettle();
expect(find.text('shell1'), findsNothing);
expect(find.text('shell2'), findsOneWidget);
expect(find.text('shell2 body'), findsOneWidget);
find.text('shell2 body').evaluate().first.pop();
await tester.pumpAndSettle();
expect(find.text('shell1'), findsOneWidget);
expect(find.text('shell2'), findsNothing);
await tester.tap(find.text('push the regular route /regular-route'));
await tester.pumpAndSettle();
expect(find.text('shell1'), findsNothing);
expect(find.text('regular route'), findsOneWidget);
find.text('regular route').evaluate().first.pop();
await tester.pumpAndSettle();
expect(find.text('shell1'), findsOneWidget);
expect(find.text('regular route'), findsNothing);
});
}
| packages/packages/go_router/example/test/push_with_shell_route_test.dart/0 | {'file_path': 'packages/packages/go_router/example/test/push_with_shell_route_test.dart', 'repo_id': 'packages', 'token_count': 601} |
// 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:developer' as developer;
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
/// The logger for this package.
@visibleForTesting
final Logger logger = Logger('GoRouter');
/// Whether or not the logging is enabled.
bool _enabled = false;
/// Logs the message if logging is enabled.
void log(String message, {Level level = Level.INFO}) {
if (_enabled) {
logger.log(level, message);
}
}
StreamSubscription<LogRecord>? _subscription;
/// Forwards diagnostic messages to the dart:developer log() API.
void setLogging({bool enabled = false}) {
_subscription?.cancel();
_enabled = enabled;
if (!enabled) {
return;
}
_subscription = logger.onRecord.listen((LogRecord e) {
// use `dumpErrorToConsole` for severe messages to ensure that severe
// exceptions are formatted consistently with other Flutter examples and
// avoids printing duplicate exceptions
if (e.level >= Level.SEVERE) {
final Object? error = e.error;
FlutterError.dumpErrorToConsole(
FlutterErrorDetails(
exception: error is Exception ? error : Exception(error),
stack: e.stackTrace,
library: e.loggerName,
context: ErrorDescription(e.message),
),
);
} else {
developer.log(
e.message,
time: e.time,
sequenceNumber: e.sequenceNumber,
level: e.level.value,
name: e.loggerName,
zone: e.zone,
error: e.error,
stackTrace: e.stackTrace,
);
}
});
}
| packages/packages/go_router/lib/src/logging.dart/0 | {'file_path': 'packages/packages/go_router/lib/src/logging.dart', 'repo_id': 'packages', 'token_count': 633} |
# This custom rule set only exists to allow very targeted changes
# relative to the default repo settings, for specific use cases.
# Please do NOT add more changes here without consulting with
# #hackers-ecosystem on Discord.
include: ../../../analysis_options.yaml
linter:
rules:
# Matches flutter/flutter, which disables this rule due to false positives
# from navigator APIs.
unawaited_futures: false
| packages/packages/go_router/test/analysis_options.yaml/0 | {'file_path': 'packages/packages/go_router/test/analysis_options.yaml', 'repo_id': 'packages', 'token_count': 118} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
void main() {
group('updateShouldNotify', () {
test('does not update when goRouter does not change', () {
final GoRouter goRouter = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Page1(),
),
],
);
final bool shouldNotify = setupInheritedGoRouterChange(
oldGoRouter: goRouter,
newGoRouter: goRouter,
);
expect(shouldNotify, false);
});
test('does not update even when goRouter changes', () {
final GoRouter oldGoRouter = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Page1(),
),
],
);
final GoRouter newGoRouter = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Page2(),
),
],
);
final bool shouldNotify = setupInheritedGoRouterChange(
oldGoRouter: oldGoRouter,
newGoRouter: newGoRouter,
);
expect(shouldNotify, false);
});
});
test('adds [goRouter] as a diagnostics property', () {
final GoRouter goRouter = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Page1(),
),
],
);
final InheritedGoRouter inheritedGoRouter = InheritedGoRouter(
goRouter: goRouter,
child: Container(),
);
final DiagnosticPropertiesBuilder properties =
DiagnosticPropertiesBuilder();
inheritedGoRouter.debugFillProperties(properties);
expect(properties.properties.length, 1);
expect(properties.properties.first, isA<DiagnosticsProperty<GoRouter>>());
expect(properties.properties.first.value, goRouter);
});
testWidgets("mediates Widget's access to GoRouter.",
(WidgetTester tester) async {
final MockGoRouter router = MockGoRouter();
await tester.pumpWidget(MaterialApp(
home: InheritedGoRouter(goRouter: router, child: const _MyWidget())));
await tester.tap(find.text('My Page'));
expect(router.latestPushedName, 'my_page');
});
testWidgets('builder can access GoRouter', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/110512.
late final GoRouter buildContextRouter;
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, __) {
buildContextRouter = GoRouter.of(context);
return const DummyScreen();
},
)
],
);
await tester.pumpWidget(
MaterialApp.router(
routeInformationProvider: router.routeInformationProvider,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate),
);
expect(buildContextRouter, isNotNull);
expect(buildContextRouter, equals(router));
});
}
bool setupInheritedGoRouterChange({
required GoRouter oldGoRouter,
required GoRouter newGoRouter,
}) {
final InheritedGoRouter oldInheritedGoRouter = InheritedGoRouter(
goRouter: oldGoRouter,
child: Container(),
);
final InheritedGoRouter newInheritedGoRouter = InheritedGoRouter(
goRouter: newGoRouter,
child: Container(),
);
return newInheritedGoRouter.updateShouldNotify(
oldInheritedGoRouter,
);
}
class Page1 extends StatelessWidget {
const Page1({super.key});
@override
Widget build(BuildContext context) => Container();
}
class Page2 extends StatelessWidget {
const Page2({super.key});
@override
Widget build(BuildContext context) => Container();
}
class _MyWidget extends StatelessWidget {
const _MyWidget();
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => context.pushNamed('my_page'),
child: const Text('My Page'));
}
}
class MockGoRouter extends GoRouter {
MockGoRouter()
: super.routingConfig(
routingConfig: const ConstantRoutingConfig(
RoutingConfig(routes: <RouteBase>[])));
late String latestPushedName;
@override
Future<T?> pushNamed<T extends Object?>(String name,
{Map<String, String> pathParameters = const <String, String>{},
Map<String, dynamic> queryParameters = const <String, dynamic>{},
Object? extra}) {
latestPushedName = name;
return Future<T?>.value();
}
@override
BackButtonDispatcher get backButtonDispatcher => RootBackButtonDispatcher();
}
| packages/packages/go_router/test/inherited_test.dart/0 | {'file_path': 'packages/packages/go_router/test/inherited_test.dart', 'repo_id': 'packages', 'token_count': 1979} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, unreachable_from_main
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
part 'extra_example.g.dart';
void main() => runApp(const App());
final GoRouter _router = GoRouter(
routes: $appRoutes,
initialLocation: '/splash',
);
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}
class Extra {
const Extra(this.value);
final int value;
}
@TypedGoRoute<RequiredExtraRoute>(path: '/requiredExtra')
class RequiredExtraRoute extends GoRouteData {
const RequiredExtraRoute({required this.$extra});
final Extra $extra;
@override
Widget build(BuildContext context, GoRouterState state) =>
RequiredExtraScreen(extra: $extra);
}
class RequiredExtraScreen extends StatelessWidget {
const RequiredExtraScreen({super.key, required this.extra});
final Extra extra;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Required Extra')),
body: Center(child: Text('Extra: ${extra.value}')),
);
}
}
@TypedGoRoute<OptionalExtraRoute>(path: '/optionalExtra')
class OptionalExtraRoute extends GoRouteData {
const OptionalExtraRoute({this.$extra});
final Extra? $extra;
@override
Widget build(BuildContext context, GoRouterState state) =>
OptionalExtraScreen(extra: $extra);
}
class OptionalExtraScreen extends StatelessWidget {
const OptionalExtraScreen({super.key, this.extra});
final Extra? extra;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Optional Extra')),
body: Center(child: Text('Extra: ${extra?.value}')),
);
}
}
@TypedGoRoute<SplashRoute>(path: '/splash')
class SplashRoute extends GoRouteData {
const SplashRoute();
@override
Widget build(BuildContext context, GoRouterState state) => const Splash();
}
class Splash extends StatelessWidget {
const Splash({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Splash')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Placeholder(),
ElevatedButton(
onPressed: () =>
const RequiredExtraRoute($extra: Extra(1)).go(context),
child: const Text('Required Extra'),
),
ElevatedButton(
onPressed: () =>
const OptionalExtraRoute($extra: Extra(2)).go(context),
child: const Text('Optional Extra'),
),
ElevatedButton(
onPressed: () => const OptionalExtraRoute().go(context),
child: const Text('Optional Extra (null)'),
),
],
),
);
}
}
| packages/packages/go_router_builder/example/lib/extra_example.dart/0 | {'file_path': 'packages/packages/go_router_builder/example/lib/extra_example.dart', 'repo_id': 'packages', 'token_count': 1115} |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: always_specify_types, public_member_api_docs
part of 'stateful_shell_route_initial_location_example.dart';
// **************************************************************************
// GoRouterGenerator
// **************************************************************************
List<RouteBase> get $appRoutes => [
$mainShellRouteData,
];
RouteBase get $mainShellRouteData => StatefulShellRouteData.$route(
factory: $MainShellRouteDataExtension._fromState,
branches: [
StatefulShellBranchData.$branch(
routes: [
GoRouteData.$route(
path: '/home',
factory: $HomeRouteDataExtension._fromState,
),
],
),
StatefulShellBranchData.$branch(
initialLocation: NotificationsShellBranchData.$initialLocation,
routes: [
GoRouteData.$route(
path: '/notifications/:section',
factory: $NotificationsRouteDataExtension._fromState,
),
],
),
StatefulShellBranchData.$branch(
routes: [
GoRouteData.$route(
path: '/orders',
factory: $OrdersRouteDataExtension._fromState,
),
],
),
],
);
extension $MainShellRouteDataExtension on MainShellRouteData {
static MainShellRouteData _fromState(GoRouterState state) =>
const MainShellRouteData();
}
extension $HomeRouteDataExtension on HomeRouteData {
static HomeRouteData _fromState(GoRouterState state) => const HomeRouteData();
String get location => GoRouteData.$location(
'/home',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $NotificationsRouteDataExtension on NotificationsRouteData {
static NotificationsRouteData _fromState(GoRouterState state) =>
NotificationsRouteData(
section: _$NotificationsPageSectionEnumMap
._$fromName(state.pathParameters['section']!),
);
String get location => GoRouteData.$location(
'/notifications/${Uri.encodeComponent(_$NotificationsPageSectionEnumMap[section]!)}',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
const _$NotificationsPageSectionEnumMap = {
NotificationsPageSection.latest: 'latest',
NotificationsPageSection.old: 'old',
NotificationsPageSection.archive: 'archive',
};
extension $OrdersRouteDataExtension on OrdersRouteData {
static OrdersRouteData _fromState(GoRouterState state) =>
const OrdersRouteData();
String get location => GoRouteData.$location(
'/orders',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension<T extends Enum> on Map<T, String> {
T _$fromName(String value) =>
entries.singleWhere((element) => element.value == value).key;
}
| packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart/0 | {'file_path': 'packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart', 'repo_id': 'packages', 'token_count': 1278} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:go_router_builder/src/path_utils.dart';
import 'package:test/test.dart';
void main() {
group('pathParametersFromPattern', () {
test('It should return the parameters of the path', () {
expect(pathParametersFromPattern('/'), const <String>{});
expect(pathParametersFromPattern('/user'), const <String>{});
expect(pathParametersFromPattern('/user/:id'), const <String>{'id'});
expect(pathParametersFromPattern('/user/:id/book'), const <String>{'id'});
expect(
pathParametersFromPattern('/user/:id/book/:bookId'),
const <String>{'id', 'bookId'},
);
});
});
group('patternToPath', () {
test('It should replace the path parameters with their values', () {
expect(patternToPath('/', const <String, String>{}), '/');
expect(patternToPath('/user', const <String, String>{}), '/user');
expect(
patternToPath('/user/:id', const <String, String>{'id': 'user-id'}),
'/user/user-id');
expect(
patternToPath(
'/user/:id/book', const <String, String>{'id': 'user-id'}),
'/user/user-id/book');
expect(
patternToPath('/user/:id/book/:bookId',
const <String, String>{'id': 'user-id', 'bookId': 'book-id'}),
'/user/user-id/book/book-id',
);
});
});
}
| packages/packages/go_router_builder/test/path_utils_test.dart/0 | {'file_path': 'packages/packages/go_router_builder/test/path_utils_test.dart', 'repo_id': 'packages', 'token_count': 609} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('browser') // Uses package:web
library;
import 'package:google_identity_services_web/loader.dart';
import 'package:test/test.dart';
import 'package:web/web.dart' as web;
import 'tools.dart';
// NOTE: This file needs to be separated from the others because Content
// Security Policies can never be *relaxed* once set.
//
// In order to not introduce a dependency in the order of the tests, we split
// them in different files, depending on the strictness of their CSP:
//
// * js_loader_test.dart : default TT configuration (not enforced)
// * js_loader_tt_custom_test.dart : TT are customized, but allowed
// * js_loader_tt_forbidden_test.dart: TT are completely disallowed
void main() {
group('loadWebSdk (TrustedTypes configured)', () {
final web.HTMLDivElement target =
web.document.createElement('div') as web.HTMLDivElement;
injectMetaTag(<String, String>{
'http-equiv': 'Content-Security-Policy',
'content': "trusted-types my-custom-policy-name 'allow-duplicates';",
});
test('Wrong policy name: Fail with TrustedTypesException', () {
expect(() {
loadWebSdk(target: target);
}, throwsA(isA<TrustedTypesException>()));
});
test('Correct policy name: Completes', () {
final Future<void> done = loadWebSdk(
target: target,
trustedTypePolicyName: 'my-custom-policy-name',
);
expect(done, isA<Future<void>>());
});
});
}
| packages/packages/google_identity_services_web/test/js_loader_tt_custom_test.dart/0 | {'file_path': 'packages/packages/google_identity_services_web/test/js_loader_tt_custom_test.dart', 'repo_id': 'packages', 'token_count': 547} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'fake_google_maps_flutter_platform.dart';
Widget _mapWithPolylines(Set<Polyline> polylines) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
polylines: polylines,
),
);
}
void main() {
late FakeGoogleMapsFlutterPlatform platform;
setUp(() {
platform = FakeGoogleMapsFlutterPlatform();
GoogleMapsFlutterPlatform.instance = platform;
});
testWidgets('Initializing a polyline', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToAdd.length, 1);
final Polyline initializedPolyline =
map.polylineUpdates.last.polylinesToAdd.first;
expect(initializedPolyline, equals(p1));
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true);
});
testWidgets('Adding a polyline', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2'));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToAdd.length, 1);
final Polyline addedPolyline =
map.polylineUpdates.last.polylinesToAdd.first;
expect(addedPolyline, equals(p2));
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true);
});
testWidgets('Removing a polyline', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylineIdsToRemove.length, 1);
expect(map.polylineUpdates.last.polylineIdsToRemove.first,
equals(p1.polylineId));
expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('Updating a polyline', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 =
Polyline(polylineId: PolylineId('polyline_1'), geodesic: true);
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange.length, 1);
expect(map.polylineUpdates.last.polylinesToChange.first, equals(p2));
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('Updating a polyline', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 =
Polyline(polylineId: PolylineId('polyline_1'), geodesic: true);
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange.length, 1);
final Polyline update = map.polylineUpdates.last.polylinesToChange.first;
expect(update, equals(p2));
expect(update.geodesic, true);
});
testWidgets('Mutate a polyline', (WidgetTester tester) async {
final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)];
final Polyline p1 = Polyline(
polylineId: const PolylineId('polyline_1'),
points: points,
);
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
p1.points.add(const LatLng(1.0, 1.0));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange.length, 1);
expect(map.polylineUpdates.last.polylinesToChange.first, equals(p1));
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1'));
Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2'));
final Set<Polyline> prev = <Polyline>{p1, p2};
p1 = const Polyline(polylineId: PolylineId('polyline_1'), visible: false);
p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true);
final Set<Polyline> cur = <Polyline>{p1, p2};
await tester.pumpWidget(_mapWithPolylines(prev));
await tester.pumpWidget(_mapWithPolylines(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange, cur);
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2'));
const Polyline p3 = Polyline(polylineId: PolylineId('polyline_3'));
final Set<Polyline> prev = <Polyline>{p2, p3};
// p1 is added, p2 is updated, p3 is removed.
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true);
final Set<Polyline> cur = <Polyline>{p1, p2};
await tester.pumpWidget(_mapWithPolylines(prev));
await tester.pumpWidget(_mapWithPolylines(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange.length, 1);
expect(map.polylineUpdates.last.polylinesToAdd.length, 1);
expect(map.polylineUpdates.last.polylineIdsToRemove.length, 1);
expect(map.polylineUpdates.last.polylinesToChange.first, equals(p2));
expect(map.polylineUpdates.last.polylinesToAdd.first, equals(p1));
expect(map.polylineUpdates.last.polylineIdsToRemove.first,
equals(p3.polylineId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2'));
Polyline p3 = const Polyline(polylineId: PolylineId('polyline_3'));
final Set<Polyline> prev = <Polyline>{p1, p2, p3};
p3 = const Polyline(polylineId: PolylineId('polyline_3'), geodesic: true);
final Set<Polyline> cur = <Polyline>{p1, p2, p3};
await tester.pumpWidget(_mapWithPolylines(prev));
await tester.pumpWidget(_mapWithPolylines(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange, <Polyline>{p3});
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1'));
final Set<Polyline> prev = <Polyline>{p1};
p1 = Polyline(polylineId: const PolylineId('polyline_1'), onTap: () {});
final Set<Polyline> cur = <Polyline>{p1};
await tester.pumpWidget(_mapWithPolylines(prev));
await tester.pumpWidget(_mapWithPolylines(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true);
expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true);
});
testWidgets('multi-update with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1'));
const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2'));
const Polyline p3 =
Polyline(polylineId: PolylineId('polyline_3'), width: 1);
const Polyline p3updated =
Polyline(polylineId: PolylineId('polyline_3'), width: 2);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p3}));
await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polylineUpdates.length, 3);
expect(map.polylineUpdates[0].polylinesToChange.isEmpty, true);
expect(map.polylineUpdates[0].polylinesToAdd, <Polyline>{p1, p2});
expect(map.polylineUpdates[0].polylineIdsToRemove.isEmpty, true);
expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true);
expect(map.polylineUpdates[1].polylinesToAdd, <Polyline>{p3});
expect(map.polylineUpdates[1].polylineIdsToRemove,
<PolylineId>{p2.polylineId});
expect(map.polylineUpdates[2].polylinesToChange, <Polyline>{p3updated});
expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true);
expect(map.polylineUpdates[2].polylineIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
}
| packages/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart', 'repo_id': 'packages', 'token_count': 3736} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
// #docregion DisplayMode
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
void main() {
// Require Hybrid Composition mode on Android.
final GoogleMapsFlutterPlatform mapsImplementation =
GoogleMapsFlutterPlatform.instance;
if (mapsImplementation is GoogleMapsFlutterAndroid) {
// Force Hybrid Composition mode.
mapsImplementation.useAndroidViewSurface = true;
}
// #enddocregion DisplayMode
runApp(const MyApp());
// #docregion DisplayMode
}
// #enddocregion DisplayMode
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// #docregion MapRenderer
AndroidMapRenderer mapRenderer = AndroidMapRenderer.platformDefault;
// #enddocregion MapRenderer
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('README snippet app'),
),
body: const Text('See example in main.dart'),
),
);
}
Future<void> initializeLatestMapRenderer() async {
// #docregion MapRenderer
final GoogleMapsFlutterPlatform mapsImplementation =
GoogleMapsFlutterPlatform.instance;
if (mapsImplementation is GoogleMapsFlutterAndroid) {
WidgetsFlutterBinding.ensureInitialized();
mapRenderer = await mapsImplementation
.initializeWithRenderer(AndroidMapRenderer.latest);
}
// #enddocregion MapRenderer
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart', 'repo_id': 'packages', 'token_count': 628} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/src/types/tile_overlay.dart';
import 'package:google_maps_flutter_platform_interface/src/types/tile_overlay_updates.dart';
import 'package:google_maps_flutter_platform_interface/src/types/utils/tile_overlay.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('tile overlay updates tests', () {
test('Correctly set toRemove, toAdd and toChange', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
final Set<TileOverlayId> toRemove = <TileOverlayId>{
const TileOverlayId('id1')
};
expect(updates.tileOverlayIdsToRemove, toRemove);
final Set<TileOverlay> toAdd = <TileOverlay>{to4};
expect(updates.tileOverlaysToAdd, toAdd);
final Set<TileOverlay> toChange = <TileOverlay>{to3Changed};
expect(updates.tileOverlaysToChange, toChange);
});
test('toJson', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
final Object json = updates.toJson();
expect(json, <String, Object>{
'tileOverlaysToAdd': serializeTileOverlaySet(updates.tileOverlaysToAdd),
'tileOverlaysToChange':
serializeTileOverlaySet(updates.tileOverlaysToChange),
'tileOverlayIdsToRemove': updates.tileOverlayIdsToRemove
.map<String>((TileOverlayId m) => m.value)
.toList()
});
});
test('equality', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current1 = <TileOverlay>{to2, to3Changed, to4};
final Set<TileOverlay> current2 = <TileOverlay>{to2, to3Changed, to4};
final Set<TileOverlay> current3 = <TileOverlay>{to2, to4};
final TileOverlayUpdates updates1 =
TileOverlayUpdates.from(previous, current1);
final TileOverlayUpdates updates2 =
TileOverlayUpdates.from(previous, current2);
final TileOverlayUpdates updates3 =
TileOverlayUpdates.from(previous, current3);
expect(updates1, updates2);
expect(updates1, isNot(updates3));
});
test('hashCode', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
expect(
updates.hashCode,
Object.hash(
Object.hashAll(updates.tileOverlaysToAdd),
Object.hashAll(updates.tileOverlayIdsToRemove),
Object.hashAll(updates.tileOverlaysToChange)));
});
test('toString', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
expect(
updates.toString(),
'TileOverlayUpdates(add: ${updates.tileOverlaysToAdd}, '
'remove: ${updates.tileOverlayIdsToRemove}, '
'change: ${updates.tileOverlaysToChange})');
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart', 'repo_id': 'packages', 'token_count': 2382} |
// 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:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'
hide GoogleMapController;
import 'package:integration_test/integration_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
@GenerateNiceMocks(<MockSpec<dynamic>>[MockSpec<TileProvider>()])
import 'overlays_test.mocks.dart';
MockTileProvider neverTileProvider() {
final MockTileProvider tileProvider = MockTileProvider();
when(tileProvider.getTile(any, any, any))
.thenAnswer((_) => Completer<Tile>().future);
return tileProvider;
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('TileOverlaysController', () {
late TileOverlaysController controller;
late gmaps.GMap map;
late List<MockTileProvider> tileProviders;
late List<TileOverlay> tileOverlays;
/// Queries the current overlay map types for tiles at x = 0, y = 0, zoom =
/// 0.
void probeTiles() {
for (final gmaps.MapType? mapType in map.overlayMapTypes!.array!) {
mapType?.getTile!(gmaps.Point(0, 0), 0, html.document);
}
}
setUp(() {
controller = TileOverlaysController();
map = gmaps.GMap(html.DivElement());
controller.googleMap = map;
tileProviders = <MockTileProvider>[
for (int i = 0; i < 3; ++i) neverTileProvider()
];
tileOverlays = <TileOverlay>[
for (int i = 0; i < 3; ++i)
TileOverlay(
tileOverlayId: TileOverlayId('$i'),
tileProvider: tileProviders[i],
zIndex: i)
];
});
testWidgets('addTileOverlays', (WidgetTester tester) async {
controller.addTileOverlays(<TileOverlay>{...tileOverlays});
probeTiles();
verifyInOrder(<dynamic>[
tileProviders[0].getTile(any, any, any),
tileProviders[1].getTile(any, any, any),
tileProviders[2].getTile(any, any, any),
]);
verifyNoMoreInteractions(tileProviders[0]);
verifyNoMoreInteractions(tileProviders[1]);
verifyNoMoreInteractions(tileProviders[2]);
});
testWidgets('changeTileOverlays', (WidgetTester tester) async {
controller.addTileOverlays(<TileOverlay>{...tileOverlays});
// Set overlay 0 visiblity to false; flip z ordering of 1 and 2, leaving 1
// unchanged.
controller.changeTileOverlays(<TileOverlay>{
tileOverlays[0].copyWith(visibleParam: false),
tileOverlays[2].copyWith(zIndexParam: 0),
});
probeTiles();
verifyInOrder(<dynamic>[
tileProviders[2].getTile(any, any, any),
tileProviders[1].getTile(any, any, any),
]);
verifyZeroInteractions(tileProviders[0]);
verifyNoMoreInteractions(tileProviders[1]);
verifyNoMoreInteractions(tileProviders[2]);
// Re-enable overlay 0.
controller.changeTileOverlays(
<TileOverlay>{tileOverlays[0].copyWith(visibleParam: true)});
probeTiles();
verify(tileProviders[2].getTile(any, any, any));
verifyInOrder(<dynamic>[
tileProviders[0].getTile(any, any, any),
tileProviders[1].getTile(any, any, any),
]);
verifyNoMoreInteractions(tileProviders[0]);
verifyNoMoreInteractions(tileProviders[1]);
verifyNoMoreInteractions(tileProviders[2]);
});
testWidgets(
'updating the z index of a hidden layer does not make it visible',
(WidgetTester tester) async {
controller.addTileOverlays(<TileOverlay>{...tileOverlays});
controller.changeTileOverlays(<TileOverlay>{
tileOverlays[0].copyWith(zIndexParam: -1, visibleParam: false),
});
probeTiles();
verifyZeroInteractions(tileProviders[0]);
});
testWidgets('removeTileOverlays', (WidgetTester tester) async {
controller.addTileOverlays(<TileOverlay>{...tileOverlays});
controller.removeTileOverlays(<TileOverlayId>{
tileOverlays[0].tileOverlayId,
tileOverlays[2].tileOverlayId,
});
probeTiles();
verify(tileProviders[1].getTile(any, any, any));
verifyZeroInteractions(tileProviders[0]);
verifyZeroInteractions(tileProviders[2]);
});
testWidgets('clearTileCache', (WidgetTester tester) async {
final Completer<GoogleMapController> controllerCompleter =
Completer<GoogleMapController>();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: GoogleMap(
initialCameraPosition: const CameraPosition(
target: LatLng(43.3078, -5.6958),
zoom: 14,
),
tileOverlays: <TileOverlay>{...tileOverlays.take(2)},
onMapCreated: (GoogleMapController value) {
controllerCompleter.complete(value);
addTearDown(() => value.dispose());
},
))));
// This is needed to kick-off the rendering of the JS Map flutter widget
await tester.pump();
final GoogleMapController controller = await controllerCompleter.future;
await tester.pump();
verify(tileProviders[0].getTile(any, any, any));
verify(tileProviders[1].getTile(any, any, any));
await controller.clearTileCache(tileOverlays[0].tileOverlayId);
await tester.pump();
verify(tileProviders[0].getTile(any, any, any));
verifyNoMoreInteractions(tileProviders[1]);
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart', 'repo_id': 'packages', 'token_count': 2336} |
// 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.
part of '../google_maps_flutter_web.dart';
/// The web implementation of [GoogleMapsFlutterPlatform].
///
/// This class implements the `package:google_maps_flutter` functionality for the web.
class GoogleMapsPlugin extends GoogleMapsFlutterPlatform {
/// Registers this class as the default instance of [GoogleMapsFlutterPlatform].
static void registerWith(Registrar registrar) {
GoogleMapsFlutterPlatform.instance = GoogleMapsPlugin();
}
// A cache of map controllers by map Id.
Map<int, GoogleMapController> _mapById = <int, GoogleMapController>{};
/// Allows tests to inject controllers without going through the buildView flow.
@visibleForTesting
// ignore: use_setters_to_change_properties
void debugSetMapById(Map<int, GoogleMapController> mapById) {
_mapById = mapById;
}
// Convenience getter for a stream of events filtered by their mapId.
Stream<MapEvent<Object?>> _events(int mapId) => _map(mapId).events;
/// Retrieve a map controller by its mapId.
GoogleMapController _map(int mapId) {
final GoogleMapController? controller = _mapById[mapId];
assert(controller != null,
'Maps cannot be retrieved before calling buildView!');
return controller!;
}
@override
Future<void> init(int mapId) async {
// The internal instance of our controller is initialized eagerly in `buildView`,
// so we don't have to do anything in this method, which is left intentionally
// blank.
assert(_mapById[mapId] != null, 'Must call buildWidget before init!');
}
/// Updates the options of a given `mapId`.
///
/// This attempts to merge the new `optionsUpdate` passed in, with the previous
/// options passed to the map (in other updates, or when creating it).
@override
Future<void> updateMapConfiguration(
MapConfiguration update, {
required int mapId,
}) async {
_map(mapId).updateMapConfiguration(update);
}
/// Applies the passed in `markerUpdates` to the `mapId`.
@override
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) async {
_map(mapId).updateMarkers(markerUpdates);
}
/// Applies the passed in `polygonUpdates` to the `mapId`.
@override
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) async {
_map(mapId).updatePolygons(polygonUpdates);
}
/// Applies the passed in `polylineUpdates` to the `mapId`.
@override
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) async {
_map(mapId).updatePolylines(polylineUpdates);
}
/// Applies the passed in `circleUpdates` to the `mapId`.
@override
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) async {
_map(mapId).updateCircles(circleUpdates);
}
@override
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) async {
_map(mapId).updateTileOverlays(newTileOverlays);
}
@override
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) async {
_map(mapId).clearTileCache(tileOverlayId);
}
/// Applies the given `cameraUpdate` to the current viewport (with animation).
@override
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {
return moveCamera(cameraUpdate, mapId: mapId);
}
/// Applies the given `cameraUpdate` to the current viewport.
@override
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {
return _map(mapId).moveCamera(cameraUpdate);
}
/// Sets the passed-in `mapStyle` to the map.
///
/// This function just adds a 'styles' option to the current map options.
///
/// Subsequent calls to this method override previous calls, you need to
/// pass full styles.
@override
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) async {
_map(mapId).updateStyles(_mapStyles(mapStyle));
}
/// Returns the bounds of the current viewport.
@override
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) {
return _map(mapId).getVisibleRegion();
}
/// Returns the screen coordinate (in pixels) of a given `latLng`.
@override
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) {
return _map(mapId).getScreenCoordinate(latLng);
}
/// Returns the [LatLng] of a [ScreenCoordinate] of the viewport.
@override
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) {
return _map(mapId).getLatLng(screenCoordinate);
}
/// Shows the [InfoWindow] (if any) of the [Marker] identified by `markerId`.
///
/// See also:
/// * [hideMarkerInfoWindow] to hide the info window.
/// * [isMarkerInfoWindowShown] to check if the info window is visible/hidden.
@override
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {
_map(mapId).showInfoWindow(markerId);
}
/// Hides the [InfoWindow] (if any) of the [Marker] identified by `markerId`.
///
/// See also:
/// * [showMarkerInfoWindow] to show the info window.
/// * [isMarkerInfoWindowShown] to check if the info window is shown.
@override
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {
_map(mapId).hideInfoWindow(markerId);
}
/// Returns true if the [InfoWindow] of the [Marker] identified by `markerId` is shown.
///
/// See also:
/// * [showMarkerInfoWindow] to show the info window.
/// * [hideMarkerInfoWindow] to hide the info window.
@override
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) async {
return _map(mapId).isInfoWindowShown(markerId);
}
/// Returns the zoom level of the `mapId`.
@override
Future<double> getZoomLevel({
required int mapId,
}) {
return _map(mapId).getZoomLevel();
}
// The following are the 11 possible streams of data from the native side
// into the plugin
@override
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
return _events(mapId).whereType<CameraMoveStartedEvent>();
}
@override
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
return _events(mapId).whereType<CameraMoveEvent>();
}
@override
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
return _events(mapId).whereType<CameraIdleEvent>();
}
@override
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
return _events(mapId).whereType<MarkerTapEvent>();
}
@override
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
return _events(mapId).whereType<InfoWindowTapEvent>();
}
@override
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
return _events(mapId).whereType<MarkerDragStartEvent>();
}
@override
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
return _events(mapId).whereType<MarkerDragEvent>();
}
@override
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
return _events(mapId).whereType<MarkerDragEndEvent>();
}
@override
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
return _events(mapId).whereType<PolylineTapEvent>();
}
@override
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
return _events(mapId).whereType<PolygonTapEvent>();
}
@override
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
return _events(mapId).whereType<CircleTapEvent>();
}
@override
Stream<MapTapEvent> onTap({required int mapId}) {
return _events(mapId).whereType<MapTapEvent>();
}
@override
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
return _events(mapId).whereType<MapLongPressEvent>();
}
/// Disposes of the current map. It can't be used afterwards!
@override
void dispose({required int mapId}) {
_map(mapId).dispose();
_mapById.remove(mapId);
}
@override
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) {
// Bail fast if we've already rendered this map ID...
if (_mapById[creationId]?.widget != null) {
return _mapById[creationId]!.widget!;
}
final StreamController<MapEvent<Object?>> controller =
StreamController<MapEvent<Object?>>.broadcast();
final GoogleMapController mapController = GoogleMapController(
mapId: creationId,
streamController: controller,
widgetConfiguration: widgetConfiguration,
mapObjects: mapObjects,
mapConfiguration: mapConfiguration,
)..init(); // Initialize the controller
_mapById[creationId] = mapController;
mapController.events
.whereType<WebMapReadyEvent>()
.first
.then((WebMapReadyEvent event) {
assert(creationId == event.mapId,
'Received WebMapReadyEvent for the wrong map');
// Notify the plugin now that there's a fully initialized controller.
onPlatformViewCreated.call(event.mapId);
});
assert(mapController.widget != null,
'The widget of a GoogleMapController cannot be null before calling dispose on it.');
return mapController.widget!;
}
/// Populates [GoogleMapsFlutterInspectorPlatform.instance] to allow
/// inspecting the platform map state.
@override
void enableDebugInspection() {
GoogleMapsInspectorPlatform.instance = GoogleMapsInspectorWeb(
(int mapId) => _map(mapId).configuration,
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart', 'repo_id': 'packages', 'token_count': 3349} |
// Mocks generated by Mockito 5.4.4 from annotations
// in google_sign_in_ios/test/google_sign_in_ios_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:google_sign_in_ios/src/messages.g.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeUserData_0 extends _i1.SmartFake implements _i2.UserData {
_FakeUserData_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeTokenData_1 extends _i1.SmartFake implements _i2.TokenData {
_FakeTokenData_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [GoogleSignInApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi {
MockGoogleSignInApi() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> init(_i2.InitParams? arg_params) => (super.noSuchMethod(
Invocation.method(
#init,
[arg_params],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<_i2.UserData> signInSilently() => (super.noSuchMethod(
Invocation.method(
#signInSilently,
[],
),
returnValue: _i3.Future<_i2.UserData>.value(_FakeUserData_0(
this,
Invocation.method(
#signInSilently,
[],
),
)),
) as _i3.Future<_i2.UserData>);
@override
_i3.Future<_i2.UserData> signIn() => (super.noSuchMethod(
Invocation.method(
#signIn,
[],
),
returnValue: _i3.Future<_i2.UserData>.value(_FakeUserData_0(
this,
Invocation.method(
#signIn,
[],
),
)),
) as _i3.Future<_i2.UserData>);
@override
_i3.Future<_i2.TokenData> getAccessToken() => (super.noSuchMethod(
Invocation.method(
#getAccessToken,
[],
),
returnValue: _i3.Future<_i2.TokenData>.value(_FakeTokenData_1(
this,
Invocation.method(
#getAccessToken,
[],
),
)),
) as _i3.Future<_i2.TokenData>);
@override
_i3.Future<void> signOut() => (super.noSuchMethod(
Invocation.method(
#signOut,
[],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<void> disconnect() => (super.noSuchMethod(
Invocation.method(
#disconnect,
[],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<bool> isSignedIn() => (super.noSuchMethod(
Invocation.method(
#isSignedIn,
[],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
@override
_i3.Future<bool> requestScopes(List<String?>? arg_scopes) =>
(super.noSuchMethod(
Invocation.method(
#requestScopes,
[arg_scopes],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
}
| packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart/0 | {'file_path': 'packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart', 'repo_id': 'packages', 'token_count': 1911} |
// 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:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'src/messages.g.dart';
// Converts an [ImageSource] to the corresponding Pigeon API enum value.
SourceType _convertSource(ImageSource source) {
switch (source) {
case ImageSource.camera:
return SourceType.camera;
case ImageSource.gallery:
return SourceType.gallery;
}
// The enum comes from a different package, which could get a new value at
// any time, so a fallback case is necessary. Since there is no reasonable
// default behavior, throw to alert the client that they need an updated
// version. This is deliberately outside the switch rather than a `default`
// so that the linter will flag the switch as needing an update.
// ignore: dead_code
throw UnimplementedError('Unknown source: $source');
}
// Converts a [CameraDevice] to the corresponding Pigeon API enum value.
SourceCamera _convertCamera(CameraDevice camera) {
switch (camera) {
case CameraDevice.front:
return SourceCamera.front;
case CameraDevice.rear:
return SourceCamera.rear;
}
// The enum comes from a different package, which could get a new value at
// any time, so a fallback case is necessary. Since there is no reasonable
// default behavior, throw to alert the client that they need an updated
// version. This is deliberately outside the switch rather than a `default`
// so that the linter will flag the switch as needing an update.
// ignore: dead_code
throw UnimplementedError('Unknown camera: $camera');
}
/// An implementation of [ImagePickerPlatform] for iOS.
class ImagePickerIOS extends ImagePickerPlatform {
final ImagePickerApi _hostApi = ImagePickerApi();
/// Registers this class as the default platform implementation.
static void registerWith() {
ImagePickerPlatform.instance = ImagePickerIOS();
}
@override
Future<PickedFile?> pickImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) async {
final String? path = await _pickImageAsPath(
source: source,
options: ImagePickerOptions(
maxWidth: maxWidth,
maxHeight: maxHeight,
imageQuality: imageQuality,
preferredCameraDevice: preferredCameraDevice,
),
);
return path != null ? PickedFile(path) : null;
}
@override
Future<XFile?> getImageFromSource({
required ImageSource source,
ImagePickerOptions options = const ImagePickerOptions(),
}) async {
final String? path = await _pickImageAsPath(
source: source,
options: options,
);
return path != null ? XFile(path) : null;
}
@override
Future<List<PickedFile>?> pickMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) async {
final List<dynamic> paths = await _pickMultiImageAsPath(
options: MultiImagePickerOptions(
imageOptions: ImageOptions(
maxWidth: maxWidth,
maxHeight: maxHeight,
imageQuality: imageQuality,
),
),
);
// Convert an empty list to a null return since that was the legacy behavior
// of this method.
if (paths.isEmpty) {
return null;
}
return paths.map((dynamic path) => PickedFile(path as String)).toList();
}
@override
Future<List<XFile>> getMultiImageWithOptions({
MultiImagePickerOptions options = const MultiImagePickerOptions(),
}) async {
final List<String> paths = await _pickMultiImageAsPath(options: options);
return paths.map((String path) => XFile(path)).toList();
}
Future<List<String>> _pickMultiImageAsPath({
MultiImagePickerOptions options = const MultiImagePickerOptions(),
}) async {
final int? imageQuality = options.imageOptions.imageQuality;
if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) {
throw ArgumentError.value(
imageQuality, 'imageQuality', 'must be between 0 and 100');
}
final double? maxWidth = options.imageOptions.maxWidth;
if (maxWidth != null && maxWidth < 0) {
throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative');
}
final double? maxHeight = options.imageOptions.maxHeight;
if (maxHeight != null && maxHeight < 0) {
throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative');
}
// TODO(stuartmorgan): Remove the cast once Pigeon supports non-nullable
// generics, https://github.com/flutter/flutter/issues/97848
return (await _hostApi.pickMultiImage(
MaxSize(width: maxWidth, height: maxHeight),
imageQuality,
options.imageOptions.requestFullMetadata))
.cast<String>();
}
Future<String?> _pickImageAsPath({
required ImageSource source,
ImagePickerOptions options = const ImagePickerOptions(),
}) {
final int? imageQuality = options.imageQuality;
if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) {
throw ArgumentError.value(
imageQuality, 'imageQuality', 'must be between 0 and 100');
}
final double? maxHeight = options.maxHeight;
final double? maxWidth = options.maxWidth;
if (maxWidth != null && maxWidth < 0) {
throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative');
}
if (maxHeight != null && maxHeight < 0) {
throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative');
}
return _hostApi.pickImage(
SourceSpecification(
type: _convertSource(source),
camera: _convertCamera(options.preferredCameraDevice),
),
MaxSize(width: maxWidth, height: maxHeight),
imageQuality,
options.requestFullMetadata,
);
}
@override
Future<List<XFile>> getMedia({
required MediaOptions options,
}) async {
final MediaSelectionOptions mediaSelectionOptions =
_mediaOptionsToMediaSelectionOptions(options);
return (await _hostApi.pickMedia(mediaSelectionOptions))
.map((String? path) => XFile(path!))
.toList();
}
MaxSize _imageOptionsToMaxSizeWithValidation(ImageOptions imageOptions) {
final double? maxHeight = imageOptions.maxHeight;
final double? maxWidth = imageOptions.maxWidth;
final int? imageQuality = imageOptions.imageQuality;
if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) {
throw ArgumentError.value(
imageQuality, 'imageQuality', 'must be between 0 and 100');
}
if (maxWidth != null && maxWidth < 0) {
throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative');
}
if (maxHeight != null && maxHeight < 0) {
throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative');
}
return MaxSize(width: maxWidth, height: maxHeight);
}
MediaSelectionOptions _mediaOptionsToMediaSelectionOptions(
MediaOptions mediaOptions) {
final MaxSize maxSize =
_imageOptionsToMaxSizeWithValidation(mediaOptions.imageOptions);
return MediaSelectionOptions(
maxSize: maxSize,
imageQuality: mediaOptions.imageOptions.imageQuality,
requestFullMetadata: mediaOptions.imageOptions.requestFullMetadata,
allowMultiple: mediaOptions.allowMultiple,
);
}
@override
Future<PickedFile?> pickVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) async {
final String? path = await _pickVideoAsPath(
source: source,
maxDuration: maxDuration,
preferredCameraDevice: preferredCameraDevice,
);
return path != null ? PickedFile(path) : null;
}
Future<String?> _pickVideoAsPath({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) {
return _hostApi.pickVideo(
SourceSpecification(
type: _convertSource(source),
camera: _convertCamera(preferredCameraDevice)),
maxDuration?.inSeconds);
}
@override
Future<XFile?> getImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) async {
final String? path = await _pickImageAsPath(
source: source,
options: ImagePickerOptions(
maxWidth: maxWidth,
maxHeight: maxHeight,
imageQuality: imageQuality,
preferredCameraDevice: preferredCameraDevice,
),
);
return path != null ? XFile(path) : null;
}
@override
Future<List<XFile>?> getMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) async {
final List<String> paths = await _pickMultiImageAsPath(
options: MultiImagePickerOptions(
imageOptions: ImageOptions(
maxWidth: maxWidth,
maxHeight: maxHeight,
imageQuality: imageQuality,
),
),
);
// Convert an empty list to a null return since that was the legacy behavior
// of this method.
if (paths.isEmpty) {
return null;
}
return paths.map((String path) => XFile(path)).toList();
}
@override
Future<XFile?> getVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) async {
final String? path = await _pickVideoAsPath(
source: source,
maxDuration: maxDuration,
preferredCameraDevice: preferredCameraDevice,
);
return path != null ? XFile(path) : null;
}
}
| packages/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart/0 | {'file_path': 'packages/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart', 'repo_id': 'packages', 'token_count': 3369} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import './base.dart';
/// A PickedFile backed by a dart:io File.
class PickedFile extends PickedFileBase {
/// Construct a PickedFile object backed by a dart:io File.
PickedFile(super.path) : _file = File(path);
final File _file;
@override
String get path {
return _file.path;
}
@override
Future<String> readAsString({Encoding encoding = utf8}) {
return _file.readAsString(encoding: encoding);
}
@override
Future<Uint8List> readAsBytes() {
return _file.readAsBytes();
}
@override
Stream<Uint8List> openRead([int? start, int? end]) {
return _file
.openRead(start ?? 0, end)
.map((List<int> chunk) => Uint8List.fromList(chunk));
}
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart/0 | {'file_path': 'packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart', 'repo_id': 'packages', 'token_count': 335} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'billing_client_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
const _$BillingResponseEnumMap = {
BillingResponse.serviceTimeout: -3,
BillingResponse.featureNotSupported: -2,
BillingResponse.serviceDisconnected: -1,
BillingResponse.ok: 0,
BillingResponse.userCanceled: 1,
BillingResponse.serviceUnavailable: 2,
BillingResponse.billingUnavailable: 3,
BillingResponse.itemUnavailable: 4,
BillingResponse.developerError: 5,
BillingResponse.error: 6,
BillingResponse.itemAlreadyOwned: 7,
BillingResponse.itemNotOwned: 8,
BillingResponse.networkError: 12,
};
const _$ProductTypeEnumMap = {
ProductType.inapp: 'inapp',
ProductType.subs: 'subs',
};
const _$ProrationModeEnumMap = {
ProrationMode.unknownSubscriptionUpgradeDowngradePolicy: 0,
ProrationMode.immediateWithTimeProration: 1,
ProrationMode.immediateAndChargeProratedPrice: 2,
ProrationMode.immediateWithoutProration: 3,
ProrationMode.deferred: 4,
ProrationMode.immediateAndChargeFullPrice: 5,
};
const _$BillingClientFeatureEnumMap = {
BillingClientFeature.inAppItemsOnVR: 'inAppItemsOnVr',
BillingClientFeature.priceChangeConfirmation: 'priceChangeConfirmation',
BillingClientFeature.productDetails: 'fff',
BillingClientFeature.subscriptions: 'subscriptions',
BillingClientFeature.subscriptionsOnVR: 'subscriptionsOnVr',
BillingClientFeature.subscriptionsUpdate: 'subscriptionsUpdate',
};
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart/0 | {'file_path': 'packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart', 'repo_id': 'packages', 'token_count': 496} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:ios_platform_images/ios_platform_images.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('resolves URL', (WidgetTester _) async {
final String? path = await IosPlatformImages.resolveURL('textfile');
expect(Uri.parse(path!).scheme, 'file');
expect(path.contains('Runner.app'), isTrue);
});
testWidgets('loads image', (WidgetTester _) async {
final Completer<bool> successCompleter = Completer<bool>();
final ImageProvider<Object> provider = IosPlatformImages.load('flutter');
final ImageStream imageStream = provider.resolve(ImageConfiguration.empty);
imageStream.addListener(
ImageStreamListener((ImageInfo image, bool synchronousCall) {
successCompleter.complete(true);
}, onError: (Object e, StackTrace? _) {
successCompleter.complete(false);
}));
final bool succeeded = await successCompleter.future;
expect(succeeded, true);
});
}
| packages/packages/ios_platform_images/example/integration_test/ios_platform_images_test.dart/0 | {'file_path': 'packages/packages/ios_platform_images/example/integration_test/ios_platform_images_test.dart', 'repo_id': 'packages', 'token_count': 429} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'package:googleapis/storage/v1.dart';
/// Global (in terms of earth) mutex using Google Cloud Storage.
class GcsLock {
/// Create a lock with an authenticated client and a GCS bucket name.
///
/// The client is used to communicate with Google Cloud Storage APIs.
GcsLock(this._api, this._bucketName);
/// Create a temporary lock file in GCS, and use it as a mutex mechanism to
/// run a piece of code exclusively.
///
/// There must be no existing lock file with the same name in order to
/// proceed. If multiple [GcsLock]s with the same `bucketName` and
/// `lockFileName` try [protectedRun] simultaneously, only one will proceed
/// and create the lock file. All others will be blocked.
///
/// When [protectedRun] finishes, the lock file is deleted, and other blocked
/// [protectedRun] may proceed.
///
/// If the lock file is stuck (e.g., `_unlock` is interrupted unexpectedly),
/// one may need to manually delete the lock file from GCS to unblock any
/// [protectedRun] that may depend on it.
Future<void> protectedRun(
String lockFileName, Future<void> Function() f) async {
await _lock(lockFileName);
try {
await f();
} catch (e, stacktrace) {
print(stacktrace);
rethrow;
} finally {
await _unlock(lockFileName);
}
}
Future<void> _lock(String lockFileName) async {
final Object object = Object();
object.bucket = _bucketName;
object.name = lockFileName;
final Media content = Media(const Stream<List<int>>.empty(), 0);
Duration waitPeriod = const Duration(milliseconds: 10);
bool locked = false;
while (!locked) {
try {
await _api.objects.insert(object, _bucketName,
ifGenerationMatch: '0', uploadMedia: content);
locked = true;
} on DetailedApiRequestError catch (e) {
if (e.status == 412) {
// Status 412 means that the lock file already exists. Wait until
// that lock file is deleted.
await Future<void>.delayed(waitPeriod);
waitPeriod *= 2;
if (waitPeriod >= _kWarningThreshold) {
print(
'The lock is waiting for a long time: $waitPeriod. '
'If the lock file $lockFileName in bucket $_bucketName '
'seems to be stuck (i.e., it was created a long time ago and '
'no one seems to be owning it currently), delete it manually '
'to unblock this.',
);
}
} else {
rethrow;
}
}
}
}
Future<void> _unlock(String lockFileName) async {
Duration waitPeriod = const Duration(milliseconds: 10);
bool unlocked = false;
// Retry in the case of GCS returning an API error, but rethrow if unable
// to unlock after a certain period of time.
while (!unlocked) {
try {
await _api.objects.delete(_bucketName, lockFileName);
unlocked = true;
} on DetailedApiRequestError {
if (waitPeriod < _unlockThreshold) {
await Future<void>.delayed(waitPeriod);
waitPeriod *= 2;
} else {
rethrow;
}
}
}
}
final String _bucketName;
final StorageApi _api;
static const Duration _kWarningThreshold = Duration(seconds: 10);
static const Duration _unlockThreshold = Duration(minutes: 1);
}
| packages/packages/metrics_center/lib/src/gcs_lock.dart/0 | {'file_path': 'packages/packages/metrics_center/lib/src/gcs_lock.dart', 'repo_id': 'packages', 'token_count': 1320} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
// Support code to generate the hex-lists in test/decode_test.dart from
// a hex-stream.
import 'dart:io';
void formatHexStream(String hexStream) {
String s = '';
for (int i = 0; i < hexStream.length / 2; i++) {
if (s.isNotEmpty) {
s += ', ';
}
s += '0x';
final String x = hexStream.substring(i * 2, i * 2 + 2);
s += x;
if (((i + 1) % 8) == 0) {
s += ',';
print(s);
s = '';
}
}
if (s.isNotEmpty) {
print(s);
}
}
// Support code for generating the hex-lists in test/decode_test.dart.
void hexDumpList(List<int> package) {
String s = '';
for (int i = 0; i < package.length; i++) {
if (s.isNotEmpty) {
s += ', ';
}
s += '0x';
final String x = package[i].toRadixString(16);
if (x.length == 1) {
s += '0';
}
s += x;
if (((i + 1) % 8) == 0) {
s += ',';
print(s);
s = '';
}
}
if (s.isNotEmpty) {
print(s);
}
}
void dumpDatagram(Datagram datagram) {
String toHex(List<int> ints) {
final StringBuffer buffer = StringBuffer();
for (int i = 0; i < ints.length; i++) {
buffer.write(ints[i].toRadixString(16).padLeft(2, '0'));
if ((i + 1) % 10 == 0) {
buffer.writeln();
} else {
buffer.write(' ');
}
}
return buffer.toString();
}
print('${datagram.address.address}:${datagram.port}:');
print(toHex(datagram.data));
print('');
}
| packages/packages/multicast_dns/tool/packet_gen.dart/0 | {'file_path': 'packages/packages/multicast_dns/tool/packet_gen.dart', 'repo_id': 'packages', 'token_count': 730} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/path_provider/path_provider_android/example/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/path_provider/path_provider_android/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
name: pigeon_example_app
description: An example of using Pigeon in an application.
publish_to: 'none'
version: 1.0.0
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
build_runner: ^2.1.10
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
# When depending on this package from a real application you should use:
# file_selector_windows: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
pigeon:
path: ../../
flutter:
uses-material-design: true
| packages/packages/pigeon/example/app/pubspec.yaml/0 | {'file_path': 'packages/packages/pigeon/example/app/pubspec.yaml', 'repo_id': 'packages', 'token_count': 258} |
// 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 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
export 'cpp_generator.dart' show CppOptions;
export 'dart_generator.dart' show DartOptions;
export 'java_generator.dart' show JavaOptions;
export 'kotlin_generator.dart' show KotlinOptions;
export 'objc_generator.dart' show ObjcOptions;
export 'pigeon_lib.dart';
export 'swift_generator.dart' show SwiftOptions;
| packages/packages/pigeon/lib/pigeon.dart/0 | {'file_path': 'packages/packages/pigeon/lib/pigeon.dart', 'repo_id': 'packages', 'token_count': 182} |
name: alternate_language_test_plugin
description: Pigeon test harness for alternate plugin languages.
version: 0.0.1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
flutter:
plugin:
platforms:
android:
package: com.example.alternate_language_test_plugin
pluginClass: AlternateLanguageTestPlugin
ios:
pluginClass: AlternateLanguageTestPlugin
macos:
pluginClass: AlternateLanguageTestPlugin
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml/0 | {'file_path': 'packages/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml', 'repo_id': 'packages', 'token_count': 226} |
// 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:platform/platform.dart';
/// This sample app shows the platform details of the device it is running on.
void main() => runApp(const MyApp());
/// The main app.
class MyApp extends StatelessWidget {
/// Constructs a [MyApp]
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const LocalPlatform platform = LocalPlatform();
return MaterialApp(
title: 'Platform Example',
home: Scaffold(
appBar: AppBar(
title: const Text('Platform Example'),
),
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FormatDetails(
title: 'Operating System:',
value: platform.operatingSystem,
),
FormatDetails(
title: 'Number of Processors:',
value: platform.numberOfProcessors.toString(),
),
FormatDetails(
title: 'Path Separator:',
value: platform.pathSeparator,
),
FormatDetails(
title: 'Local Hostname:',
value: platform.localHostname,
),
FormatDetails(
title: 'Environment:',
value: platform.environment.toString(),
),
FormatDetails(
title: 'Executable:',
value: platform.executable,
),
FormatDetails(
title: 'Resolved Executable:',
value: platform.resolvedExecutable,
),
FormatDetails(
title: 'Script:',
value: platform.script.toString(),
),
FormatDetails(
title: 'Executable Arguments:',
value: platform.executableArguments.toString(),
),
FormatDetails(
title: 'Package Config:',
value: platform.packageConfig.toString(),
),
FormatDetails(
title: 'Version:',
value: platform.version,
),
FormatDetails(
title: 'Stdin Supports ANSI:',
value: platform.stdinSupportsAnsi.toString(),
),
FormatDetails(
title: 'Stdout Supports ANSI:',
value: platform.stdoutSupportsAnsi.toString(),
),
FormatDetails(
title: 'Locale Name:',
value: platform.localeName,
),
FormatDetails(
title: 'isAndroid:',
value: platform.isAndroid.toString(),
),
FormatDetails(
title: 'isFuchsia:',
value: platform.isFuchsia.toString(),
),
FormatDetails(
title: 'isIOS:',
value: platform.isIOS.toString(),
),
FormatDetails(
title: 'isLinux:',
value: platform.isLinux.toString(),
),
FormatDetails(
title: 'isMacOS:',
value: platform.isMacOS.toString(),
),
FormatDetails(
title: 'isWindows:',
value: platform.isWindows.toString(),
),
],
),
),
),
),
);
}
}
/// A widget to format the details.
class FormatDetails extends StatelessWidget {
/// Constructs a [FormatDetails].
const FormatDetails({
super.key,
required this.title,
required this.value,
});
/// The title of the field.
final String title;
/// The value of the field.
final String value;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(
title,
style: Theme.of(context).textTheme.titleLarge,
),
Text(value),
const SizedBox(height: 20),
],
);
}
}
| packages/packages/platform/example/lib/main.dart/0 | {'file_path': 'packages/packages/platform/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 2418} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.