text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2019 The Flutter team. 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:dual_screen/dual_screen.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart' show timeDilation; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:flutter_localized_locales/flutter_localized_locales.dart'; import 'package:gallery/constants.dart'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/pages/backdrop.dart'; import 'package:gallery/pages/splash.dart'; import 'package:gallery/routes.dart'; import 'package:gallery/themes/gallery_theme_data.dart'; import 'package:get_storage/get_storage.dart'; import 'package:google_fonts/google_fonts.dart'; import 'layout/adaptive.dart'; export 'package:gallery/data/demos.dart' show pumpDeferredLibraries; void main() async { GoogleFonts.config.allowRuntimeFetching = false; await GetStorage.init(); runApp(const GalleryApp()); } class GalleryApp extends StatelessWidget { const GalleryApp({ super.key, this.initialRoute, this.isTestMode = false, }); final String? initialRoute; final bool isTestMode; @override Widget build(BuildContext context) { return ModelBinding( initialModel: GalleryOptions( themeMode: ThemeMode.system, textScaleFactor: systemTextScaleFactorOption, customTextDirection: CustomTextDirection.localeBased, locale: null, timeDilation: timeDilation, platform: defaultTargetPlatform, isTestMode: isTestMode, ), child: Builder( builder: (context) { final options = GalleryOptions.of(context); final hasHinge = MediaQuery.of(context).hinge?.bounds != null; return MaterialApp( restorationScopeId: 'rootGallery', title: 'Flutter Gallery', debugShowCheckedModeBanner: false, themeMode: options.themeMode, theme: GalleryThemeData.lightThemeData.copyWith( platform: options.platform, ), darkTheme: GalleryThemeData.darkThemeData.copyWith( platform: options.platform, ), localizationsDelegates: const [ ...GalleryLocalizations.localizationsDelegates, LocaleNamesLocalizationsDelegate() ], initialRoute: initialRoute, supportedLocales: GalleryLocalizations.supportedLocales, locale: options.locale, localeListResolutionCallback: (locales, supportedLocales) { deviceLocale = locales?.first; return basicLocaleListResolution(locales, supportedLocales); }, onGenerateRoute: (settings) => RouteConfiguration.onGenerateRoute(settings, hasHinge), ); }, ), ); } } class RootPage extends StatelessWidget { const RootPage({ super.key, }); @override Widget build(BuildContext context) { return ApplyTextOptions( child: SplashPage( child: Backdrop( isDesktop: isDisplayDesktop(context), ), ), ); } }
gallery/lib/main.dart/0
{ "file_path": "gallery/lib/main.dart", "repo_id": "gallery", "token_count": 1309 }
871
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; const cranePurple700 = Color(0xFF720D5D); const cranePurple800 = Color(0xFF5D1049); const cranePurple900 = Color(0xFF4E0D3A); const craneRed700 = Color(0xFFE30425); const craneWhite60 = Color(0x99FFFFFF); const cranePrimaryWhite = Color(0xFFFFFFFF); const craneErrorOrange = Color(0xFFFF9100); const craneAlpha = Color(0x00FFFFFF); const craneGrey = Color(0xFF747474); const craneBlack = Color(0xFF1E252D);
gallery/lib/studies/crane/colors.dart/0
{ "file_path": "gallery/lib/studies/crane/colors.dart", "repo_id": "gallery", "token_count": 210 }
872
// Copyright 2019 The Flutter team. 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:math' as math; import 'package:flutter/material.dart'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/layout/letter_spacing.dart'; import 'package:gallery/layout/text_scale.dart'; import 'package:gallery/studies/rally/colors.dart'; import 'package:gallery/studies/rally/data.dart'; import 'package:gallery/studies/rally/formatters.dart'; /// A colored piece of the [RallyPieChart]. class RallyPieChartSegment { const RallyPieChartSegment({ required this.color, required this.value, }); final Color color; final double value; } /// The max height and width of the [RallyPieChart]. const pieChartMaxSize = 500.0; List<RallyPieChartSegment> buildSegmentsFromAccountItems( List<AccountData> items) { return List<RallyPieChartSegment>.generate( items.length, (i) { return RallyPieChartSegment( color: RallyColors.accountColor(i), value: items[i].primaryAmount, ); }, ); } List<RallyPieChartSegment> buildSegmentsFromBillItems(List<BillData> items) { return List<RallyPieChartSegment>.generate( items.length, (i) { return RallyPieChartSegment( color: RallyColors.billColor(i), value: items[i].primaryAmount, ); }, ); } List<RallyPieChartSegment> buildSegmentsFromBudgetItems( List<BudgetData> items) { return List<RallyPieChartSegment>.generate( items.length, (i) { return RallyPieChartSegment( color: RallyColors.budgetColor(i), value: items[i].primaryAmount - items[i].amountUsed, ); }, ); } /// An animated circular pie chart to represent pieces of a whole, which can /// have empty space. class RallyPieChart extends StatefulWidget { const RallyPieChart({ super.key, required this.heroLabel, required this.heroAmount, required this.wholeAmount, required this.segments, }); final String heroLabel; final double heroAmount; final double wholeAmount; final List<RallyPieChartSegment> segments; @override State<RallyPieChart> createState() => _RallyPieChartState(); } class _RallyPieChartState extends State<RallyPieChart> with SingleTickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 600), vsync: this, ); animation = CurvedAnimation( parent: TweenSequence<double>(<TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: 0), weight: 1, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: 1), weight: 1.5, ), ]).animate(controller), curve: Curves.decelerate); controller.forward(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MergeSemantics( child: _AnimatedRallyPieChart( animation: animation, centerLabel: widget.heroLabel, centerAmount: widget.heroAmount, total: widget.wholeAmount, segments: widget.segments, ), ); } } class _AnimatedRallyPieChart extends AnimatedWidget { const _AnimatedRallyPieChart({ required this.animation, required this.centerLabel, required this.centerAmount, required this.total, required this.segments, }) : super(listenable: animation); final Animation<double> animation; final String centerLabel; final double centerAmount; final double total; final List<RallyPieChartSegment> segments; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final labelTextStyle = textTheme.bodyMedium!.copyWith( fontSize: 14, letterSpacing: letterSpacingOrNone(0.5), ); return LayoutBuilder(builder: (context, constraints) { // When the widget is larger, we increase the font size. var headlineStyle = constraints.maxHeight >= pieChartMaxSize ? textTheme.headlineSmall!.copyWith(fontSize: 70) : textTheme.headlineSmall; // With a large text scale factor, we set a max font size. if (GalleryOptions.of(context).textScaleFactor(context) > 1.0) { headlineStyle = headlineStyle!.copyWith( fontSize: (headlineStyle.fontSize! / reducedTextScale(context)), ); } return DecoratedBox( decoration: _RallyPieChartOutlineDecoration( maxFraction: animation.value, total: total, segments: segments, ), child: Container( height: constraints.maxHeight, alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( centerLabel, style: labelTextStyle, ), SelectableText( usdWithSignFormat(context).format(centerAmount), style: headlineStyle, ), ], ), ), ); }); } } class _RallyPieChartOutlineDecoration extends Decoration { const _RallyPieChartOutlineDecoration({ required this.maxFraction, required this.total, required this.segments, }); final double maxFraction; final double total; final List<RallyPieChartSegment> segments; @override BoxPainter createBoxPainter([VoidCallback? onChanged]) { return _RallyPieChartOutlineBoxPainter( maxFraction: maxFraction, wholeAmount: total, segments: segments, ); } } class _RallyPieChartOutlineBoxPainter extends BoxPainter { _RallyPieChartOutlineBoxPainter({ required this.maxFraction, required this.wholeAmount, required this.segments, }); final double maxFraction; final double wholeAmount; final List<RallyPieChartSegment> segments; static const double wholeRadians = 2 * math.pi; static const double spaceRadians = wholeRadians / 180; @override void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { // Create two padded reacts to draw arcs in: one for colored arcs and one for // inner bg arc. const strokeWidth = 4.0; final outerRadius = math.min( configuration.size!.width, configuration.size!.height, ) / 2; final outerRect = Rect.fromCircle( center: configuration.size!.center(offset), radius: outerRadius - strokeWidth * 3, ); final innerRect = Rect.fromCircle( center: configuration.size!.center(offset), radius: outerRadius - strokeWidth * 4, ); // Paint each arc with spacing. var cumulativeSpace = 0.0; var cumulativeTotal = 0.0; for (final segment in segments) { final paint = Paint()..color = segment.color; final startAngle = _calculateStartAngle(cumulativeTotal, cumulativeSpace); final sweepAngle = _calculateSweepAngle(segment.value, 0); canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint); cumulativeTotal += segment.value; cumulativeSpace += spaceRadians; } // Paint any remaining space black (e.g. budget amount remaining). final remaining = wholeAmount - cumulativeTotal; if (remaining > 0) { final paint = Paint()..color = Colors.black; final startAngle = _calculateStartAngle(cumulativeTotal, spaceRadians * segments.length); final sweepAngle = _calculateSweepAngle(remaining, -spaceRadians); canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint); } // Paint a smaller inner circle to cover the painted arcs, so they are // display as segments. final bgPaint = Paint()..color = RallyColors.primaryBackground; canvas.drawArc(innerRect, 0, 2 * math.pi, true, bgPaint); } double _calculateAngle(double amount, double offset) { final wholeMinusSpacesRadians = wholeRadians - (segments.length * spaceRadians); return maxFraction * (amount / wholeAmount * wholeMinusSpacesRadians + offset); } double _calculateStartAngle(double total, double offset) => _calculateAngle(total, offset) - math.pi / 2; double _calculateSweepAngle(double total, double offset) => _calculateAngle(total, offset); }
gallery/lib/studies/rally/charts/pie_chart.dart/0
{ "file_path": "gallery/lib/studies/rally/charts/pie_chart.dart", "repo_id": "gallery", "token_count": 3241 }
873
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:gallery/layout/adaptive.dart'; import 'package:gallery/layout/image_placeholder.dart'; import 'package:gallery/studies/shrine/model/app_state_model.dart'; import 'package:gallery/studies/shrine/model/product.dart'; import 'package:intl/intl.dart'; import 'package:scoped_model/scoped_model.dart'; class MobileProductCard extends StatelessWidget { const MobileProductCard({ super.key, this.imageAspectRatio = 33 / 49, required this.product, }) : assert(imageAspectRatio > 0); final double imageAspectRatio; final Product product; static const double defaultTextBoxHeight = 65; @override Widget build(BuildContext context) { return Semantics( container: true, button: true, enabled: true, child: _buildProductCard( context: context, product: product, imageAspectRatio: imageAspectRatio, ), ); } } class DesktopProductCard extends StatelessWidget { const DesktopProductCard({ super.key, required this.product, required this.imageWidth, }); final Product product; final double imageWidth; @override Widget build(BuildContext context) { return _buildProductCard( context: context, product: product, imageWidth: imageWidth, ); } } Widget _buildProductCard({ required BuildContext context, required Product product, double? imageWidth, double? imageAspectRatio, }) { final isDesktop = isDisplayDesktop(context); // In case of desktop , imageWidth is passed through [DesktopProductCard] in // case of mobile imageAspectRatio is passed through [MobileProductCard]. // Below assert is so that correct combination should always be present. assert(isDesktop && imageWidth != null || !isDesktop && imageAspectRatio != null); final formatter = NumberFormat.simpleCurrency( decimalDigits: 0, locale: Localizations.localeOf(context).toString(), ); final theme = Theme.of(context); final imageWidget = FadeInImagePlaceholder( image: AssetImage(product.assetName, package: product.assetPackage), placeholder: Container( color: Colors.black.withOpacity(0.1), width: imageWidth, height: imageWidth == null ? null : imageWidth / product.assetAspectRatio, ), fit: BoxFit.cover, width: isDesktop ? imageWidth : null, height: isDesktop ? null : double.infinity, excludeFromSemantics: true, ); return ScopedModelDescendant<AppStateModel>( builder: (context, child, model) { return Semantics( hint: GalleryLocalizations.of(context)! .shrineScreenReaderProductAddToCart, child: MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { model.addProductToCart(product.id); }, child: child, ), ), ); }, child: Stack( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ isDesktop ? imageWidget : AspectRatio( aspectRatio: imageAspectRatio!, child: imageWidget, ), SizedBox( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(height: 23), SizedBox( width: imageWidth, child: Text( product.name(context), style: theme.textTheme.labelLarge, softWrap: true, textAlign: TextAlign.center, ), ), const SizedBox(height: 4), Text( formatter.format(product.price), style: theme.textTheme.bodySmall, ), ], ), ), ], ), const Padding( padding: EdgeInsets.all(16), child: Icon(Icons.add_shopping_cart), ), ], ), ); }
gallery/lib/studies/shrine/supplemental/product_card.dart/0
{ "file_path": "gallery/lib/studies/shrine/supplemental/product_card.dart", "repo_id": "gallery", "token_count": 1980 }
874
// Copyright 2014 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:web_benchmarks/client.dart'; import 'gallery_automator.dart'; /// A recorder that measures frame building durations for the Gallery. class GalleryRecorder extends WidgetRecorder { GalleryRecorder({ required this.benchmarkName, this.shouldRunPredicate, this.testScrollingOnly = false, }) : assert(testScrollingOnly || shouldRunPredicate != null), super(name: benchmarkName, useCustomWarmUp: true); /// The name of the gallery benchmark to be run. /// /// See `common.dart` for the list of the names of all benchmarks. final String benchmarkName; /// A function that accepts the name of a demo and returns whether we should /// run this demo in this benchmark. /// /// See `common.dart` for examples. /// /// The name of any demo has the format `<demo-name>@<demo-type>`, such as /// `progress-indicator@material`. /// A list of all demo names can be obtained using /// [allGalleryDemoDescriptions]. final bool Function(String)? shouldRunPredicate; /// Whether this benchmark only tests scrolling. final bool testScrollingOnly; GalleryAutomator? _galleryAutomator; bool get _finished => _galleryAutomator?.finished ?? false; /// Whether we should continue recording. @override bool shouldContinue() => !_finished || profile.shouldContinue(); /// Creates the [GalleryAutomator] widget. @override Widget createWidget() { _galleryAutomator = GalleryAutomator( benchmarkName: benchmarkName, shouldRunPredicate: shouldRunPredicate, testScrollsOnly: testScrollingOnly, stopWarmingUpCallback: profile.stopWarmingUp, ); return _galleryAutomator!.createWidget(); } }
gallery/test_benchmarks/benchmarks/gallery_recorder.dart/0
{ "file_path": "gallery/test_benchmarks/benchmarks/gallery_recorder.dart", "repo_id": "gallery", "token_count": 560 }
875
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="local" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="additionalArgs" value="--dart-define=ENCRYPTION_KEY=X9YTchZdcnyZTNBSBgzj29p7RMBAIubD --dart-define=ENCRYPTION_IV=FxC21ctRg9SgiXuZ --dart-define=RECAPTCHA_KEY=6LeafHolAAAAAH-kou5bR2y4gtEOmFXdd6pM4cJz --dart-define=APPCHECK_DEBUG_TOKEN=1E88A2CC-8D94-4ADC-A156-A63DBA49627D --dart-define=ALLOW_PRIVATE_MATCHES=true" /> <option name="buildFlavor" value="development" /> <option name="filePath" value="$PROJECT_DIR$/lib/main_local.dart" /> <method v="2" /> </configuration> </component>
io_flip/.idea/runConfigurations/local.xml/0
{ "file_path": "io_flip/.idea/runConfigurations/local.xml", "repo_id": "io_flip", "token_count": 281 }
876
// ignore_for_file: avoid_print import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; extension ApplicationJsonX on Map<String, String> { bool isContentTypeJson() { return this[HttpHeaders.contentTypeHeader] ?.startsWith(ContentType.json.value) ?? false; } } const methodsRequiringContentTypeJson = [ HttpMethod.post, HttpMethod.put, HttpMethod.patch, ]; Middleware contentTypeHeader() { return (handler) { return (context) async { final method = context.request.method; final headers = context.request.headers; if (methodsRequiringContentTypeJson.contains(method) && !headers.isContentTypeJson()) { final path = context.request.uri.path; final message = '${HttpHeaders.contentTypeHeader} not allowed ' 'for ${method.value} $path'; print(message); return Response(statusCode: HttpStatus.badRequest); } final response = await handler(context); return response; }; }; }
io_flip/api/headers/application_json_header.dart/0
{ "file_path": "io_flip/api/headers/application_json_header.dart", "repo_id": "io_flip", "token_count": 396 }
877
/// Access to Cards data source. library cards_repository; export 'src/cards_repository.dart';
io_flip/api/packages/cards_repository/lib/cards_repository.dart/0
{ "file_path": "io_flip/api/packages/cards_repository/lib/cards_repository.dart", "repo_id": "io_flip", "token_count": 31 }
878
/// Client used to access the game database library db_client; export 'src/db_client.dart';
io_flip/api/packages/db_client/lib/db_client.dart/0
{ "file_path": "io_flip/api/packages/db_client/lib/db_client.dart", "repo_id": "io_flip", "token_count": 28 }
879
/// A Very Good Project created by Very Good CLI. library firebase_cloud_storage; export 'src/firebase_cloud_storage.dart';
io_flip/api/packages/firebase_cloud_storage/lib/firebase_cloud_storage.dart/0
{ "file_path": "io_flip/api/packages/firebase_cloud_storage/lib/firebase_cloud_storage.dart", "repo_id": "io_flip", "token_count": 37 }
880
import 'package:equatable/equatable.dart'; import 'package:game_domain/game_domain.dart'; import 'package:json_annotation/json_annotation.dart'; part 'match.g.dart'; /// {@template match} /// A model that represents a match. /// {@endtemplate} @JsonSerializable(ignoreUnannotated: true, explicitToJson: true) class Match extends Equatable { /// {@macro match} const Match({ required this.id, required this.hostDeck, required this.guestDeck, this.hostConnected = false, this.guestConnected = false, }); /// {@macro match} factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json); /// Match id. @JsonKey() final String id; /// Deck of the host. @JsonKey() final Deck hostDeck; /// Deck of the guest. @JsonKey() final Deck guestDeck; /// If the host is connected or disconnected from the match. @JsonKey() final bool hostConnected; /// If the guest is connected or disconnected from the match. @JsonKey() final bool guestConnected; /// Returns a json representation from this instance. Map<String, dynamic> toJson() => _$MatchToJson(this); @override List<Object> get props => [ id, hostDeck, guestDeck, hostConnected, guestConnected, ]; }
io_flip/api/packages/game_domain/lib/src/models/match.dart/0
{ "file_path": "io_flip/api/packages/game_domain/lib/src/models/match.dart", "repo_id": "io_flip", "token_count": 459 }
881
// ignore_for_file: prefer_const_constructors import 'package:game_domain/src/models/card_description.dart'; import 'package:test/test.dart'; void main() { group('CardDescription', () { test('can instantiate', () { expect( CardDescription( character: '', characterClass: '', power: '', location: '', description: '', ), isNotNull, ); }); test('can deserialize', () { expect( CardDescription.fromJson( const { 'character': 'character', 'characterClass': 'characterClass', 'power': 'power', 'location': 'location', 'description': 'description', }, ), equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ); }); test('can serialize', () { expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ).toJson(), equals( const { 'character': 'character', 'characterClass': 'characterClass', 'power': 'power', 'location': 'location', 'description': 'description', }, ), ); }); }); test('supports equality', () { expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character1', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass1', power: 'power', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power1', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location1', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description1', ), ), ), ); }); }
io_flip/api/packages/game_domain/test/src/models/card_description_test.dart/0
{ "file_path": "io_flip/api/packages/game_domain/test/src/models/card_description_test.dart", "repo_id": "io_flip", "token_count": 2195 }
882
/// The default script, used when none is found in the firebase. const defaultGameLogic = ''' external fun rollDoubleValue fun rollCardRarity() -> bool { var chance = rollDoubleValue(); return chance >= 0.95; } fun rollCardPower(isRare: bool) -> int { const maxValue = 99; const minValue = 10; const gap = maxValue - minValue; var base = rollDoubleValue(); var value = (base * gap + minValue).toInt(); value = if (isRare) 100 else value; return value; } fun compareCards(valueA: int, valueB: int, suitA: str, suitB: str) -> int { var evaluation = compareSuits(suitA, suitB); var aModifier = if (evaluation == -1) 10 else 0; var bModifier = if (evaluation == 1) 10 else 0; var a = valueA - aModifier; var b = valueB - bModifier; if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } fun compareSuits(suitA: str, suitB: str) -> int { when (suitA) { 'fire' -> { when (suitB) { 'air', 'metal' -> return 1; 'water', 'earth' -> return -1; else -> return 0; } } 'air' -> { when (suitB) { 'water', 'earth' -> return 1; 'fire', 'metal' -> return -1; else -> return 0; } } 'metal' -> { when (suitB) { 'water', 'air' -> return 1; 'fire', 'earth' -> return -1; else -> return 0; } } 'earth' -> { when (suitB) { 'fire', 'metal' -> return 1; 'water', 'air' -> return -1; else -> return 0; } } 'water' -> { when (suitB) { 'fire', 'earth' -> return 1; 'metal', 'air' -> return -1; else -> return 0; } } else -> return 0; } } ''';
io_flip/api/packages/game_script_machine/lib/src/default_script.dart/0
{ "file_path": "io_flip/api/packages/game_script_machine/lib/src/default_script.dart", "repo_id": "io_flip", "token_count": 770 }
883
/// A dart_frog middleware for checking JWT authorization. library jwt_middleware; export 'src/authenticated_user.dart'; export 'src/jwt_middleware.dart';
io_flip/api/packages/jwt_middleware/lib/jwt_middleware.dart/0
{ "file_path": "io_flip/api/packages/jwt_middleware/lib/jwt_middleware.dart", "repo_id": "io_flip", "token_count": 50 }
884
include: package:very_good_analysis/analysis_options.3.1.0.yaml
io_flip/api/packages/prompt_repository/analysis_options.yaml/0
{ "file_path": "io_flip/api/packages/prompt_repository/analysis_options.yaml", "repo_id": "io_flip", "token_count": 23 }
885
import 'dart:async'; import 'dart:io'; import 'package:collection/collection.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:prompt_repository/prompt_repository.dart'; FutureOr<Response> onRequest(RequestContext context) async { if (context.request.method == HttpMethod.get) { final type = context.request.uri.queryParameters['type']; final promptType = PromptTermType.values.firstWhereOrNull( (element) => element.name == type, ); if (promptType == null) { return Response(statusCode: HttpStatus.badRequest, body: 'Invalid type'); } final promptRepository = context.read<PromptRepository>(); final list = await promptRepository.getPromptTermsByType( promptType, ); return Response.json(body: {'list': list.map((e) => e.term).toList()}); } return Response(statusCode: HttpStatus.methodNotAllowed); }
io_flip/api/routes/game/prompt/terms/index.dart/0
{ "file_path": "io_flip/api/routes/game/prompt/terms/index.dart", "repo_id": "io_flip", "token_count": 326 }
886
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:logging/logging.dart'; import 'package:match_repository/match_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../../../routes/game/matches/[matchId]/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockMatchRepository extends Mock implements MatchRepository {} class _MockRequest extends Mock implements Request {} class _MockLogger extends Mock implements Logger {} void main() { group('GET /game/matches/[matchId]', () { late MatchRepository matchRepository; late Request request; late RequestContext context; late Logger logger; const hostDeck = Deck( id: 'hostDeckId', userId: 'hostUserId', cards: [ Card( id: '', name: '', description: '', image: '', power: 10, rarity: false, suit: Suit.air, ), ], ); const guestDeck = Deck( id: 'guestDeckId', userId: 'guestUserId', cards: [ Card( id: '', name: '', description: '', image: '', power: 10, rarity: false, suit: Suit.air, ), ], ); const match = Match( id: 'matchId', guestDeck: guestDeck, hostDeck: hostDeck, ); setUp(() { matchRepository = _MockMatchRepository(); when(() => matchRepository.getMatch(any())).thenAnswer( (_) async => match, ); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.get); when(request.json).thenAnswer( (_) async => match.toJson(), ); logger = _MockLogger(); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<MatchRepository>()).thenReturn(matchRepository); when(() => context.read<Logger>()).thenReturn(logger); }); test('responds with a 200', () async { final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.ok)); }); test('responds with the match', () async { final response = await route.onRequest(context, match.id); final json = await response.json() as Map<String, dynamic>; expect( json, equals(match.toJson()), ); }); test("responds 404 when the match doesn't exists", () async { when(() => matchRepository.getMatch(any())).thenAnswer((_) async => null); final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.notFound)); }); test('allows only get methods', () async { when(() => request.method).thenReturn(HttpMethod.post); final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); }
io_flip/api/test/routes/game/matches/[matchId]/index_test.dart/0
{ "file_path": "io_flip/api/test/routes/game/matches/[matchId]/index_test.dart", "repo_id": "io_flip", "token_count": 1268 }
887
// ignore_for_file: avoid_print import 'dart:io'; import 'package:data_loader/src/prompt_mapper.dart'; import 'package:db_client/db_client.dart'; import 'package:game_domain/game_domain.dart'; /// {@template check_missing_descriptions} /// Dart tool that feed descriptions into the Descriptions base /// {@endtemplate} class MissingDescriptions { /// {@macro check_missing_descriptions} const MissingDescriptions({ required DbClient dbClient, required File csv, required String character, }) : _dbClient = dbClient, _csv = csv, _character = character; final File _csv; final DbClient _dbClient; final String _character; String _normalizeTerm(String term) { return term.trim().toLowerCase().replaceAll(' ', '_'); } /// Loads the descriptions from the CSV file into the database /// [onProgress] is called everytime there is progress, /// it takes in the current inserted and the total to insert. Future<void> checkMissing(void Function(int, int) onProgress) async { final lines = await _csv.readAsLines(); final map = mapCsvToPrompts(lines); final queries = <Map<String, dynamic>>[]; for (final characterClass in map[PromptTermType.characterClass]!) { for (final power in map[PromptTermType.power]!) { for (final location in map[PromptTermType.location]!) { queries.add( { 'character': _normalizeTerm(_character), 'characterClass': _normalizeTerm(characterClass), 'power': _normalizeTerm(power), 'location': _normalizeTerm(location), }, ); } } } for (final query in queries) { final result = await _dbClient.find( 'card_descriptions', query, ); if (result.isEmpty) { print(query.values.join('_')); } } print('Done'); } }
io_flip/api/tools/data_loader/lib/src/check_missing_descriptions_loader.dart/0
{ "file_path": "io_flip/api/tools/data_loader/lib/src/check_missing_descriptions_loader.dart", "repo_id": "io_flip", "token_count": 733 }
888
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect x="10.5" y="10" width="3" height="12" fill="white"/> <path d="M12 6C12.5667 6 13.0417 5.80833 13.425 5.425C13.8083 5.04167 14 4.56667 14 4C14 3.43333 13.8083 2.95833 13.425 2.575C13.0417 2.19167 12.5667 2 12 2C11.4333 2 10.9583 2.19167 10.575 2.575C10.1917 2.95833 10 3.43333 10 4C10 4.56667 10.1917 5.04167 10.575 5.425C10.9583 5.80833 11.4333 6 12 6Z" fill="white"/> </svg>
io_flip/assets/icons/info.svg/0
{ "file_path": "io_flip/assets/icons/info.svg", "repo_id": "io_flip", "token_count": 233 }
889
// ignore_for_file: avoid_web_libraries_in_flutter, avoid_print import 'dart:async'; import 'dart:math'; import 'package:api_client/api_client.dart'; import 'package:authentication_repository/authentication_repository.dart'; import 'package:bloc/bloc.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:equatable/equatable.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flop/firebase_options_development.dart'; import 'package:game_domain/game_domain.dart'; import 'package:match_maker_repository/match_maker_repository.dart'; part 'flop_event.dart'; part 'flop_state.dart'; class FlopBloc extends Bloc<FlopEvent, FlopState> { FlopBloc({ required this.setAppCheckDebugToken, required this.reload, }) : super(const FlopState.initial()) { on<NextStepRequested>(_onNextStepRequested); } final void Function(String) setAppCheckDebugToken; final void Function() reload; late AuthenticationRepository authenticationRepository; late ConnectionRepository connectionRepository; late MatchMakerRepository matchMakerRepository; late ApiClient apiClient; late FirebaseAuth authInstance; late bool isHost; late List<Card> cards; late String matchId; late String deckId; late String matchStateId; Future<void> initialize(Emitter<FlopState> emit) async { emit(state.withNewMessage('πŸ€– Hello, I am Flop and I am ready!')); const recaptchaKey = String.fromEnvironment('RECAPTCHA_KEY'); const appCheckDebugToken = String.fromEnvironment('APPCHECK_DEBUG_TOKEN'); setAppCheckDebugToken(appCheckDebugToken); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Ensure we always have a new user. authInstance = FirebaseAuth.instance; await authInstance.setPersistence(Persistence.NONE); emit(state.withNewMessage('πŸ”₯ Firebase initialized')); final appCheck = FirebaseAppCheck.instance; await appCheck.activate( webRecaptchaSiteKey: recaptchaKey, ); await appCheck.setTokenAutoRefreshEnabled(true); emit(state.withNewMessage('βœ… AppCheck activated')); } Future<void> authenticate(Emitter<FlopState> emit) async { authenticationRepository = AuthenticationRepository( firebaseAuth: authInstance, ); final appCheck = FirebaseAppCheck.instance; apiClient = ApiClient( baseUrl: 'https://top-dash-dev-api-synvj3dcmq-uc.a.run.app', idTokenStream: authenticationRepository.idToken, refreshIdToken: authenticationRepository.refreshIdToken, appCheckTokenStream: appCheck.onTokenChange, appCheckToken: await appCheck.getToken(), ); await authenticationRepository.signInAnonymously(); await authenticationRepository.idToken.first; final user = await authenticationRepository.user.first; connectionRepository = ConnectionRepository( apiClient: apiClient, ); emit(state.withNewMessage('🎭 Authenticated anonymously: ${user.id}')); } Future<void> generateCards(Emitter<FlopState> emit) async { final generatedCards = await apiClient.gameResource.generateCards( const Prompt( characterClass: 'Wizard', power: 'Chocolate', ), ); emit( state.withNewMessage( 'πŸƒ Generated ${generatedCards.length} cards\n ' '${generatedCards.map((card) => ' - ${card.name}').join('\n ')}', ), ); cards = (generatedCards..shuffle()).take(3).toList(); emit( state.withNewMessage( 'πŸƒ Choose 3 cards\n ' '${cards.map((card) => ' - ${card.name}').join('\n ')}', ), ); } Future<void> requestMatchConnection() async { final completer = Completer<void>(); await connectionRepository.connect(); late StreamSubscription<WebSocketMessage> subscription; subscription = connectionRepository.messages.listen( (message) { if (message.messageType == MessageType.connected) { completer.complete(); subscription.cancel(); } else if (message.messageType == MessageType.error) { completer.completeError('Already connected'); } }, ); return completer.future.timeout(const Duration(seconds: 4)); } Future<void> connectToMatch({ required String matchId, required bool isHost, }) async { connectionRepository.send( WebSocketMessage.matchJoined( matchId: matchId, isHost: isHost, ), ); await connectionRepository.messages.firstWhere((message) { return message.messageType == MessageType.matchJoined; }); } Future<void> matchMaking(Emitter<FlopState> emit) async { emit(state.withNewMessage('πŸ₯Ί Requesting match connection')); await requestMatchConnection(); emit(state.withNewMessage('🀝 Connection established')); final cardIds = cards.map((card) => card.id).toList(); deckId = await apiClient.gameResource.createDeck(cardIds); emit(state.withNewMessage('πŸ‘‹ User hand is: $deckId')); matchMakerRepository = MatchMakerRepository( db: FirebaseFirestore.instance, ); final match = await matchMakerRepository.findMatch(deckId); isHost = match.guest == null; await connectToMatch( matchId: match.id, isHost: isHost, ); if (isHost) { final newState = state.copyWith( messages: [ 'πŸ‘€ No match found, created one and waiting for a guest', ...state.messages, ], steps: [...state.steps, FlopStep.matchmaking], ); emit(newState); final stream = matchMakerRepository.watchMatch(match.id); late StreamSubscription<DraftMatch> subscription; final completer = Completer<void>(); subscription = stream.listen((newMatch) { print(newMatch); if (newMatch.guest != null) { matchId = newMatch.id; emit( newState.copyWith( messages: ['πŸŽ‰ Match joined', ...newState.messages], steps: [...newState.steps, FlopStep.joinedMatch], ), ); subscription.cancel(); completer.complete(); } }); return completer.future; } else { matchId = match.id; emit( state.copyWith( messages: ['πŸŽ‰ Match joined: ${match.id}', ...state.messages], steps: [ ...state.steps, FlopStep.matchmaking, FlopStep.joinedMatch, ], ), ); } } Future<void> playCard(int i, Emitter<FlopState> emit) async { await apiClient.gameResource.playCard( matchId: matchId, cardId: cards[i].id, deckId: deckId, ); emit( state.withNewMessage( 'πŸƒ Played ${cards[i].name}', ), ); } Future<void> playGame(Emitter<FlopState> emit) async { final rng = Random(); final completer = Completer<void>(); final matchState = await apiClient.gameResource.getMatchState(matchId); matchStateId = matchState!.id; late StreamSubscription<MatchState> subscription; subscription = matchMakerRepository.watchMatchState(matchStateId).listen((matchState) { if (matchState.isOver()) { emit( state.copyWith( messages: ['πŸŽ‰ Match over', ...state.messages], steps: [...state.steps, FlopStep.playing], ), ); subscription.cancel(); completer.complete(); } else { final myPlayedCards = isHost ? matchState.hostPlayedCards : matchState.guestPlayedCards; final opponentPlayedCards = isHost ? matchState.guestPlayedCards : matchState.hostPlayedCards; if (myPlayedCards.length == opponentPlayedCards.length || myPlayedCards.length < opponentPlayedCards.length) { var retries = 3; Future<void>.delayed(Duration(milliseconds: rng.nextInt(1000) + 500), () async { await playCard(myPlayedCards.length, emit); }).onError( (error, _) { if (retries > 0) { return Future<void>.delayed( Duration(milliseconds: rng.nextInt(1000) + 500), ).then((_) { retries--; return playCard(myPlayedCards.length, emit); }); } else { emit(state.withNewMessage('😭 Error playing cards: $error')); } }, ); Future<void>.delayed(const Duration(seconds: 3)).then((_) { playCard(myPlayedCards.length, emit); }); } } }); await playCard(0, emit); await completer.future; } Future<void> _onNextStepRequested( _, Emitter<FlopState> emit, ) async { try { if (state.steps.isEmpty) { await initialize(emit); emit(state.copyWith(steps: [FlopStep.initial])); } else { final lastStep = state.steps.last; switch (lastStep) { case FlopStep.initial: await authenticate(emit); emit( state.copyWith( steps: [...state.steps, FlopStep.authentication], ), ); break; case FlopStep.authentication: await generateCards(emit); emit( state.copyWith( steps: [...state.steps, FlopStep.deckDraft], ), ); break; case FlopStep.deckDraft: await matchMaking(emit).timeout(const Duration(seconds: 120)); break; case FlopStep.matchmaking: break; case FlopStep.joinedMatch: await playGame(emit).timeout(const Duration(seconds: 30)); break; case FlopStep.playing: emit( state.copyWith( status: FlopStatus.success, ), ); await Future<void>.delayed(const Duration(seconds: 2)); reload(); break; } } } catch (e, s) { emit( state.copyWith( status: FlopStatus.error, messages: [ '🚨 Error: $e $s', ...state.messages, ], ), ); print(e); print(s); addError(e, s); await Future<void>.delayed(const Duration(seconds: 2)); reload(); } } }
io_flip/flop/lib/flop/bloc/flop_bloc.dart/0
{ "file_path": "io_flip/flop/lib/flop/bloc/flop_bloc.dart", "repo_id": "io_flip", "token_count": 4558 }
890
<html> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png" /> <script type="text/javascript"> window.addEventListener('load', function() { let botArea = document.getElementById('botArea'); let field = document.getElementById('botCount'); let button = document.getElementById('summon'); button.addEventListener('click', function() { let number = parseInt(field.value); summonSquad(number); }); function summonSquad(number) { for (let i = 0; i < number; i++) { setTimeout(summonBot, 2500 * Math.random()); } } function summonBot() { let iframe = document.createElement('iframe'); iframe.src = '/'; iframe.width = 500; iframe.height = 500; iframe.frameBorder = 0; botArea.appendChild(iframe); } if (location.hash.length > 0) { let number = parseInt(location.hash.substring(1)); summonSquad(number); } }); </script> <body> <div style="text-align: center;"> <img src="/assets/assets/flop.png" width="200" height="200"/> <h1>Hello, I am Flop and I am ready to help you!</h1> <hr /> <label>How many bots should I summon?</label> <input type="number" id="botCount" value="5" /> <button id="summon">Summon</button> </div> <div style="text-align: center;" id="botArea"> </div> </body> </html>
io_flip/flop/web/squad.html/0
{ "file_path": "io_flip/flop/web/squad.html", "repo_id": "io_flip", "token_count": 647 }
891
export 'widgets/widgets.dart';
io_flip/lib/audio/audio.dart/0
{ "file_path": "io_flip/lib/audio/audio.dart", "repo_id": "io_flip", "token_count": 12 }
892
export 'bloc/draft_bloc.dart'; export 'views/views.dart'; export 'widgets/widgets.dart';
io_flip/lib/draft/draft.dart/0
{ "file_path": "io_flip/lib/draft/draft.dart", "repo_id": "io_flip", "token_count": 36 }
893
import 'dart:async'; import 'package:flutter/material.dart' hide Card, Element; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:game_domain/game_domain.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; enum ComparisonResult { player, opponent, none } extension on int { ComparisonResult get result { if (this == 1) { return ComparisonResult.player; } else if (this == -1) { return ComparisonResult.opponent; } else { return ComparisonResult.none; } } } extension on TickerFuture { Future<void> get done => orCancel.then<void>((_) {}, onError: (_) {}); } class ClashScene extends StatefulWidget { const ClashScene({ required this.onFinished, required this.opponentCard, required this.playerCard, super.key, }); final VoidCallback onFinished; final Card opponentCard; final Card playerCard; @override State<StatefulWidget> createState() => ClashSceneState(); } class ClashSceneState extends State<ClashScene> with TickerProviderStateMixin { Color bgColor = Colors.transparent; final AnimatedCardController opponentController = AnimatedCardController(); final AnimatedCardController playerController = AnimatedCardController(); late final AnimationController motionController = AnimationController( vsync: this, duration: const Duration(seconds: 5), ); late final motion = TweenSequence([ TweenSequenceItem(tween: Tween<double>(begin: 60, end: 15), weight: 4), TweenSequenceItem(tween: Tween<double>(begin: 15, end: 0), weight: 5), ]).animate( CurvedAnimation(parent: motionController, curve: Curves.easeOutCirc), ); late final AnimationController damageController = AnimationController( vsync: this, duration: const Duration(seconds: 2), ); final Completer<void> damageCompleter = Completer<void>(); Animation<int>? powerDecrementAnimation; late final ComparisonResult winningCard; late final ComparisonResult winningSuit; bool _flipCards = false; bool _playedWinningElementSound = false; void onFlipCards() { motionController.stop(); Future.delayed( const Duration(milliseconds: 100), () => opponentController.run(smallFlipAnimation), ); playerController.run(smallFlipAnimation); Future.delayed( const Duration(milliseconds: 500), () => setState(() => _flipCards = true), ); } void onDamageRecieved() => damageController ..forward() ..addStatusListener((status) { if (status == AnimationStatus.completed) { damageCompleter.complete(); } }); Future<void> onElementalComplete() async { if (winningCard != ComparisonResult.none) { setState(() { bgColor = Colors.black.withOpacity(0.5); }); if (winningCard == ComparisonResult.player) { await playerController.run(playerAttackForwardAnimation).done; await Future<void>.delayed(const Duration(milliseconds: 5)); await Future.wait([ playerController.run(playerAttackBackAnimation).done, opponentController.run(opponentKnockOutAnimation).done, ]); } else if (winningCard == ComparisonResult.opponent) { await opponentController.run(opponentAttackForwardAnimation).done; await Future<void>.delayed(const Duration(milliseconds: 5)); await Future.wait([ opponentController.run(opponentAttackBackAnimation).done, playerController.run(playerKnockOutAnimation).done, ]); } } widget.onFinished(); } void _getResults() { final gameScript = context.read<GameScriptMachine>(); final playerCard = widget.playerCard; final opponentCard = widget.opponentCard; winningCard = gameScript.compare(playerCard, opponentCard).result; winningSuit = gameScript.compareSuits(playerCard.suit, opponentCard.suit).result; if (winningSuit != ComparisonResult.none) { int power; if (winningSuit == ComparisonResult.player) { power = widget.opponentCard.power; } else { power = widget.playerCard.power; } powerDecrementAnimation = IntTween( begin: power, end: power - 10, ).animate( CurvedAnimation( parent: damageController, curve: Curves.easeOutCirc, ), ); } } void _playSoundByElement(Element element) { switch (element) { case Element.fire: context.read<AudioController>().playSfx(Assets.sfx.fire); break; case Element.air: context.read<AudioController>().playSfx(Assets.sfx.air); break; case Element.earth: context.read<AudioController>().playSfx(Assets.sfx.earth); break; case Element.metal: context.read<AudioController>().playSfx(Assets.sfx.metal); break; case Element.water: context.read<AudioController>().playSfx(Assets.sfx.water); break; } } @override void initState() { super.initState(); _getResults(); motionController.forward(); context.read<AudioController>().playSfx(Assets.sfx.flip); } @override void dispose() { motionController.dispose(); opponentController.dispose(); playerController.dispose(); damageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const cardSize = GameCardSize.md(); final clashSceneSize = Size(cardSize.width * 1.7, cardSize.height * 2.15); final playerCard = AnimatedBuilder( key: const Key('player_card'), animation: motion, builder: (_, child) { return Positioned( bottom: 0, right: motion.value, child: child!, ); }, child: AnimatedCard( controller: playerController, front: const FlippedGameCard( size: cardSize, ), back: powerDecrementAnimation != null && winningSuit == ComparisonResult.opponent ? AnimatedBuilder( animation: powerDecrementAnimation!, builder: (_, __) { return GameCard( size: cardSize, image: widget.playerCard.image, name: widget.playerCard.name, description: widget.playerCard.description, power: powerDecrementAnimation!.value, suitName: widget.playerCard.suit.name, isRare: widget.playerCard.rarity, ); }, ) : GameCard( size: cardSize, image: widget.playerCard.image, name: widget.playerCard.name, description: widget.playerCard.description, power: widget.playerCard.power, suitName: widget.playerCard.suit.name, isRare: widget.playerCard.rarity, ), ), ); final opponentCard = AnimatedBuilder( key: const Key('opponent_card'), animation: motion, builder: (_, child) { return Positioned( top: 0, left: motion.value, child: child!, ); }, child: AnimatedCard( controller: opponentController, front: const FlippedGameCard( size: cardSize, ), back: powerDecrementAnimation != null && winningSuit == ComparisonResult.player ? AnimatedBuilder( animation: powerDecrementAnimation!, builder: (_, __) { return GameCard( size: cardSize, image: widget.opponentCard.image, name: widget.opponentCard.name, description: widget.opponentCard.description, power: powerDecrementAnimation!.value, suitName: widget.opponentCard.suit.name, isRare: widget.opponentCard.rarity, ); }, ) : GameCard( size: cardSize, image: widget.opponentCard.image, name: widget.opponentCard.name, description: widget.opponentCard.description, power: widget.opponentCard.power, suitName: widget.opponentCard.suit.name, isRare: widget.opponentCard.rarity, ), ), ); if (_playedWinningElementSound) { final suit = switch (winningCard) { ComparisonResult.player => widget.playerCard.suit, ComparisonResult.opponent => widget.opponentCard.suit, ComparisonResult.none => null, }; if (suit != null) { final element = _elementsMap[suit]!; _playSoundByElement(element); } } final winningElement = _elementsMap[winningSuit == ComparisonResult.player ? widget.playerCard.suit : widget.opponentCard.suit]; if (_flipCards && !_playedWinningElementSound && winningSuit != ComparisonResult.none) { if (winningSuit != ComparisonResult.none) { _playSoundByElement(winningElement!); } _playedWinningElementSound = true; } return AnimatedContainer( duration: const Duration(milliseconds: 300), color: bgColor, child: Center( child: SizedBox.fromSize( size: clashSceneSize, child: Stack( children: [ if (winningCard == ComparisonResult.player) ...[ opponentCard, playerCard ] else ...[ playerCard, opponentCard ], Positioned.fill( child: Visibility( visible: !_flipCards, child: FlipCountdown( onComplete: onFlipCards, ), ), ), if (_flipCards) ElementalDamageAnimation( winningElement!, direction: winningSuit == ComparisonResult.player || (winningSuit == ComparisonResult.none && winningCard == ComparisonResult.player) ? DamageDirection.bottomToTop : DamageDirection.topToBottom, size: cardSize, assetSize: platformAwareAsset<AssetSize>( desktop: AssetSize.large, mobile: AssetSize.small, ), initialState: winningSuit == ComparisonResult.none ? DamageAnimationState.victory : DamageAnimationState.charging, onDamageReceived: onDamageRecieved, pointDeductionCompleter: damageCompleter, onComplete: onElementalComplete, ) ], ), ), ), ); } static const _elementsMap = { Suit.air: Element.air, Suit.earth: Element.earth, Suit.fire: Element.fire, Suit.metal: Element.metal, Suit.water: Element.water, }; }
io_flip/lib/game/widgets/clash_scene.dart/0
{ "file_path": "io_flip/lib/game/widgets/clash_scene.dart", "repo_id": "io_flip", "token_count": 5033 }
894
export 'arrow_widget.dart'; export 'circular_alignment_tween.dart'; export 'fade_animated_switcher.dart'; export 'how_to_play_styled_text.dart'; export 'suits_wheel.dart';
io_flip/lib/how_to_play/widgets/widgets.dart/0
{ "file_path": "io_flip/lib/how_to_play/widgets/widgets.dart", "repo_id": "io_flip", "token_count": 67 }
895
export 'bloc/leaderboard_bloc.dart'; export 'views/views.dart'; export 'widgets/widgets.dart';
io_flip/lib/leaderboard/leaderboard.dart/0
{ "file_path": "io_flip/lib/leaderboard/leaderboard.dart", "repo_id": "io_flip", "token_count": 37 }
896
import 'package:flutter/material.dart' hide Card; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:game_domain/game_domain.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/audio.dart'; import 'package:io_flip/game/game.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/match_making/match_making.dart'; import 'package:io_flip/utils/utils.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class MatchMakingView extends StatelessWidget { const MatchMakingView({ required this.deck, required this.tryAgainEvent, super.key, Future<void> Function(ClipboardData) setClipboardData = Clipboard.setData, RouterNeglectCall routerNeglectCall = Router.neglect, }) : _setClipboardData = setClipboardData, _routerNeglectCall = routerNeglectCall; final Future<void> Function(ClipboardData) _setClipboardData; final Deck deck; final RouterNeglectCall _routerNeglectCall; /// The event to add to the bloc when match making fails and we try again. final MatchMakingEvent tryAgainEvent; @override Widget build(BuildContext context) { return BlocConsumer<MatchMakingBloc, MatchMakingState>( listener: (previous, current) { if (current.status == MatchMakingStatus.completed) { Future.delayed( const Duration(seconds: 3), () => _routerNeglectCall( context, () => context.goNamed( 'game', extra: GamePageData( isHost: current.isHost, matchId: current.match?.id ?? '', deck: deck, ), ), ), ); } }, builder: (context, state) { final l10n = context.l10n; if (state.status == MatchMakingStatus.processing || state.status == MatchMakingStatus.initial) { return ResponsiveLayoutBuilder( small: (_, __) => _WaitingForMatchView( cards: deck.cards, setClipboardData: _setClipboardData, inviteCode: state.match?.inviteCode, title: IoFlipTextStyles.mobileH4Light, subtitle: IoFlipTextStyles.mobileH6Light, key: const Key('small_waiting_for_match_view'), ), large: (_, __) => _WaitingForMatchView( cards: deck.cards, setClipboardData: _setClipboardData, inviteCode: state.match?.inviteCode, title: IoFlipTextStyles.headlineH4Light, subtitle: IoFlipTextStyles.headlineH6Light, key: const Key('large_waiting_for_match_view'), ), ); } if (state.status == MatchMakingStatus.timeout) { return IoFlipScaffold( body: IoFlipErrorView( text: 'Match making timed out, sorry!', buttonText: l10n.playAgain, onPressed: () => context.read<MatchMakingBloc>().add(tryAgainEvent), ), ); } if (state.status == MatchMakingStatus.failed) { return IoFlipScaffold( body: IoFlipErrorView( text: 'Match making failed, sorry!', buttonText: l10n.playAgain, onPressed: () => context.read<MatchMakingBloc>().add(tryAgainEvent), ), ); } return IoFlipScaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( l10n.getReadyToFlip, style: IoFlipTextStyles.mobileH1, ), const SizedBox(height: IoFlipSpacing.xlg), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 320), child: Text( l10n.aiGameByGoogle, style: IoFlipTextStyles.mobileH4Light, textAlign: TextAlign.center, ), ), ], ), ), ); }, ); } } class _WaitingForMatchView extends StatelessWidget { const _WaitingForMatchView({ required this.title, required this.subtitle, required this.cards, required this.setClipboardData, this.inviteCode, super.key, }); final List<Card> cards; final String? inviteCode; final Future<void> Function(ClipboardData) setClipboardData; final TextStyle title; final TextStyle subtitle; @override Widget build(BuildContext context) { return IoFlipScaffold( body: Column( children: [ Expanded( child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 600), child: Column( children: [ const Spacer(), Text( context.l10n.findingMatch, style: title, ), if (inviteCode == null) Text( context.l10n.searchingForOpponents, style: subtitle, ) else ElevatedButton( onPressed: () { final code = inviteCode; if (code != null) { setClipboardData(ClipboardData(text: code)); } }, child: Text(context.l10n.copyInviteCode), ), const SizedBox(height: IoFlipSpacing.xxlg), const FadingDotLoader(), const Spacer(), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (final card in cards) Padding( padding: const EdgeInsets.all(IoFlipSpacing.xs), child: GameCard( size: const GameCardSize.xs(), image: card.image, name: card.name, description: card.description, suitName: card.suit.name, power: card.power, isRare: card.rarity, ), ), ], ), ], ), ), ), ), IoFlipBottomBar( leading: const AudioToggleButton(), middle: RoundedButton.text( context.l10n.matchmaking, backgroundColor: IoFlipColors.seedGrey50, foregroundColor: IoFlipColors.seedGrey70, ), ), ], ), ); } }
io_flip/lib/match_making/views/match_making_view.dart/0
{ "file_path": "io_flip/lib/match_making/views/match_making_view.dart", "repo_id": "io_flip", "token_count": 3933 }
897
import 'package:api_client/api_client.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:game_script_machine/game_script_machine.dart'; part 'scripts_state.dart'; class ScriptsCubit extends Cubit<ScriptsState> { ScriptsCubit({ required this.scriptsResource, required this.gameScriptMachine, }) : super( ScriptsState( status: ScriptsStateStatus.loaded, current: gameScriptMachine.currentScript, ), ); final ScriptsResource scriptsResource; final GameScriptMachine gameScriptMachine; Future<void> updateScript(String content) async { try { emit( state.copyWith(status: ScriptsStateStatus.loading), ); await scriptsResource.updateScript('current', content); gameScriptMachine.currentScript = content; emit( state.copyWith( status: ScriptsStateStatus.loaded, current: content, ), ); } catch (e, s) { emit( state.copyWith( status: ScriptsStateStatus.failed, ), ); addError(e, s); } } }
io_flip/lib/scripts/cubit/scripts_cubit.dart/0
{ "file_path": "io_flip/lib/scripts/cubit/scripts_cubit.dart", "repo_id": "io_flip", "token_count": 470 }
898
import 'package:flutter/material.dart' hide Card; import 'package:game_domain/game_domain.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/share/share.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; typedef ShowShareDialog = Future<void> Function(Card card); class CardInspectorDialog extends StatefulWidget { const CardInspectorDialog({ required this.cards, required this.playerCardIds, required this.startingIndex, super.key, }); final List<String> playerCardIds; final List<Card> cards; final int startingIndex; @override State<CardInspectorDialog> createState() => _CardInspectorDialogState(); } class _CardInspectorDialogState extends State<CardInspectorDialog> { late final start = widget.cards.length * 300 + widget.startingIndex; late final controller = PageController(initialPage: start); @override Widget build(BuildContext context) { const transitionDuration = Duration(milliseconds: 200); const phoneHeight = 600; const smallestPhoneHeight = 500; final height = MediaQuery.sizeOf(context).height; final cardSize = height > phoneHeight ? const GameCardSize.xxl() : const GameCardSize.xl(); return Dialog( insetPadding: const EdgeInsets.all(IoFlipSpacing.sm), backgroundColor: Colors.transparent, child: Column( mainAxisSize: MainAxisSize.min, children: [ _CardViewer( controller: controller, deck: widget.cards, share: (card) => IoFlipDialog.show( context, child: ShareCardDialog(card: card), ), size: cardSize, playerCardIds: widget.playerCardIds, ), if (height > smallestPhoneHeight) Padding( padding: const EdgeInsets.all(IoFlipSpacing.lg), child: Row( mainAxisSize: MainAxisSize.min, children: [ _BackButton( controller: controller, transitionDuration: transitionDuration, ), const SizedBox(width: IoFlipSpacing.lg), _ForwardButton( controller: controller, transitionDuration: transitionDuration, ), ], ), ), ], ), ); } @override void dispose() { controller.dispose(); super.dispose(); } } class _ForwardButton extends StatelessWidget { const _ForwardButton({ required this.controller, required this.transitionDuration, }); final PageController controller; final Duration transitionDuration; @override Widget build(BuildContext context) { return RoundedButton.icon( Icons.arrow_forward, onPressed: () => controller.nextPage( duration: transitionDuration, curve: Curves.linear, ), ); } } class _BackButton extends StatelessWidget { const _BackButton({ required this.controller, required this.transitionDuration, }); final PageController controller; final Duration transitionDuration; @override Widget build(BuildContext context) { return RoundedButton.icon( Icons.arrow_back, onPressed: () => controller.previousPage( duration: transitionDuration, curve: Curves.linear, ), ); } } class _CardViewer extends StatelessWidget { const _CardViewer({ required this.controller, required this.deck, required this.size, required this.share, required this.playerCardIds, }); final PageController controller; final List<Card> deck; final GameCardSize size; final ShowShareDialog share; final List<String> playerCardIds; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { GoRouter.of(context).pop(); }, child: SizedBox( height: size.height, width: MediaQuery.sizeOf(context).width * .9, child: PageView.builder( clipBehavior: Clip.none, controller: controller, itemBuilder: (context, i) { final index = i % deck.length; final card = deck[index]; return Center( child: GestureDetector( // Used to ignore taps. onTap: () {}, child: Stack( clipBehavior: Clip.none, children: [ TiltBuilder( builder: (context, tilt) => GameCard( key: ValueKey('GameCard$index'), tilt: tilt / 2, size: size, image: card.image, name: card.name, description: card.description, suitName: card.suit.name, power: card.power, isRare: card.rarity, ), ), if (playerCardIds.contains(card.id)) Positioned( top: IoFlipSpacing.lg, left: IoFlipSpacing.lg, child: RoundedButton.icon( Icons.share_outlined, onPressed: () => share(card), ), ), ], ), ), ); }, ), ), ); } }
io_flip/lib/share/views/card_inspector_dialog.dart/0
{ "file_path": "io_flip/lib/share/views/card_inspector_dialog.dart", "repo_id": "io_flip", "token_count": 2668 }
899
import 'package:flutter/widgets.dart'; typedef RouterNeglectCall = void Function(BuildContext, VoidCallback);
io_flip/lib/utils/router_neglect_call.dart/0
{ "file_path": "io_flip/lib/utils/router_neglect_call.dart", "repo_id": "io_flip", "token_count": 33 }
900
import 'dart:io'; import 'dart:typed_data'; import 'package:api_client/api_client.dart'; /// {@template share_resource} /// An api resource for the public sharing API. /// {@endtemplate} class ShareResource { /// {@macro share_resource} ShareResource({ required ApiClient apiClient, }) : _apiClient = apiClient; final ApiClient _apiClient; final _tweetContent = 'Check out my AI-designed team of heroes from I/O FLIP at ' '#GoogleIO! #FlipWithGoogle'; String _twitterShareUrl(String text) => 'https://twitter.com/intent/tweet?text=$text'; String _facebookShareUrl(String shareUrl) => 'https://www.facebook.com/sharer.php?u=$shareUrl'; String _encode(List<String> content) => content.join('%0a').replaceAll(' ', '%20').replaceAll('#', '%23'); /// Returns the url to share a tweet for the specified [cardId]. String twitterShareCardUrl(String cardId) { final cardUrl = _apiClient.shareCardUrl(cardId); final content = [ _tweetContent, cardUrl, ]; return _twitterShareUrl(_encode(content)); } /// Returns the url to share a tweet for the specified [deckId]. String twitterShareHandUrl(String deckId) { final handUrl = _apiClient.shareHandUrl(deckId); final content = [ _tweetContent, handUrl, ]; return _twitterShareUrl(_encode(content)); } /// Returns the url to share a facebook post for the specified [cardId]. String facebookShareCardUrl(String cardId) { final cardUrl = _apiClient.shareCardUrl(cardId); return _facebookShareUrl(cardUrl); } /// Returns the url to share a facebook post for the specified [deckId]. String facebookShareHandUrl(String deckId) { final handUrl = _apiClient.shareHandUrl(deckId); return _facebookShareUrl(handUrl); } /// Get public/cards/:cardId /// /// Returns a [Uint8List] image, if any to be found. Future<Uint8List> getShareCardImage(String cardId) async { final response = await _apiClient.getPublic('/public/cards/$cardId'); if (response.statusCode != HttpStatus.ok) { throw ApiClientError( 'GET public/cards/$cardId returned status ${response.statusCode} with the following response: "${response.body}"', StackTrace.current, ); } return response.bodyBytes; } /// Get public/deck/:deckId /// /// Returns a [Uint8List] image, if any to be found. Future<Uint8List> getShareDeckImage(String deckId) async { final response = await _apiClient.getPublic('/public/decks/$deckId'); if (response.statusCode != HttpStatus.ok) { throw ApiClientError( 'GET public/decks/$deckId returned status ${response.statusCode} with the following response: "${response.body}"', StackTrace.current, ); } return response.bodyBytes; } }
io_flip/packages/api_client/lib/src/resources/share_resource.dart/0
{ "file_path": "io_flip/packages/api_client/lib/src/resources/share_resource.dart", "repo_id": "io_flip", "token_count": 982 }
901
name: authentication_repository description: Repository to manage authentication. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: equatable: ^2.0.5 firebase_auth: ^4.2.9 firebase_core: ^2.5.0 firebase_core_platform_interface: ^4.5.3 flutter: sdk: flutter plugin_platform_interface: ^2.1.4 dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^4.0.0
io_flip/packages/authentication_repository/pubspec.yaml/0
{ "file_path": "io_flip/packages/authentication_repository/pubspec.yaml", "repo_id": "io_flip", "token_count": 207 }
902
import 'dart:async'; import 'dart:convert'; import 'package:api_client/api_client.dart'; import 'package:game_domain/game_domain.dart'; import 'package:web_socket_client/web_socket_client.dart'; /// {@template connection_repository} /// Repository to manage the connection state. /// {@endtemplate} class ConnectionRepository { /// {@macro connection_repository} ConnectionRepository({ required ApiClient apiClient, }) : _apiClient = apiClient; final ApiClient _apiClient; WebSocket? _webSocket; /// Connects to the server using a WebSocket. Future<void> connect() async { _webSocket = await _apiClient.connect('/public/connect'); } /// The stream of [WebSocketMessage] received from the server. Stream<WebSocketMessage> get messages => _webSocket?.messages.transform( StreamTransformer.fromHandlers( handleData: (rawMessage, sink) { try { if (rawMessage is String) { final messageJson = jsonDecode(rawMessage); if (messageJson is Map) { final message = WebSocketMessage.fromJson( Map<String, dynamic>.from(messageJson), ); sink.add(message); } } } catch (e) { // ignore it } }, ), ) ?? const Stream.empty(); /// Sends a [WebSocketMessage] to the server. void send(WebSocketMessage message) { _webSocket?.send(jsonEncode(message)); } /// Closes the connection to the server. void close() { _webSocket?.close(); _webSocket = null; } }
io_flip/packages/connection_repository/lib/src/connection_repository.dart/0
{ "file_path": "io_flip/packages/connection_repository/lib/src/connection_repository.dart", "repo_id": "io_flip", "token_count": 692 }
903
<svg width="98" height="98" viewBox="0 0 98 98" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M61.77 24.62L91.58 86.89L86.58 90.89H76.14H14.1H6L43.72 11L48.72 7L53.51 30.72L61.77 24.62Z" fill="#202124" stroke="#202124" stroke-width="2" stroke-linejoin="round"/> <path d="M61.77 24.62L91.58 86.89H81.14H19.1H11L48.72 7L58 29.95L61.77 24.62Z" fill="#FF5145" stroke="#202124" stroke-width="2" stroke-linejoin="round"/> </svg>
io_flip/packages/io_flip_ui/assets/images/suits/card/earth.svg/0
{ "file_path": "io_flip/packages/io_flip_ui/assets/images/suits/card/earth.svg", "repo_id": "io_flip", "token_count": 203 }
904
import 'package:flutter/material.dart'; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class AppSpacingStory extends StatelessWidget { const AppSpacingStory({super.key}); @override Widget build(BuildContext context) { const spacingList = [ _SpacingItem(spacing: IoFlipSpacing.xxxs, name: 'xxxs'), _SpacingItem(spacing: IoFlipSpacing.xxs, name: 'xxs'), _SpacingItem(spacing: IoFlipSpacing.xs, name: 'xs'), _SpacingItem(spacing: IoFlipSpacing.sm, name: 'sm'), _SpacingItem(spacing: IoFlipSpacing.md, name: 'md'), _SpacingItem(spacing: IoFlipSpacing.lg, name: 'lg'), _SpacingItem(spacing: IoFlipSpacing.xlgsm, name: 'xlgsm'), _SpacingItem(spacing: IoFlipSpacing.xlg, name: 'xlg'), _SpacingItem(spacing: IoFlipSpacing.xxlg, name: 'xxlg'), _SpacingItem(spacing: IoFlipSpacing.xxxlg, name: 'xxxlg'), ]; return StoryScaffold( title: 'Spacing', body: ListView( shrinkWrap: true, children: spacingList, ), ); } } class _SpacingItem extends StatelessWidget { const _SpacingItem({required this.spacing, required this.name}); final double spacing; final String name; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(IoFlipSpacing.sm), child: Row( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Container( color: IoFlipColors.seedBlack, width: IoFlipSpacing.xxs, height: IoFlipSpacing.lg, ), Container( width: spacing, height: IoFlipSpacing.lg, color: IoFlipColors.seedPaletteBlue70, ), Container( color: IoFlipColors.seedBlack, width: IoFlipSpacing.xxs, height: IoFlipSpacing.lg, ), ], ), const SizedBox(width: IoFlipSpacing.sm), Text('$name ($spacing)'), ], ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/spacing/app_spacing_story.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/lib/spacing/app_spacing_story.dart", "repo_id": "io_flip", "token_count": 1071 }
905
import 'package:flutter/material.dart'; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class ResponsiveLayoutStory extends StatelessWidget { const ResponsiveLayoutStory({super.key}); @override Widget build(BuildContext context) { return StoryScaffold( title: 'Responsive Layout', body: ResponsiveLayoutBuilder( small: (_, __) => const Center( child: Text( 'Small Layout\nResize the window to see the large layout', style: TextStyle(color: IoFlipColors.seedLightBlue), textAlign: TextAlign.center, ), ), large: (_, __) => const Center( child: Text( 'Large Layout\nResize the window to see the small layout', style: TextStyle(color: IoFlipColors.seedGold), textAlign: TextAlign.center, ), ), ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/widgets/responsive_layout_story.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/lib/widgets/responsive_layout_story.dart", "repo_id": "io_flip", "token_count": 404 }
906
import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; /// {@template card_animation} /// Used to set the animation properties of an animated card. /// {@endtemplate} class CardAnimation { /// {@macro card_animation} const CardAnimation({ required this.animatable, required this.duration, this.curve = Curves.linear, this.flipsCard = false, }); /// The animation to be used. final Animatable<Matrix4> animatable; /// The duration of the animation. final Duration duration; /// The curve of the animation. Defaults to [Curves.linear]. final Curve curve; /// Whether this animation causes the card to flip. final bool flipsCard; }
io_flip/packages/io_flip_ui/lib/src/animations/card_animation.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/animations/card_animation.dart", "repo_id": "io_flip", "token_count": 211 }
907
import 'dart:ui'; /// Card sizes used in the I/O FLIP UI. abstract class IoFlipCardSizes { /// xxs card size static const Size xxs = Size(54, 72); /// xs card size static const Size xs = Size(103, 137); /// sm card size static const Size sm = Size(139, 185); /// md card size static const Size md = Size(175, 233); /// lg card size static const Size lg = Size(224, 298); /// xl card size static const Size xl = Size(275, 366); /// xxl card size static const Size xxl = Size(327, 435); }
io_flip/packages/io_flip_ui/lib/src/theme/io_flip_card_sizes.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/theme/io_flip_card_sizes.dart", "repo_id": "io_flip", "token_count": 179 }
908
export 'charge_back.dart'; export 'charge_front.dart'; export 'damage_receive.dart'; export 'damage_send.dart'; export 'victory_charge_back.dart'; export 'victory_charge_front.dart';
io_flip/packages/io_flip_ui/lib/src/widgets/damages/damages.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/damages/damages.dart", "repo_id": "io_flip", "token_count": 67 }
909
import 'package:flutter/widgets.dart'; /// Signature for callbacks that are to receive and return a value /// of the same type. typedef ValueUpdater<T> = T Function(T current); /// {@template simple_flow} /// A flow-builder like stepper widget that allows to build a flow of steps /// in a form. /// {@endtemplate} class SimpleFlow<T> extends StatefulWidget { /// {@macro simple_flow} const SimpleFlow({ required this.initialData, required this.onComplete, required this.stepBuilder, super.key, this.child, }); /// Get a [SimpleFlowState] from the [BuildContext]. static SimpleFlowState<T> of<T>(BuildContext context) { final result = context.getInheritedWidgetOfExactType<_SimpleFlowInherited<T>>(); assert(result != null, 'No ${_SimpleFlowInherited<T>} found in context'); return result!.state; } /// The initial data to be used in the flow. final ValueGetter<T> initialData; /// Called when the flow is marked as completed. final ValueChanged<T> onComplete; /// The builder for each step of the flow. final ValueWidgetBuilder<T> stepBuilder; /// Optional child widget to be passed to [stepBuilder]. final Widget? child; @override State<SimpleFlow<T>> createState() => _SimpleFlowState<T>(); } /// Public interface to manipulate the simple flow widget state. abstract class SimpleFlowState<T> { /// Update the current data. void update(ValueUpdater<T> updater); /// Mark the flow as completed. void complete(ValueUpdater<T> updater); } class _SimpleFlowState<T> extends State<SimpleFlow<T>> implements SimpleFlowState<T> { late T data; @override void initState() { super.initState(); data = widget.initialData(); } @override void complete(ValueUpdater<T> updater) { setState(() { data = updater(data); widget.onComplete(data); }); } @override void update(ValueUpdater<T> updater) { setState(() { data = updater(data); }); } @override Widget build(BuildContext context) { return _SimpleFlowInherited<T>( state: this, child: Builder( builder: (context) { return widget.stepBuilder(context, data, widget.child); }, ), ); } } class _SimpleFlowInherited<T> extends InheritedWidget { const _SimpleFlowInherited({ required super.child, required this.state, }); final SimpleFlowState<T> state; @override bool updateShouldNotify(_SimpleFlowInherited<T> old) { return false; } } /// Adds utility methods to [BuildContext] to manipulate the simple flow widget. extension SimpleFlowContext on BuildContext { /// Update the current data. void updateFlow<T>(ValueUpdater<T> updater) { SimpleFlow.of<T>(this).update(updater); } /// Mark the flow as completed. void completeFlow<T>(ValueUpdater<T> updater) { SimpleFlow.of<T>(this).complete(updater); } }
io_flip/packages/io_flip_ui/lib/src/widgets/simple_flow.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/simple_flow.dart", "repo_id": "io_flip", "token_count": 1002 }
910
import 'package:flame/cache.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:provider/provider.dart'; class _MockImages extends Mock implements Images {} void main() { group('ChargeBack', () { late Images images; setUp(() { images = _MockImages(); }); testWidgets('renders SpriteAnimationWidget', (tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Provider.value( value: images, child: const ChargeBack( '', size: GameCardSize.md(), assetSize: AssetSize.large, animationColor: Colors.white, ), ), ), ); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/damages/charge_back_test.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/test/src/widgets/damages/charge_back_test.dart", "repo_id": "io_flip", "token_count": 440 }
911
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; void main() { group('IoFlipScaffold', () { testWidgets('renders correctly', (tester) async { await tester.pumpWidget( MaterialApp( home: IoFlipScaffold( body: Center(child: Text('Test')), ), ), ); expect( find.byType(IoFlipScaffold), findsOneWidget, ); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/io_flip_scaffold_test.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/test/src/widgets/io_flip_scaffold_test.dart", "repo_id": "io_flip", "token_count": 259 }
912
name: match_maker_repository description: Repository for match making. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: cloud_firestore: ^4.4.3 equatable: ^2.0.5 flutter: sdk: flutter game_domain: path: ../../api/packages/game_domain uuid: ^3.0.7 dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^4.0.0
io_flip/packages/match_maker_repository/pubspec.yaml/0
{ "file_path": "io_flip/packages/match_maker_repository/pubspec.yaml", "repo_id": "io_flip", "token_count": 198 }
913
import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/connection/connection.dart'; import 'package:mocktail/mocktail.dart'; class _MockConnectionRepository extends Mock implements ConnectionRepository {} void main() { group('ConnectionBloc', () { late ConnectionRepository connectionRepository; late StreamController<WebSocketMessage> messageController; setUp(() { connectionRepository = _MockConnectionRepository(); messageController = StreamController<WebSocketMessage>(); when(() => connectionRepository.messages) .thenAnswer((_) => messageController.stream); }); group('on ConnectionRequested', () { blocTest<ConnectionBloc, ConnectionState>( 'emits ConnectionInProgress when connection is successful', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionSuccessful] when connection is ' 'successful and a connected message is received', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.add(const WebSocketMessage.connected()); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionSuccess(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionFailure] when connection is ' 'successful and an error message is received', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.add( WebSocketMessage.error(WebSocketErrorCode.playerAlreadyConnected), ); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionFailure(WebSocketErrorCode.playerAlreadyConnected), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits ConnectionInitial when messages stream is closed', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.close(); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionInitial(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionFailure] ' 'when connection is not successful', setUp: () { when(() => connectionRepository.connect()).thenThrow(Exception()); }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionFailure(WebSocketErrorCode.unknown), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); }, errors: () => [ isA<Exception>(), ], ); }); }); }
io_flip/test/connection/bloc/connection_bloc_test.dart/0
{ "file_path": "io_flip/test/connection/bloc/connection_bloc_test.dart", "repo_id": "io_flip", "token_count": 1869 }
914
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart' hide Card; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/game/game.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:io_flip/match_making/views/match_making_page.dart'; import 'package:io_flip/settings/settings_controller.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import '../../helpers/helpers.dart'; class _MockSettingsController extends Mock implements SettingsController {} class _MockGameBloc extends Mock implements GameBloc {} class _MockLeaderboardResource extends Mock implements LeaderboardResource {} class _MockAudioController extends Mock implements AudioController {} class _MockGameScriptMachine extends Mock implements GameScriptMachine {} class _FakeGameState extends Fake implements GameState {} void main() { group('GameView', () { late GameBloc bloc; late LeaderboardResource leaderboardResource; const playerCards = [ Card( id: 'player_card', name: 'host_card', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), Card( id: 'player_card_2', name: 'host_card_2', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), ]; const opponentCards = [ Card( id: 'opponent_card', name: 'guest_card', description: '', image: '', rarity: true, power: 1, suit: Suit.air, ), Card( id: 'opponent_card_2', name: 'guest_card', description: '', image: '', rarity: true, power: 1, suit: Suit.air, ), ]; final deck = Deck(id: '', userId: '', cards: playerCards); setUpAll(() { registerFallbackValue( Card( id: '', name: '', description: '', image: '', power: 0, rarity: false, suit: Suit.air, ), ); registerFallbackValue(_FakeGameState()); }); setUp(() { bloc = _MockGameBloc(); when(() => bloc.isHost).thenReturn(true); when(() => bloc.isWinningCard(any(), isPlayer: any(named: 'isPlayer'))) .thenReturn(null); when(() => bloc.canPlayerPlay(any())).thenReturn(true); when(() => bloc.isPlayerAllowedToPlay).thenReturn(true); when(() => bloc.matchCompleted(any())).thenReturn(false); when(() => bloc.playerDeck).thenReturn(deck); leaderboardResource = _MockLeaderboardResource(); when(() => leaderboardResource.getInitialsBlacklist()) .thenAnswer((_) async => ['WTF']); }); void mockState(GameState state) { whenListen( bloc, Stream.value(state), initialState: state, ); } testWidgets('renders a loading when on initial state', (tester) async { mockState(MatchLoadingState()); await tester.pumpSubject(bloc); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets( 'renders an error message when failed and navigates to match making', (tester) async { final goRouter = MockGoRouter(); mockState(MatchLoadFailedState(deck: deck)); await tester.pumpSubject( bloc, goRouter: goRouter, ); expect(find.text('Unable to join game!'), findsOneWidget); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify( () => goRouter.goNamed( 'match_making', extra: MatchMakingPageData( deck: deck, ), ), ).called(1); }, ); testWidgets( 'renders an error message when failed and navigates to home ' 'if deck not available', (tester) async { final goRouter = MockGoRouter(); mockState(MatchLoadFailedState(deck: null)); await tester.pumpSubject( bloc, goRouter: goRouter, ); expect(find.text('Unable to join game!'), findsOneWidget); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify(() => goRouter.go('/')).called(1); }, ); group('Gameplay', () { final baseState = MatchLoadedState( playerScoreCard: ScoreCard(id: 'scoreCardId'), match: Match( id: '', hostDeck: Deck(id: '', userId: '', cards: playerCards), guestDeck: Deck(id: '', userId: '', cards: opponentCards), ), matchState: MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), rounds: const [], turnTimeRemaining: 10, turnAnimationsFinished: true, isClashScene: false, showCardLanding: false, ); setUp(() { when(() => bloc.playerCards).thenReturn(playerCards); when(() => bloc.opponentCards).thenReturn(opponentCards); }); testWidgets('preloads opponent cards when game starts', (tester) async { whenListen( bloc, Stream.fromIterable([MatchLoadingState(), baseState]), initialState: MatchLoadingState(), ); await tester.pumpSubject(bloc); for (final card in opponentCards) { expect(imageCache.containsKey(NetworkImage(card.image)), isTrue); } }); testWidgets('renders the game in its initial state', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); expect( find.byKey(const Key('opponent_hidden_card_opponent_card')), findsOneWidget, ); expect( find.byKey(const Key('player_card_player_card')), findsOneWidget, ); }); testWidgets( 'renders leaderboard entry view when state is LeaderboardEntryState', (tester) async { mockState(LeaderboardEntryState('scoreCardId')); await tester.pumpSubject( bloc, leaderboardResource: leaderboardResource, ); expect(find.byType(LeaderboardEntryView), findsOneWidget); }, ); testWidgets( 'renders the opponent absent message when the opponent leaves', (tester) async { mockState(OpponentAbsentState(deck: deck)); await tester.pumpSubject(bloc); expect( find.text('Opponent left the game!'), findsOneWidget, ); expect( find.widgetWithText(RoundedButton, 'PLAY AGAIN'), findsOneWidget, ); }, ); testWidgets( 'goes to match making when the replay button is tapped ' 'on opponent absent', (tester) async { final goRouter = MockGoRouter(); mockState(OpponentAbsentState(deck: deck)); await tester.pumpSubject( bloc, goRouter: goRouter, ); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify( () => goRouter.goNamed( 'match_making', extra: MatchMakingPageData( deck: deck, ), ), ).called(1); }, ); testWidgets( 'goes to home when the replay button is tapped on opponent absent ' 'and no deck is available', (tester) async { final goRouter = MockGoRouter(); mockState(OpponentAbsentState(deck: null)); await tester.pumpSubject( bloc, goRouter: goRouter, ); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify(() => goRouter.go('/')).called(1); }, ); testWidgets( 'plays a player card on tap', (tester) async { final audioController = _MockAudioController(); mockState(baseState); await tester.pumpSubject(bloc, audioController: audioController); await tester.tap(find.byKey(const Key('player_card_player_card'))); verify(() => audioController.playSfx(Assets.sfx.cardMovement)) .called(1); verify(() => bloc.add(PlayerPlayed('player_card'))).called(1); }, ); testWidgets( "can't play a card that was already played", (tester) async { mockState(baseState); when(() => bloc.canPlayerPlay('player_card')).thenReturn(false); await tester.pumpSubject(bloc); await tester.tap(find.byKey(const Key('player_card_player_card'))); verifyNever(() => bloc.add(PlayerPlayed('player_card'))); }, ); testWidgets( "can't play when it is not the player turn", (tester) async { when(() => bloc.canPlayerPlay(any())).thenReturn(false); mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: null, ) ], ), ); await tester.pumpSubject(bloc); await tester.tap(find.byKey(const Key('player_card_player_card_2'))); verifyNever(() => bloc.add(PlayerPlayed('player_card_2'))); }, ); testWidgets( 'plays a player card when dragged', (tester) async { final audioController = _MockAudioController(); mockState(baseState); await tester.pumpSubject(bloc, audioController: audioController); final start = tester .getCenter(find.byKey(const Key('player_card_player_card'))); final end = tester.getCenter(find.byKey(const Key('clash_card_1'))); await tester.dragFrom(start, end - start); await tester.pumpAndSettle(); verify(() => audioController.playSfx(Assets.sfx.cardMovement)) .called(1); verify(() => bloc.add(PlayerPlayed('player_card'))).called(1); }, ); testWidgets( 'dragging a player card not to the correct spot does not play it', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); final start = tester .getCenter(find.byKey(const Key('player_card_player_card'))); final end = tester.getCenter(find.byKey(const Key('clash_card_0'))); await tester.dragFrom(start, end - start); await tester.pumpAndSettle(); verifyNever(() => bloc.add(PlayerPlayed('player_card'))); }, ); testWidgets( 'dragging a player card moves it with the pointer', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_1'))); Offset getPlayerCenter() => tester.getCenter( find.byKey(const Key('player_card_player_card')), ); final startClashRect = getClashRect(); final start = getPlayerCenter(); final end = getClashRect().center; final offset = end - start; final gesture = await tester.startGesture(start); await gesture.moveBy(Offset(kDragSlopDefault, -kDragSlopDefault)); await gesture.moveBy( Offset( offset.dx - kDragSlopDefault, offset.dy + kDragSlopDefault, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(getClashRect().contains(getPlayerCenter()), isTrue); expect(getClashRect(), equals(startClashRect.inflate(8))); }, ); testWidgets( 'render the opponent card instantly when played', (tester) async { mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('opponent_revealed_card_opponent_card')), findsOneWidget, ); expect( find.byKey(const Key('player_card_player_card')), findsOneWidget, ); }, ); testWidgets( 'shows an initially played opponent card in the clash area', (tester) async { mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: null, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpSubject(bloc); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_0'))); Rect getOpponentCardRect() => tester.getRect( find.byKey(const Key('opponent_card_opponent_card')), ); await tester.pumpAndSettle(); expect(getClashRect(), equals(getOpponentCardRect())); }, ); testWidgets( 'does not move opponent card until after clash scene ends', (tester) async { final gameScriptMachine = _MockGameScriptMachine(); when( () => gameScriptMachine.compare( playerCards.first, opponentCards.first, ), ).thenReturn(0); when( () => gameScriptMachine.compareSuits( playerCards.first.suit, opponentCards.first.suit, ), ).thenReturn(0); final controller = StreamController<GameState>(); whenListen(bloc, controller.stream, initialState: baseState); when(() => bloc.clashSceneOpponentCard) .thenReturn(opponentCards.first); when(() => bloc.clashScenePlayerCard).thenReturn(playerCards.first); await tester.pumpSubject( bloc, gameScriptMachine: gameScriptMachine, ); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card', rounds: [ MatchRound( playerCardId: null, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); controller.add( baseState.copyWith( isClashScene: true, lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_0'))); Rect getOpponentCardRect() => tester.getRect( find.byKey(const Key('opponent_card_opponent_card_2')), ); await tester.pumpAndSettle(); expect(getOpponentCardRect(), isNot(equals(getClashRect()))); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card_2', isClashScene: true, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), MatchRound( playerCardId: null, opponentCardId: 'opponent_card_2', ), ], ), ); await tester.pump(); tester.widget<ClashScene>(find.byType(ClashScene)).onFinished(); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card_2', isClashScene: false, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), MatchRound( playerCardId: null, opponentCardId: 'opponent_card_2', ), ], ), ); await tester.pump(turnEndDuration); await tester.pumpAndSettle(); expect(getOpponentCardRect(), equals(getClashRect())); }, ); testWidgets( 'render the win overlay on the player winning card', (tester) async { when( () => bloc.isWinningCard( Card( id: 'player_card', name: 'host_card', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), isPlayer: true, ), ).thenReturn(CardOverlayType.win); mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', showCardsOverlay: true, ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('win_card_overlay')), findsOneWidget, ); }, ); testWidgets( 'render the win overlay on the opponent winning card', (tester) async { when( () => bloc.isWinningCard( any(), isPlayer: false, ), ).thenReturn(CardOverlayType.win); mockState( baseState.copyWith( match: Match( id: '', hostDeck: baseState.match.hostDeck, guestDeck: Deck( id: '', userId: '', cards: const [ Card( id: 'opponent_card', name: 'guest_card', description: '', image: '', rarity: true, power: 10, suit: Suit.air, ), ], ), ), rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', showCardsOverlay: true, ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('win_card_overlay')), findsOneWidget, ); }, ); }); group('Card animation', () { late GameScriptMachine gameScriptMachine; final baseState = MatchLoadedState( playerScoreCard: ScoreCard(id: 'scoreCardId'), match: Match( id: '', hostDeck: Deck(id: '', userId: '', cards: playerCards), guestDeck: Deck(id: '', userId: '', cards: opponentCards), ), matchState: MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), rounds: const [], turnTimeRemaining: 10, turnAnimationsFinished: true, isClashScene: false, showCardLanding: false, ); setUp(() { gameScriptMachine = _MockGameScriptMachine(); when( () => gameScriptMachine.compare( playerCards.first, opponentCards.first, ), ).thenReturn(0); when( () => gameScriptMachine.compareSuits( playerCards.first.suit, opponentCards.first.suit, ), ).thenReturn(0); when(() => bloc.playerCards).thenReturn(playerCards); when(() => bloc.opponentCards).thenReturn(opponentCards); when(() => bloc.clashScenePlayerCard).thenReturn(playerCards.first); when(() => bloc.clashSceneOpponentCard).thenReturn(opponentCards.first); }); testWidgets('starts when player plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ) ]), initialState: baseState, ); await tester.pumpSubject(bloc); final cardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final initialOffset = tester.getCenter(cardFinder); await tester.pumpAndSettle(); final finalOffset = tester.getCenter(cardFinder); expect( initialOffset, isNot(equals(finalOffset)), ); }); testWidgets('starts when opponent plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: null, opponentCardId: opponentCards.first.id, ) ], ) ]), initialState: baseState, ); await tester.pumpSubject(bloc); final cardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); final initialOffset = tester.getCenter(cardFinder); await tester.pumpAndSettle(); final finalOffset = tester.getCenter(cardFinder); expect( initialOffset, isNot(equals(finalOffset)), ); }); testWidgets('completes when both players play a card', (tester) async { final controller = StreamController<GameState>(); final playedState = baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ); whenListen( bloc, controller.stream, initialState: baseState, ); when(() => bloc.add(CardLandingStarted())).thenAnswer((_) { controller.add(playedState.copyWith(showCardLanding: true)); }); await tester.pumpSubject(bloc); controller ..add(baseState) ..add(playedState); await tester.pumpAndSettle(); controller.add(playedState.copyWith(showCardLanding: false)); await tester.pumpAndSettle(); verify(() => bloc.add(ClashSceneStarted())).called(1); }); testWidgets( 'completes and goes back when both players play a card and ' 'clash scene finishes, plays round lost sfx', (tester) async { final controller = StreamController<GameState>.broadcast(); final audioController = _MockAudioController(); when(() => bloc.isWinningCard(playerCards.first, isPlayer: true)) .thenReturn(CardOverlayType.lose); whenListen( bloc, controller.stream, initialState: baseState, ); await tester.pumpSubject( bloc, audioController: audioController, gameScriptMachine: gameScriptMachine, ); final playerCardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final opponentCardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); // Get card offset before moving final playerInitialOffset = tester.getCenter(playerCardFinder); final opponentInitialOffset = tester.getCenter(opponentCardFinder); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ), ); // Get card offset after both players play and cards are in the clash // zone await tester.pumpAndSettle(); final playerClashOffset = tester.getCenter(playerCardFinder); expect(playerClashOffset, isNot(equals(playerInitialOffset))); controller.add( baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ), ); await tester.pump(); await tester.pump(); await tester.pump(Duration(milliseconds: 400)); final opponentClashOffset = tester.getCenter(opponentCardFinder); expect(opponentClashOffset, isNot(equals(opponentInitialOffset))); controller.add(baseState.copyWith(isClashScene: true)); await tester.pumpAndSettle(); final clashScene = find.byType(ClashScene); expect(clashScene, findsOneWidget); tester.widget<ClashScene>(clashScene).onFinished(); controller.add(baseState.copyWith(isClashScene: false)); // Get card offset once clash is over and both cards are back in the // original position await tester.pump(turnEndDuration); await tester.pumpAndSettle(); final playerFinalOffset = tester.getCenter(playerCardFinder); final opponentFinalOffset = tester.getCenter(opponentCardFinder); expect(playerFinalOffset, equals(playerInitialOffset)); expect(opponentFinalOffset, equals(opponentInitialOffset)); verify(() => audioController.playSfx(Assets.sfx.lostMatch)).called(1); verify(() => bloc.add(ClashSceneStarted())).called(1); verify(() => bloc.add(ClashSceneCompleted())).called(1); verify(() => bloc.add(TurnAnimationsFinished())).called(1); verify(() => bloc.add(TurnTimerStarted())).called(1); }, ); testWidgets( 'completes and goes back when both players play a card and ' 'clash scene finishes, plays round win sfx', (tester) async { final controller = StreamController<GameState>.broadcast(); final audioController = _MockAudioController(); when(() => bloc.isWinningCard(playerCards.first, isPlayer: true)) .thenReturn(CardOverlayType.win); whenListen( bloc, controller.stream, initialState: baseState, ); await tester.pumpSubject( bloc, audioController: audioController, gameScriptMachine: gameScriptMachine, ); final playerCardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final opponentCardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); // Get card offset before moving final playerInitialOffset = tester.getCenter(playerCardFinder); final opponentInitialOffset = tester.getCenter(opponentCardFinder); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ), ); // Get card offset after both players play and cards are in the clash // zone await tester.pumpAndSettle(); final playerClashOffset = tester.getCenter(playerCardFinder); expect(playerClashOffset, isNot(equals(playerInitialOffset))); controller.add( baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ), ); await tester.pump(); await tester.pump(); await tester.pump(Duration(milliseconds: 400)); final opponentClashOffset = tester.getCenter(opponentCardFinder); expect(opponentClashOffset, isNot(equals(opponentInitialOffset))); controller.add(baseState.copyWith(isClashScene: true)); await tester.pumpAndSettle(); final clashScene = find.byType(ClashScene); expect(clashScene, findsOneWidget); tester.widget<ClashScene>(clashScene).onFinished(); controller.add(baseState.copyWith(isClashScene: false)); // Get card offset once clash is over and both cards are back in the // original position await tester.pump(turnEndDuration); await tester.pumpAndSettle(); final playerFinalOffset = tester.getCenter(playerCardFinder); final opponentFinalOffset = tester.getCenter(opponentCardFinder); expect(playerFinalOffset, equals(playerInitialOffset)); expect(opponentFinalOffset, equals(opponentInitialOffset)); verify(() => audioController.playSfx(Assets.sfx.winMatch)).called(1); verify(() => bloc.add(ClashSceneStarted())).called(1); verify(() => bloc.add(ClashSceneCompleted())).called(1); verify(() => bloc.add(TurnAnimationsFinished())).called(1); verify(() => bloc.add(TurnTimerStarted())).called(1); }, ); testWidgets( 'completes and shows card landing puff effect when player plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ), ], showCardLanding: true, ), ]), initialState: baseState, ); await tester.pumpSubject(bloc); await tester.pump(bigFlipAnimation.duration); final cardLandingPuff = find.byType(CardLandingPuff); expect(cardLandingPuff, findsOneWidget); await tester.pumpAndSettle( bigFlipAnimation.duration + CardLandingPuff.duration, ); tester.widget<CardLandingPuff>(cardLandingPuff).onComplete?.call(); verify(() => bloc.add(CardLandingStarted())).called(1); verify(() => bloc.add(CardLandingCompleted())).called(1); }, ); }); }); group('CrossPainter', () { test('shouldRepaint always returns false', () { final painter = CrossPainter(); expect(painter.shouldRepaint(CrossPainter()), isFalse); }); }); } extension GameViewTest on WidgetTester { Future<void> pumpSubject( GameBloc bloc, { GoRouter? goRouter, LeaderboardResource? leaderboardResource, AudioController? audioController, GameScriptMachine? gameScriptMachine, }) { final SettingsController settingsController = _MockSettingsController(); when(() => settingsController.muted).thenReturn(ValueNotifier(true)); return mockNetworkImages(() { return pumpApp( BlocProvider<GameBloc>.value( value: bloc, child: GameView(), ), router: goRouter, settingsController: settingsController, leaderboardResource: leaderboardResource, audioController: audioController, gameScriptMachine: gameScriptMachine, ); }); } }
io_flip/test/game/views/game_view_test.dart/0
{ "file_path": "io_flip/test/game/views/game_view_test.dart", "repo_id": "io_flip", "token_count": 16689 }
915
import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart' as gd; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:mocktail/mocktail.dart'; class _MockLeaderboardResource extends Mock implements LeaderboardResource {} void main() { const leaderboardPlayers = [ gd.LeaderboardPlayer( id: 'id', longestStreak: 1, initials: 'AAA', ), gd.LeaderboardPlayer( id: 'id2', longestStreak: 2, initials: 'BBB', ), ]; group('LeaderboardBloc', () { late LeaderboardResource leaderboardResource; setUp(() { leaderboardResource = _MockLeaderboardResource(); when(() => leaderboardResource.getLeaderboardResults()) .thenAnswer((_) async => leaderboardPlayers); }); group('LeaderboardRequested', () { blocTest<LeaderboardBloc, LeaderboardState>( 'can request a leaderboard', build: () => LeaderboardBloc( leaderboardResource: leaderboardResource, ), act: (bloc) => bloc.add(const LeaderboardRequested()), expect: () => const [ LeaderboardState( status: LeaderboardStateStatus.loading, leaderboard: [], ), LeaderboardState( status: LeaderboardStateStatus.loaded, leaderboard: leaderboardPlayers, ), ], ); blocTest<LeaderboardBloc, LeaderboardState>( 'emits failure when an error occured', setUp: () { when(() => leaderboardResource.getLeaderboardResults()) .thenThrow(Exception('oops')); }, build: () => LeaderboardBloc( leaderboardResource: leaderboardResource, ), act: (bloc) => bloc.add(const LeaderboardRequested()), expect: () => const [ LeaderboardState( status: LeaderboardStateStatus.loading, leaderboard: [], ), LeaderboardState( status: LeaderboardStateStatus.failed, leaderboard: [], ), ], ); }); }); }
io_flip/test/leaderboard/bloc/leaderboard_bloc_test.dart/0
{ "file_path": "io_flip/test/leaderboard/bloc/leaderboard_bloc_test.dart", "repo_id": "io_flip", "token_count": 951 }
916
// ignore_for_file: prefer_const_constructors import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:mocktail/mocktail.dart'; class _MockPromptResource extends Mock implements PromptResource {} void main() { setUpAll(() { registerFallbackValue(PromptTermType.characterClass); }); group('PromptFormBloc', () { late PromptResource promptResource; const data = Prompt( characterClass: 'character', power: 'power', ); setUp(() { promptResource = _MockPromptResource(); }); blocTest<PromptFormBloc, PromptFormState>( 'emits state with prompts', setUp: () { when(() => promptResource.getPromptTerms(any())) .thenAnswer((_) async => ['test']); }, build: () => PromptFormBloc(promptResource: promptResource), seed: () => PromptFormState( status: PromptTermsStatus.loaded, prompts: Prompt(), ), act: (bloc) { bloc.add(PromptSubmitted(data: data)); }, expect: () => <PromptFormState>[ PromptFormState( status: PromptTermsStatus.loaded, prompts: data, ), ], ); blocTest<PromptFormBloc, PromptFormState>( 'emits state with error status', setUp: () { when(() => promptResource.getPromptTerms(any())) .thenThrow(Exception('Oops')); }, build: () => PromptFormBloc(promptResource: promptResource), act: (bloc) { bloc.add(PromptTermsRequested()); }, expect: () => <PromptFormState>[ PromptFormState( status: PromptTermsStatus.loading, prompts: Prompt(), ), PromptFormState( status: PromptTermsStatus.failed, prompts: Prompt(), ), ], ); }); }
io_flip/test/prompt/bloc/prompt_form_bloc_test.dart/0
{ "file_path": "io_flip/test/prompt/bloc/prompt_form_bloc_test.dart", "repo_id": "io_flip", "token_count": 844 }
917
import 'dart:typed_data'; import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:cross_file/cross_file.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/share/bloc/download_bloc.dart'; import 'package:mocktail/mocktail.dart'; class _MockShareResource extends Mock implements ShareResource {} class _MockXFile extends Mock implements XFile {} void main() { final XFile file = _MockXFile(); const card = Card( id: '0', name: '', description: '', image: '', rarity: false, power: 20, suit: Suit.fire, ); const deck = Deck(id: 'id', userId: 'userId', cards: [card]); group('DownloadBloc', () { late ShareResource shareResource; setUp(() { shareResource = _MockShareResource(); when(() => shareResource.getShareCardImage(any())) .thenAnswer((_) async => Uint8List(8)); when(() => shareResource.getShareDeckImage(any())) .thenAnswer((_) async => Uint8List(8)); when(() => file.saveTo(any())).thenAnswer((_) async {}); }); group('Download Cards Requested', () { blocTest<DownloadBloc, DownloadState>( 'can request a Download', build: () => DownloadBloc( shareResource: shareResource, parseBytes: (bytes, {String? mimeType, String? name}) { return file; }, ), act: (bloc) => bloc.add( const DownloadCardsRequested(cards: [card]), ), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.completed, ), ], ); blocTest<DownloadBloc, DownloadState>( 'emits failure when an error occurred', setUp: () { when(() => shareResource.getShareCardImage(any())) .thenThrow(Exception('oops')); }, build: () => DownloadBloc( shareResource: shareResource, ), act: (bloc) => bloc.add(const DownloadCardsRequested(cards: [card])), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.failure, ), ], ); }); group('Download Deck Requested', () { blocTest<DownloadBloc, DownloadState>( 'can request a Download', build: () => DownloadBloc( shareResource: shareResource, parseBytes: (bytes, {String? mimeType, String? name}) { return file; }, ), act: (bloc) => bloc.add( const DownloadDeckRequested(deck: deck), ), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.completed, ), ], ); blocTest<DownloadBloc, DownloadState>( 'emits failure when an error occurred', setUp: () { when(() => shareResource.getShareDeckImage(any())) .thenThrow(Exception('oops')); }, build: () => DownloadBloc( shareResource: shareResource, ), act: (bloc) => bloc.add(const DownloadDeckRequested(deck: deck)), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.failure, ), ], ); }); }); }
io_flip/test/share/bloc/download_bloc_test.dart/0
{ "file_path": "io_flip/test/share/bloc/download_bloc_test.dart", "repo_id": "io_flip", "token_count": 1652 }
918
{ "name": "I/O FLIP", "short_name": "I/O FLIP", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "Google I/O FLIP game", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" } ] }
io_flip/web/manifest.json/0
{ "file_path": "io_flip/web/manifest.json", "repo_id": "io_flip", "token_count": 310 }
919
{ "singleQuote": true }
news_toolkit/docs/.prettierrc/0
{ "file_path": "news_toolkit/docs/.prettierrc", "repo_id": "news_toolkit", "token_count": 11 }
920
{ "label": "Project Configuration", "position": 3, "link": { "title": "Project Configuration", "type": "generated-index", "description": "Setup your project so you can start development." } }
news_toolkit/docs/docs/project_configuration/_category_.json/0
{ "file_path": "news_toolkit/docs/docs/project_configuration/_category_.json", "repo_id": "news_toolkit", "token_count": 69 }
921
// @ts-check // Note: type annotations allow type checking and IDEs autocompletion /** @type {import('@docusaurus/types').Config} */ const config = { title: 'Flutter News Toolkit', tagline: 'A high-quality news app template powered by Flutter and Dart.', url: 'https://flutter.github.io', baseUrl: '/news_toolkit/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'img/favicon.ico', organizationName: 'flutter', projectName: 'flutter-news-toolkit-docs', // Even if you don't use internalization, you can use this field to set useful // metadata like html lang. For example, if your site is Chinese, you may want // to replace "en" with "zh-Hans". i18n: { defaultLocale: 'en', locales: ['en'], }, presets: [ [ 'classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { routeBasePath: '/', sidebarPath: require.resolve('./sidebars.js'), editUrl: 'https://github.com/flutter/news_toolkit/tree/main/docs/', }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ themeConfig: { colorMode: { defaultMode: 'light', disableSwitch: false, respectPrefersColorScheme: false, }, }, navbar: { title: 'Flutter News Toolkit', logo: { alt: 'Flutter News Toolkit Logo', src: 'img/logo.svg', }, items: [ { href: 'https://github.com/flutter/news_toolkit', position: 'right', className: 'navbar-github-icon', 'aria-label': 'GitHub repository', }, ], }, footer: { links: [ { title: 'Docs', items: [ { label: 'Getting Started', to: '/', }, ], }, { title: 'Resources', items: [ { label: 'Codelab', href: '#', }, ], }, { title: 'More', items: [ { label: 'GitHub', href: 'https://github.com/flutter/news_toolkit', }, ], }, ], copyright: `Copyright Β© ${new Date().getFullYear()} Google, Inc.`, }, prism: { additionalLanguages: ['bash', 'dart', 'yaml'], }, }), }; module.exports = config;
news_toolkit/docs/docusaurus.config.js/0
{ "file_path": "news_toolkit/docs/docusaurus.config.js", "repo_id": "news_toolkit", "token_count": 1368 }
922
{ "project_info": { "project_number": "737894073936", "project_id": "news-template-644a1", "storage_bucket": "news-template-644a1.appspot.com" }, "client": [ { "client_info": { "mobilesdk_app_id": "1:737894073936:android:dce282f64abfa89eb03355", "android_client_info": { "package_name": "com.flutter.news.example.dev" } }, "oauth_client": [ { "client_id": "737894073936-epltqsgbon16uf53qm3l49vsva3ejp7f.apps.googleusercontent.com", "client_type": 1, "android_info": { "package_name": "com.flutter.news.example.dev", "certificate_hash": "7269ff6c92958ba1a5d983636e86427be50a0ab6" } }, { "client_id": "737894073936-o8ftmcj7vvucpdrlqn49tatu67ito1t1.apps.googleusercontent.com", "client_type": 3 } ], "api_key": [ { "current_key": "AIzaSyD8mYU4ynL0L9wJyL2ocCGj96M4K2llwTo" } ], "services": { "appinvite_service": { "other_platform_oauth_client": [ { "client_id": "737894073936-o8ftmcj7vvucpdrlqn49tatu67ito1t1.apps.googleusercontent.com", "client_type": 3 }, { "client_id": "737894073936-ccvknt0jpr1nk3uhftg14k8duirosg9t.apps.googleusercontent.com", "client_type": 2, "ios_info": { "bundle_id": "com.flutter.news.example.dev", "app_store_id": "123456789" } } ] } } } ], "configuration_version": "1" }
news_toolkit/flutter_news_example/android/app/src/development/google-services.json/0
{ "file_path": "news_toolkit/flutter_news_example/android/app/src/development/google-services.json", "repo_id": "news_toolkit", "token_count": 972 }
923
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="facebook_app_id">3068290313391198</string> <string name="facebook_client_token">7a51baf0a329829a55e6ab8ced3da73a</string> <string name="twitter_redirect_uri_scheme">google-news-template</string> <string name="flavor_deep_link_domain">googlenewstemplatedev.page.link</string> <string name="admob_app_id">ca-app-pub-3940256099942544~3347511713</string> </resources>
news_toolkit/flutter_news_example/android/app/src/development/res/values/strings.xml/0
{ "file_path": "news_toolkit/flutter_news_example/android/app/src/development/res/values/strings.xml", "repo_id": "news_toolkit", "token_count": 181 }
924
import 'dart:math' as math; import 'package:collection/collection.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:flutter_news_example_api/src/data/models/models.dart'; import 'package:news_blocks/news_blocks.dart'; part 'static_news_data.dart'; /// {@template in_memory_news_data_source} /// An implementation of [NewsDataSource] which /// is powered by in-memory news content. /// {@endtemplate} class InMemoryNewsDataSource implements NewsDataSource { /// {@macro in_memory_news_data_store} InMemoryNewsDataSource() : _userSubscriptions = <String, String>{}; final Map<String, String> _userSubscriptions; @override Future<void> createSubscription({ required String userId, required String subscriptionId, }) async { final subscriptionPlan = subscriptions .firstWhereOrNull((subscription) => subscription.id == subscriptionId) ?.name; if (subscriptionPlan != null) { _userSubscriptions[userId] = subscriptionPlan.name; } } @override Future<List<Subscription>> getSubscriptions() async => subscriptions; @override Future<Article?> getArticle({ required String id, int limit = 20, int offset = 0, bool preview = false, }) async { final result = _newsItems.where((item) => item.post.id == id); if (result.isEmpty) return null; final articleNewsItem = result.first; final article = (preview ? articleNewsItem.contentPreview : articleNewsItem.content) .toArticle(title: articleNewsItem.post.title, url: articleNewsItem.url); final totalBlocks = article.totalBlocks; final normalizedOffset = math.min(offset, totalBlocks); final blocks = article.blocks.sublist(normalizedOffset).take(limit).toList(); return Article( title: article.title, blocks: blocks, totalBlocks: totalBlocks, url: article.url, ); } @override Future<bool?> isPremiumArticle({required String id}) async { final result = _newsItems.where((item) => item.post.id == id); if (result.isEmpty) return null; return result.first.post.isPremium; } @override Future<List<NewsBlock>> getPopularArticles() async { return popularArticles.map((item) => item.post).toList(); } @override Future<List<NewsBlock>> getRelevantArticles({required String term}) async { return relevantArticles.map((item) => item.post).toList(); } @override Future<List<String>> getRelevantTopics({required String term}) async { return relevantTopics; } @override Future<List<String>> getPopularTopics() async => popularTopics; @override Future<RelatedArticles> getRelatedArticles({ required String id, int limit = 20, int offset = 0, }) async { final result = _newsItems.where((item) => item.post.id == id); if (result.isEmpty) return const RelatedArticles.empty(); final articles = result.first.relatedArticles; final totalBlocks = articles.length; final normalizedOffset = math.min(offset, totalBlocks); final blocks = articles.sublist(normalizedOffset).take(limit).toList(); return RelatedArticles(blocks: blocks, totalBlocks: totalBlocks); } @override Future<Feed> getFeed({ Category category = Category.top, int limit = 20, int offset = 0, }) async { final feed = _newsFeedData[category] ?? const Feed(blocks: [], totalBlocks: 0); final totalBlocks = feed.totalBlocks; final normalizedOffset = math.min(offset, totalBlocks); final blocks = feed.blocks.sublist(normalizedOffset).take(limit).toList(); return Feed(blocks: blocks, totalBlocks: totalBlocks); } @override Future<List<Category>> getCategories() async => _newsFeedData.keys.toList(); @override Future<User> getUser({required String userId}) async { final subscription = _userSubscriptions[userId]; if (subscription == null) { return User(id: userId, subscription: SubscriptionPlan.none); } return User( id: userId, subscription: SubscriptionPlan.values.firstWhere( (e) => e.name == subscription, ), ); } }
news_toolkit/flutter_news_example/api/lib/src/data/in_memory_news_data_source.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/data/in_memory_news_data_source.dart", "repo_id": "news_toolkit", "token_count": 1410 }
925
import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; final _newsDataSource = InMemoryNewsDataSource(); /// Provider a [NewsDataSource] to the current [RequestContext]. Middleware newsDataSourceProvider() { return (handler) { return handler.use(provider<NewsDataSource>((_) => _newsDataSource)); }; }
news_toolkit/flutter_news_example/api/lib/src/middleware/news_data_source_provider.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/middleware/news_data_source_provider.dart", "repo_id": "news_toolkit", "token_count": 114 }
926
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'relevant_search_response.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** RelevantSearchResponse _$RelevantSearchResponseFromJson( Map<String, dynamic> json) => RelevantSearchResponse( articles: const NewsBlocksConverter().fromJson(json['articles'] as List), topics: (json['topics'] as List<dynamic>).map((e) => e as String).toList(), ); Map<String, dynamic> _$RelevantSearchResponseToJson( RelevantSearchResponse instance) => <String, dynamic>{ 'articles': const NewsBlocksConverter().toJson(instance.articles), 'topics': instance.topics, };
news_toolkit/flutter_news_example/api/lib/src/models/relevant_search_response/relevant_search_response.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/models/relevant_search_response/relevant_search_response.g.dart", "repo_id": "news_toolkit", "token_count": 253 }
927
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'divider_horizontal_block.g.dart'; /// {@template divider_horizontal_block} /// A block which represents a divider horizontal. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=355%3A15499 /// {@endtemplate} @JsonSerializable() class DividerHorizontalBlock with EquatableMixin implements NewsBlock { /// {@macro divider_horizontal_block} const DividerHorizontalBlock({ this.type = DividerHorizontalBlock.identifier, }); /// Converts a `Map<String, dynamic>` into /// a [DividerHorizontalBlock] instance. factory DividerHorizontalBlock.fromJson(Map<String, dynamic> json) => _$DividerHorizontalBlockFromJson(json); /// The divider horizontal block type identifier. static const identifier = '__divider_horizontal__'; @override final String type; @override Map<String, dynamic> toJson() => _$DividerHorizontalBlockToJson(this); @override List<Object?> get props => [type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/divider_horizontal_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/divider_horizontal_block.dart", "repo_id": "news_toolkit", "token_count": 372 }
928
import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'post_large_block.g.dart'; /// {@template post_large_block} /// A block which represents a large post block. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=391%3A18585 /// {@endtemplate} @JsonSerializable() class PostLargeBlock extends PostBlock { /// {@macro post_large_block} const PostLargeBlock({ required super.id, required super.category, required super.author, required super.publishedAt, required String super.imageUrl, required super.title, super.description, super.action, super.type = PostLargeBlock.identifier, super.isPremium, super.isContentOverlaid, }); /// Converts a `Map<String, dynamic>` into a [PostLargeBlock] instance. factory PostLargeBlock.fromJson(Map<String, dynamic> json) => _$PostLargeBlockFromJson(json); /// The large post block type identifier. static const identifier = '__post_large__'; @override Map<String, dynamic> toJson() => _$PostLargeBlockToJson(this); }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_large_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_large_block.dart", "repo_id": "news_toolkit", "token_count": 392 }
929
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'text_caption_block.g.dart'; /// The text color of [TextCaptionBlock]. enum TextCaptionColor { /// The normal text color. normal, /// The light text color. light, } /// {@template text_caption_block} /// A block which represents a text caption. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=365%3A35853 /// {@endtemplate} @JsonSerializable() class TextCaptionBlock with EquatableMixin implements NewsBlock { /// {@macro text_caption_block} const TextCaptionBlock({ required this.text, required this.color, this.type = TextCaptionBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [TextCaptionBlock] instance. factory TextCaptionBlock.fromJson(Map<String, dynamic> json) => _$TextCaptionBlockFromJson(json); /// The text caption block type identifier. static const identifier = '__text_caption__'; /// The color of this text caption. final TextCaptionColor color; /// The text of this text caption. final String text; @override final String type; @override Map<String, dynamic> toJson() => _$TextCaptionBlockToJson(this); @override List<Object?> get props => [text, color, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_caption_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_caption_block.dart", "repo_id": "news_toolkit", "token_count": 459 }
930
name: news_blocks description: Reusable News Blocks for the Flutter News Example Application version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: equatable: ^2.0.3 json_annotation: ^4.6.0 meta: ^1.7.0 dev_dependencies: build_runner: ^2.0.0 coverage: ^1.1.0 json_serializable: ^6.0.0 mocktail: ^1.0.2 test: ^1.21.4 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/api/packages/news_blocks/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 177 }
931
import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('PostMediumBlock', () { test('can be (de)serialized', () { final block = PostMediumBlock( id: 'id', category: PostCategory.sports, author: 'author', publishedAt: DateTime(2022, 3, 10), imageUrl: 'imageUrl', title: 'title', ); expect(PostMediumBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_medium_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_medium_block_test.dart", "repo_id": "news_toolkit", "token_count": 207 }
932
name: flutter_news_example_api description: A Flutter News Example server app built with the dart_frog package. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: collection: ^1.16.0 dart_frog: ^1.1.0 equatable: ^2.0.5 http: ^1.0.0 json_annotation: ^4.6.0 news_blocks: path: packages/news_blocks dev_dependencies: build_runner: ^2.4.8 json_serializable: ^6.7.1 mocktail: ^1.0.2 test: ^1.25.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/api/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/api/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 215 }
933
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; import '../../../routes/api/v1/feed/index.dart' as route; class _MockFeed extends Mock implements Feed {} class _MockNewsDataSource extends Mock implements NewsDataSource {} class _MockRequestContext extends Mock implements RequestContext {} void main() { group('GET /api/v1/feed', () { late NewsDataSource newsDataSource; setUpAll(() { registerFallbackValue(Category.top); }); setUp(() { newsDataSource = _MockNewsDataSource(); }); test('responds with a 200 on success.', () async { final blocks = <NewsBlock>[]; final feed = _MockFeed(); when(() => feed.blocks).thenReturn(blocks); when(() => feed.totalBlocks).thenReturn(blocks.length); when( () => newsDataSource.getFeed( category: any(named: 'category'), limit: any(named: 'limit'), offset: any(named: 'offset'), ), ).thenAnswer((_) async => feed); final expected = FeedResponse(feed: blocks, totalCount: blocks.length); final request = Request('GET', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(await response.json(), equals(expected.toJson())); }); test('parses category, limit, and offset correctly.', () async { const category = Category.entertainment; const limit = 42; const offset = 7; final blocks = <NewsBlock>[]; final feed = _MockFeed(); when(() => feed.blocks).thenReturn(blocks); when(() => feed.totalBlocks).thenReturn(blocks.length); when( () => newsDataSource.getFeed( category: any(named: 'category'), limit: any(named: 'limit'), offset: any(named: 'offset'), ), ).thenAnswer((_) async => feed); final expected = FeedResponse(feed: blocks, totalCount: blocks.length); final request = Request( 'GET', Uri.parse('http://127.0.0.1/').replace( queryParameters: <String, String>{ 'category': category.name, 'limit': '$limit', 'offset': '$offset', }, ), ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(await response.json(), equals(expected.toJson())); verify( () => newsDataSource.getFeed( category: category, limit: limit, offset: offset, ), ).called(1); }); }); test('responds with 405 when method is not GET.', () async { final request = Request('POST', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }
news_toolkit/flutter_news_example/api/test/routes/feed/index_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/feed/index_test.dart", "repo_id": "news_toolkit", "token_count": 1363 }
934
tags: presubmit-only:
news_toolkit/flutter_news_example/dart_test.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/dart_test.yaml", "repo_id": "news_toolkit", "token_count": 11 }
935
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart' as ads; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:platform/platform.dart'; part 'full_screen_ads_event.dart'; part 'full_screen_ads_state.dart'; /// Signature for the interstitial ad loader. typedef InterstitialAdLoader = Future<void> Function({ required String adUnitId, required ads.InterstitialAdLoadCallback adLoadCallback, required ads.AdRequest request, }); /// Signature for the rewarded ad loader. typedef RewardedAdLoader = Future<void> Function({ required String adUnitId, required ads.RewardedAdLoadCallback rewardedAdLoadCallback, required ads.AdRequest request, }); /// A bloc that manages pre-loading and showing interstitial and rewarded ads /// with an [_adsRetryPolicy]. class FullScreenAdsBloc extends Bloc<FullScreenAdsEvent, FullScreenAdsState> { FullScreenAdsBloc({ required AdsRetryPolicy adsRetryPolicy, required InterstitialAdLoader interstitialAdLoader, required RewardedAdLoader rewardedAdLoader, required LocalPlatform localPlatform, FullScreenAdsConfig? fullScreenAdsConfig, }) : _adsRetryPolicy = adsRetryPolicy, _interstitialAdLoader = interstitialAdLoader, _rewardedAdLoader = rewardedAdLoader, _localPlatform = localPlatform, _fullScreenAdsConfig = fullScreenAdsConfig ?? const FullScreenAdsConfig(), super(const FullScreenAdsState.initial()) { on<LoadInterstitialAdRequested>(_onLoadInterstitialAdRequested); on<LoadRewardedAdRequested>(_onLoadRewardedAdRequested); on<ShowInterstitialAdRequested>(_onShowInterstitialAdRequested); on<ShowRewardedAdRequested>(_onShowRewardedAdRequested); on<EarnedReward>(_onEarnedReward); } /// The retry policy for loading interstitial and rewarded ads. final AdsRetryPolicy _adsRetryPolicy; /// The config of interstitial and rewarded ads. final FullScreenAdsConfig _fullScreenAdsConfig; /// The loader of interstitial ads. final InterstitialAdLoader _interstitialAdLoader; /// The loader of rewarded ads. final RewardedAdLoader _rewardedAdLoader; /// The current platform. final LocalPlatform _localPlatform; Future<void> _onLoadInterstitialAdRequested( LoadInterstitialAdRequested event, Emitter<FullScreenAdsState> emit, ) async { try { final ad = Completer<ads.InterstitialAd>(); emit(state.copyWith(status: FullScreenAdsStatus.loadingInterstitialAd)); await _interstitialAdLoader( adUnitId: _fullScreenAdsConfig.interstitialAdUnitId ?? (_localPlatform.isAndroid ? FullScreenAdsConfig.androidTestInterstitialAdUnitId : FullScreenAdsConfig.iosTestInterstitialAdUnitId), request: const ads.AdRequest(), adLoadCallback: ads.InterstitialAdLoadCallback( onAdLoaded: ad.complete, onAdFailedToLoad: ad.completeError, ), ); final adResult = await ad.future; emit( state.copyWith( interstitialAd: adResult, status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, ), ); } catch (error, stackTrace) { emit( state.copyWith( status: FullScreenAdsStatus.loadingInterstitialAdFailed, ), ); addError(error, stackTrace); if (event.retry < _adsRetryPolicy.maxRetryCount) { final nextRetry = event.retry + 1; await Future<void>.delayed( _adsRetryPolicy.getIntervalForRetry(nextRetry), ); add(LoadInterstitialAdRequested(retry: nextRetry)); } } } Future<void> _onLoadRewardedAdRequested( LoadRewardedAdRequested event, Emitter<FullScreenAdsState> emit, ) async { try { final ad = Completer<ads.RewardedAd>(); emit(state.copyWith(status: FullScreenAdsStatus.loadingRewardedAd)); await _rewardedAdLoader( adUnitId: _fullScreenAdsConfig.rewardedAdUnitId ?? (_localPlatform.isAndroid ? FullScreenAdsConfig.androidTestRewardedAdUnitId : FullScreenAdsConfig.iosTestRewardedAdUnitId), request: const ads.AdRequest(), rewardedAdLoadCallback: ads.RewardedAdLoadCallback( onAdLoaded: ad.complete, onAdFailedToLoad: ad.completeError, ), ); final adResult = await ad.future; emit( state.copyWith( rewardedAd: adResult, status: FullScreenAdsStatus.loadingRewardedAdSucceeded, ), ); } catch (error, stackTrace) { emit( state.copyWith( status: FullScreenAdsStatus.loadingRewardedAdFailed, ), ); addError(error, stackTrace); if (event.retry < _adsRetryPolicy.maxRetryCount) { final nextRetry = event.retry + 1; await Future<void>.delayed( _adsRetryPolicy.getIntervalForRetry(nextRetry), ); add(LoadRewardedAdRequested(retry: nextRetry)); } } } Future<void> _onShowInterstitialAdRequested( ShowInterstitialAdRequested event, Emitter<FullScreenAdsState> emit, ) async { try { emit(state.copyWith(status: FullScreenAdsStatus.showingInterstitialAd)); state.interstitialAd?.fullScreenContentCallback = ads.FullScreenContentCallback( onAdDismissedFullScreenContent: (ad) => ad.dispose(), onAdFailedToShowFullScreenContent: (ad, error) { ad.dispose(); addError(error); }, ); // Show currently available interstitial ad. await state.interstitialAd?.show(); emit( state.copyWith( status: FullScreenAdsStatus.showingInterstitialAdSucceeded, ), ); // Load the next interstitial ad. add(const LoadInterstitialAdRequested()); } catch (error, stackTrace) { emit( state.copyWith( status: FullScreenAdsStatus.showingInterstitialAdFailed, ), ); addError(error, stackTrace); } } Future<void> _onShowRewardedAdRequested( ShowRewardedAdRequested event, Emitter<FullScreenAdsState> emit, ) async { try { emit(state.copyWith(status: FullScreenAdsStatus.showingRewardedAd)); state.rewardedAd?.fullScreenContentCallback = ads.FullScreenContentCallback( onAdDismissedFullScreenContent: (ad) => ad.dispose(), onAdFailedToShowFullScreenContent: (ad, error) { ad.dispose(); addError(error); }, ); // Show currently available rewarded ad. await state.rewardedAd?.show( onUserEarnedReward: (ad, earnedReward) => add( EarnedReward(earnedReward), ), ); emit( state.copyWith( status: FullScreenAdsStatus.showingRewardedAdSucceeded, ), ); // Load the next rewarded ad. add(const LoadRewardedAdRequested()); } catch (error, stackTrace) { emit( state.copyWith( status: FullScreenAdsStatus.showingRewardedAdFailed, ), ); addError(error, stackTrace); } } void _onEarnedReward(EarnedReward event, Emitter<FullScreenAdsState> emit) => emit(state.copyWith(earnedReward: event.reward)); }
news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_bloc.dart", "repo_id": "news_toolkit", "token_count": 2940 }
936
export 'authenticated_user_listener.dart';
news_toolkit/flutter_news_example/lib/app/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/app/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 14 }
937
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'categories_bloc.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** CategoriesState _$CategoriesStateFromJson(Map<String, dynamic> json) => CategoriesState( status: $enumDecode(_$CategoriesStatusEnumMap, json['status']), categories: (json['categories'] as List<dynamic>?) ?.map((e) => $enumDecode(_$CategoryEnumMap, e)) .toList(), selectedCategory: $enumDecodeNullable(_$CategoryEnumMap, json['selectedCategory']), ); Map<String, dynamic> _$CategoriesStateToJson(CategoriesState instance) => <String, dynamic>{ 'status': _$CategoriesStatusEnumMap[instance.status]!, 'categories': instance.categories?.map((e) => _$CategoryEnumMap[e]!).toList(), 'selectedCategory': _$CategoryEnumMap[instance.selectedCategory], }; const _$CategoriesStatusEnumMap = { CategoriesStatus.initial: 'initial', CategoriesStatus.loading: 'loading', CategoriesStatus.populated: 'populated', CategoriesStatus.failure: 'failure', }; const _$CategoryEnumMap = { Category.business: 'business', Category.entertainment: 'entertainment', Category.top: 'top', Category.health: 'health', Category.science: 'science', Category.sports: 'sports', Category.technology: 'technology', };
news_toolkit/flutter_news_example/lib/categories/bloc/categories_bloc.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/categories/bloc/categories_bloc.g.dart", "repo_id": "news_toolkit", "token_count": 480 }
938
export 'category_feed.dart'; export 'category_feed_item.dart'; export 'category_feed_loader_item.dart';
news_toolkit/flutter_news_example/lib/feed/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/feed/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 36 }
939
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:user_repository/user_repository.dart'; class LoginModal extends StatelessWidget { const LoginModal({super.key}); static Route<void> route() => MaterialPageRoute<void>(builder: (_) => const LoginModal()); static const String name = '/loginModal'; @override Widget build(BuildContext context) { return BlocProvider( create: (_) => LoginBloc( userRepository: context.read<UserRepository>(), ), child: const LoginForm(), ); } }
news_toolkit/flutter_news_example/lib/login/view/login_modal.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/view/login_modal.dart", "repo_id": "news_toolkit", "token_count": 228 }
940
import 'package:flutter/material.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; @visibleForTesting class BottomNavBar extends StatelessWidget { const BottomNavBar({ required this.currentIndex, required this.onTap, super.key, }); final int currentIndex; final ValueSetter<int> onTap; @override Widget build(BuildContext context) { return BottomNavigationBar( items: [ BottomNavigationBarItem( icon: const Icon(Icons.home_outlined), label: context.l10n.bottomNavBarTopStories, ), BottomNavigationBarItem( icon: const Icon( Icons.search, key: Key('bottomNavBar_search'), ), label: context.l10n.bottomNavBarSearch, ), ], currentIndex: currentIndex, onTap: onTap, ); } }
news_toolkit/flutter_news_example/lib/navigation/view/bottom_nav_bar.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/navigation/view/bottom_nav_bar.dart", "repo_id": "news_toolkit", "token_count": 367 }
941
export 'bloc/notification_preferences_bloc.dart'; export 'view/view.dart'; export 'widgets/widgets.dart';
news_toolkit/flutter_news_example/lib/notification_preferences/notification_preferences.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/notification_preferences.dart", "repo_id": "news_toolkit", "token_count": 41 }
942
part of 'search_bloc.dart'; enum SearchStatus { initial, loading, populated, failure, } enum SearchType { popular, relevant, } class SearchState extends Equatable { const SearchState({ required this.articles, required this.topics, required this.status, required this.searchType, }); const SearchState.initial() : this( articles: const [], topics: const [], status: SearchStatus.initial, searchType: SearchType.popular, ); final List<NewsBlock> articles; final List<String> topics; final SearchStatus status; final SearchType searchType; @override List<Object?> get props => [articles, topics, status, searchType]; SearchState copyWith({ List<NewsBlock>? articles, List<String>? topics, SearchStatus? status, SearchType? searchType, }) => SearchState( articles: articles ?? this.articles, topics: topics ?? this.topics, status: status ?? this.status, searchType: searchType ?? this.searchType, ); }
news_toolkit/flutter_news_example/lib/search/bloc/search_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/bloc/search_state.dart", "repo_id": "news_toolkit", "token_count": 397 }
943
export 'bloc/subscriptions_bloc.dart'; export 'view/purchase_subscription_dialog.dart';
news_toolkit/flutter_news_example/lib/subscriptions/dialog/dialog.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/dialog/dialog.dart", "repo_id": "news_toolkit", "token_count": 33 }
944
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; part 'theme_mode_event.dart'; /// Keeps track of and allows changing the application's [ThemeMode]. class ThemeModeBloc extends HydratedBloc<ThemeModeEvent, ThemeMode> { /// Create a new object ThemeModeBloc() : super(ThemeMode.system) { on<ThemeModeChanged>((event, emit) => emit(event.themeMode ?? state)); } @override ThemeMode fromJson(Map<dynamic, dynamic> json) => ThemeMode.values[json['theme_mode'] as int]; @override Map<String, int> toJson(ThemeMode state) => {'theme_mode': state.index}; }
news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_bloc.dart", "repo_id": "news_toolkit", "token_count": 225 }
945
export 'src/ads_consent_client.dart';
news_toolkit/flutter_news_example/packages/ads_consent_client/lib/ads_consent_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/ads_consent_client/lib/ads_consent_client.dart", "repo_id": "news_toolkit", "token_count": 15 }
946
# gallery Gallery project to showcase app_ui
news_toolkit/flutter_news_example/packages/app_ui/gallery/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/README.md", "repo_id": "news_toolkit", "token_count": 12 }
947
export 'spacing_page.dart';
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing.dart", "repo_id": "news_toolkit", "token_count": 11 }
948
export 'app_font_weight.dart'; export 'app_text_styles.dart';
news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/typography.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/typography/typography.dart", "repo_id": "news_toolkit", "token_count": 24 }
949
// ignore_for_file: prefer_const_literals_to_create_immutables // ignore_for_file: prefer_const_constructors // ignore_for_file: avoid_redundant_argument_values import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../helpers/helpers.dart'; void main() { group('AppButton', () { final theme = AppTheme().themeData; final buttonTextTheme = theme.textTheme.labelLarge!.copyWith( inherit: false, ); testWidgets('renders button', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( Column( children: [ AppButton.black( child: buttonText, ), AppButton.smallOutlineTransparent( child: buttonText, ), AppButton.redWine( child: buttonText, ), AppButton.blueDress( child: buttonText, ), ], ), ); expect(find.byType(AppButton), findsNWidgets(4)); expect(find.text('buttonText'), findsNWidgets(4)); }); testWidgets( 'renders black button ' 'when `AppButton.black()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.black( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.black, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders blueDress button ' 'when `AppButton.blueDress()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.blueDress( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.blueDress, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders crystalBlue button ' 'when `AppButton.crystalBlue()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.crystalBlue( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.crystalBlue, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders redWine button ' 'when `AppButton.redWine()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.redWine( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.redWine, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders secondary button ' 'when `AppButton.secondary()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.secondary( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.secondary, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 40), ); expect( widget.style?.minimumSize?.resolve({}), Size(0, 40), ); }); testWidgets( 'renders darkAqua button ' 'when `AppButton.darkAqua()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.darkAqua( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.darkAqua, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders outlinedWhite button ' 'when `AppButton.outlinedWhite()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.outlinedWhite( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.white, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders outlinedTransparentDarkAqua button ' 'when `AppButton.outlinedTransparentDarkAqua()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.outlinedTransparentDarkAqua( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders outlinedTransparentWhite button ' 'when `AppButton.outlinedTransparentWhite()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.outlinedTransparentWhite( onPressed: () {}, child: buttonText, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.foregroundColor?.resolve({}), AppColors.white, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders smallRedWine button ' 'when `AppButton.smallRedWine()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.smallRedWine( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.redWine, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 40), ); expect( widget.style?.minimumSize?.resolve({}), Size(0, 40), ); }); testWidgets( 'renders smallDarkAqua button ' 'when `AppButton.smallDarkAqua()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.smallDarkAqua( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.darkAqua, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 40), ); expect( widget.style?.minimumSize?.resolve({}), Size(0, 40), ); }); testWidgets( 'renders smallTransparent button ' 'when `AppButton.smallTransparent()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.smallTransparent( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 40), ); expect( widget.style?.minimumSize?.resolve({}), Size(0, 40), ); }); testWidgets( 'renders smallOutlineTransparent button ' 'when `AppButton.smallOutlineTransparent()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.smallOutlineTransparent( child: buttonText, onPressed: () {}, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 40), ); expect( widget.style?.minimumSize?.resolve({}), Size(0, 40), ); }); testWidgets( 'renders transparentDarkAqua button ' 'when `AppButton.transparentDarkAqua()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.transparentDarkAqua( onPressed: () {}, child: buttonText, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.foregroundColor?.resolve({}), AppColors.darkAqua, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders transparentWhite button ' 'when `AppButton.transparentWhite()` called', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.transparentWhite( onPressed: () {}, child: buttonText, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.foregroundColor?.resolve({}), AppColors.white, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'renders disabled transparentWhite button ' 'when `AppButton.transparentWhite()` called ' 'with onPressed equal to null', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.transparentWhite( onPressed: null, child: buttonText, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.transparent, ); expect( widget.style?.foregroundColor?.resolve({}), AppColors.white, ); expect( widget.style?.textStyle?.resolve({}), buttonTextTheme, ); expect( widget.style?.maximumSize?.resolve({}), Size(double.infinity, 56), ); expect( widget.style?.minimumSize?.resolve({}), Size(double.infinity, 56), ); }); testWidgets( 'changes background color to AppColors.black.withOpacity(.12) ' 'when `onPressed` is null', (tester) async { final buttonText = Text('buttonText'); await tester.pumpApp( AppButton.smallOutlineTransparent( child: buttonText, ), theme: theme, ); final finder = find.byType(ElevatedButton); final widget = tester.widget(finder) as ElevatedButton; expect( widget.style?.backgroundColor?.resolve({}), AppColors.black.withOpacity(.12), ); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_button_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_button_test.dart", "repo_id": "news_toolkit", "token_count": 7605 }
950
import 'package:article_repository/article_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:storage/storage.dart'; import 'package:test/test.dart'; class MockStorage extends Mock implements Storage {} void main() { group('ArticleStorage', () { late Storage storage; setUp(() { storage = MockStorage(); when( () => storage.write( key: any(named: 'key'), value: any(named: 'value'), ), ).thenAnswer((_) async {}); }); group('setArticleViews', () { test('saves the value in Storage', () async { const views = 3; await ArticleStorage(storage: storage).setArticleViews(views); verify( () => storage.write( key: ArticleStorageKeys.articleViews, value: views.toString(), ), ).called(1); }); }); group('fetchArticleViews', () { test('returns the value from Storage', () async { when( () => storage.read(key: ArticleStorageKeys.articleViews), ).thenAnswer((_) async => '3'); final result = await ArticleStorage(storage: storage).fetchArticleViews(); verify( () => storage.read( key: ArticleStorageKeys.articleViews, ), ).called(1); expect(result, equals(3)); }); test('returns 0 when no value exists in Storage', () async { when( () => storage.read(key: ArticleStorageKeys.articleViews), ).thenAnswer((_) async => null); final result = await ArticleStorage(storage: storage).fetchArticleViews(); verify( () => storage.read( key: ArticleStorageKeys.articleViews, ), ).called(1); expect(result, isZero); }); }); group('setArticleViewsResetDate', () { test('saves the value in Storage', () async { final date = DateTime(2022, 6, 7); await ArticleStorage(storage: storage).setArticleViewsResetDate(date); verify( () => storage.write( key: ArticleStorageKeys.articleViewsResetAt, value: date.toIso8601String(), ), ).called(1); }); }); group('fetchArticleViewsResetDate', () { test('returns the value from Storage', () async { final date = DateTime(2022, 6, 7); when( () => storage.read(key: ArticleStorageKeys.articleViewsResetAt), ).thenAnswer((_) async => date.toIso8601String()); final result = await ArticleStorage(storage: storage).fetchArticleViewsResetDate(); verify( () => storage.read( key: ArticleStorageKeys.articleViewsResetAt, ), ).called(1); expect(result, equals(date)); }); test('returns null when no value exists in Storage', () async { when( () => storage.read(key: ArticleStorageKeys.articleViewsResetAt), ).thenAnswer((_) async => null); final result = await ArticleStorage(storage: storage).fetchArticleViewsResetDate(); verify( () => storage.read( key: ArticleStorageKeys.articleViewsResetAt, ), ).called(1); expect(result, isNull); }); }); group('setTotalArticleViews', () { test('saves the value in Storage', () async { const views = 3; await ArticleStorage(storage: storage).setTotalArticleViews(views); verify( () => storage.write( key: ArticleStorageKeys.totalArticleViews, value: views.toString(), ), ).called(1); }); }); group('fetchTotalArticleViews', () { test('returns the value from Storage', () async { when( () => storage.read(key: ArticleStorageKeys.totalArticleViews), ).thenAnswer((_) async => '3'); final result = await ArticleStorage(storage: storage).fetchTotalArticleViews(); verify( () => storage.read( key: ArticleStorageKeys.totalArticleViews, ), ).called(1); expect(result, equals(3)); }); test('returns 0 when no value exists in Storage', () async { when( () => storage.read(key: ArticleStorageKeys.totalArticleViews), ).thenAnswer((_) async => null); final result = await ArticleStorage(storage: storage).fetchTotalArticleViews(); verify( () => storage.read( key: ArticleStorageKeys.totalArticleViews, ), ).called(1); expect(result, isZero); }); test('returns 0 when stored value is malformed', () async { when( () => storage.read(key: ArticleStorageKeys.totalArticleViews), ).thenAnswer((_) async => 'malformed'); final result = await ArticleStorage(storage: storage).fetchTotalArticleViews(); verify( () => storage.read( key: ArticleStorageKeys.totalArticleViews, ), ).called(1); expect(result, isZero); }); }); }); }
news_toolkit/flutter_news_example/packages/article_repository/test/src/article_storage_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/article_repository/test/src/article_storage_test.dart", "repo_id": "news_toolkit", "token_count": 2297 }
951
name: firebase_authentication_client description: A Firebase implementation of the authentication client interface version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: authentication_client: path: ../authentication_client firebase_auth: ^4.16.0 firebase_auth_platform_interface: ^7.0.9 firebase_core: ^2.24.2 firebase_core_platform_interface: ^5.0.0 flutter: sdk: flutter flutter_facebook_auth: ^6.0.0 google_sign_in: ^6.0.2 plugin_platform_interface: ^2.1.3 sign_in_with_apple: ^5.0.0 token_storage: path: ../token_storage twitter_login: ^4.2.2 dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 296 }
952
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/email_launcher/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/email_launcher/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
953
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/in_app_purchase_repository/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/in_app_purchase_repository/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
954
import 'package:news_blocks/news_blocks.dart'; /// Signature of callbacks invoked when [BlockAction] is triggered. typedef BlockActionCallback = void Function(BlockAction action);
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/block_action_callback.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/block_action_callback.dart", "repo_id": "news_toolkit", "token_count": 47 }
955
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template post_medium_description_layout} /// A reusable post medium news block widget showing post description. /// {@endtemplate} class PostMediumDescriptionLayout extends StatelessWidget { /// {@macro post_medium_description_layout} const PostMediumDescriptionLayout({ required this.title, required this.imageUrl, required this.publishedAt, this.description, this.author, this.onShare, super.key, }); /// Title of post. final String title; /// Description of post. final String? description; /// The date when this post was published. final DateTime publishedAt; /// The author of this post. final String? author; /// Called when the share button is tapped. final VoidCallback? onShare; /// The url of this post image. final String imageUrl; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Padding( padding: const EdgeInsets.all(AppSpacing.lg), child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( title, style: textTheme.titleLarge ?.copyWith(color: AppColors.highEmphasisSurface), ), ), const SizedBox(width: AppSpacing.md), Expanded( child: InlineImage(imageUrl: imageUrl), ), ], ), Text( description ?? '', style: textTheme.bodyMedium ?.copyWith(color: AppColors.mediumEmphasisSurface), ), const SizedBox(height: AppSpacing.sm), PostFooter( publishedAt: publishedAt, author: author, onShare: onShare, ), ], ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_description_layout.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_description_layout.dart", "repo_id": "news_toolkit", "token_count": 901 }
956
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; /// {@template banner_ad_container} /// A reusable banner ad container widget. /// {@endtemplate} class BannerAdContainer extends StatelessWidget { /// {@macro banner_ad_container} const BannerAdContainer({required this.size, required this.child, super.key}); /// The size of this banner ad. final BannerAdSize size; /// The [Widget] displayed in this container. final Widget child; @override Widget build(BuildContext context) { final horizontalPadding = size == BannerAdSize.normal ? AppSpacing.lg + AppSpacing.xs : AppSpacing.xlg + AppSpacing.xs + AppSpacing.xxs; final verticalPadding = size == BannerAdSize.normal ? AppSpacing.lg : AppSpacing.xlg + AppSpacing.sm; return ColoredBox( key: const Key('bannerAdContainer_coloredBox'), color: AppColors.brightGrey, child: Padding( padding: EdgeInsets.symmetric( horizontal: horizontalPadding, vertical: verticalPadding, ), child: child, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_container.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_container.dart", "repo_id": "news_toolkit", "token_count": 433 }
957
export 'fake_video_player_platform.dart'; export 'path_provider.dart'; export 'pump_app.dart'; export 'pump_content_themed_app.dart'; export 'tolerant_comparator.dart';
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/helpers.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/helpers.dart", "repo_id": "news_toolkit", "token_count": 65 }
958
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import '../helpers/pump_content_themed_app.dart'; void main() { const slideshowCategoryTitleKey = Key('slideshow_categoryTitle'); const slideshowHeaderKey = Key('slideshow_headerTitle'); const slideshowPageViewKey = Key('slideshow_pageView'); const slideshowItemImageKey = Key('slideshow_slideshowItemImage'); const slideshowItemCaptionKey = Key('slideshow_slideshowItemCaption'); const slideshowItemDescriptionKey = Key('slideshow_slideshowItemDescription'); const slideshowItemPhotoCreditKey = Key('slideshow_slideshowItemPhotoCredit'); const slideshowButtonsLeftKey = Key('slideshow_slideshowButtonsLeft'); const slideshowButtonsRightKey = Key('slideshow_slideshowButtonsRight'); group('Slideshow', () { const pageAnimationDuration = Duration(milliseconds: 300); final slides = List.generate( 3, (index) => SlideBlock( caption: 'Oink, Oink', description: 'Domestic pigs come in different colors, ' 'shapes and sizes. They are usually pink, but little pigs kept as' ' pets (pot-bellied pigs) are sometimes other colors. ' ' Pigs roll in mud to protect themselves from sunlight. ' ' Many people think that pigs are dirty and smell. In fact,' ' they roll around in the mud to keep bugs ' ' and ticks away from their skin. ' ' This also helps to keep their skin moist and lower their body' ' temperature on hot days. They are omnivores, ' ' which means that they eat both plants and animals.', photoCredit: 'Photo Credit: Pascal', imageUrl: 'https://media.4-paws.org/9/4/f/5/94f5197df88687ce362e32f23b926f0a246c1b54/VIER%20PFOTEN_2016-11-16_028%20%281%29-1843x1275.jpg', ), ); group('renders', () { testWidgets('slideshow category title', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs trough history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowCategoryTitleKey), findsOneWidget); }); testWidgets('slideshow header title', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowHeaderKey), findsOneWidget); }); testWidgets('slideshow page view', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowPageViewKey), findsOneWidget); }); testWidgets('slideshow item image', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowItemImageKey), findsOneWidget); }); testWidgets('slideshow item caption', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowItemCaptionKey), findsOneWidget); }); testWidgets('slideshow item description', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowItemDescriptionKey), findsOneWidget); }); testWidgets('slideshow item photo credit', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); expect(find.byKey(slideshowItemPhotoCreditKey), findsOneWidget); }); }); group('onPageChanged', () { testWidgets('when use previous button', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); final nextPageButton = find.byKey(slideshowButtonsRightKey); // Set page 2 await tester.tap(nextPageButton); await tester.pumpAndSettle(pageAnimationDuration); await tester.tap(nextPageButton); await tester.pumpAndSettle(pageAnimationDuration); final previousPageButton = find.byKey(slideshowButtonsLeftKey); final slideshowItem = find.byWidgetPredicate( (widget) => widget is SlideshowItem && widget.slide == slides[2], ); expect(slideshowItem, findsOneWidget); final currentPage = tester .widget<PageView>(find.byKey(slideshowPageViewKey)) .controller .page; // Check current page expect(currentPage, 2); await tester.tap(previousPageButton); await tester.pumpAndSettle(pageAnimationDuration); final slideshowItemPrevious = find.byWidgetPredicate( (widget) => widget is SlideshowItem && widget.slide == slides[1], ); expect(slideshowItemPrevious, findsOneWidget); }); testWidgets('when use next button', (tester) async { await mockNetworkImages( () async => tester.pumpContentThemedApp( Slideshow( block: SlideshowBlock( title: 'Pigs through history', slides: slides, ), categoryTitle: 'SLIDESHOW', navigationLabel: 'of', ), ), ); final nextPageButton = find.byKey(slideshowButtonsRightKey); // Set page 1 await tester.tap(nextPageButton); await tester.pumpAndSettle(pageAnimationDuration); final slideshowItem = find.byWidgetPredicate( (widget) => widget is SlideshowItem && widget.slide == slides[1], ); final currentPage = tester .widget<PageView>(find.byKey(slideshowPageViewKey)) .controller .page; // Check current page expect(currentPage, 1); expect(slideshowItem, findsOneWidget); await tester.tap(nextPageButton); await tester.pumpAndSettle(pageAnimationDuration); final slideshowItemNext = find.byWidgetPredicate( (widget) => widget is SlideshowItem && widget.slide == slides[2], ); expect(slideshowItemNext, findsOneWidget); }); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/slideshow_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/slideshow_test.dart", "repo_id": "news_toolkit", "token_count": 3863 }
959
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import '../helpers/helpers.dart'; void main() { group('TextCaption', () { setUpAll(setUpTolerantComparator); testWidgets( 'renders correctly ' 'with default normal color', (tester) async { final widget = Center( child: TextCaption( block: TextCaptionBlock( text: 'Text caption', color: TextCaptionColor.normal, ), ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextCaption), matchesGoldenFile('text_caption_normal_color_default.png'), ); }); testWidgets( 'renders correctly ' 'with default light color', (tester) async { final widget = Center( child: TextCaption( block: TextCaptionBlock( text: 'Text caption', color: TextCaptionColor.light, ), ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextCaption), matchesGoldenFile('text_caption_light_color_default.png'), ); }); testWidgets( 'renders correctly ' 'with provided normal color', (tester) async { final widget = Center( child: TextCaption( block: TextCaptionBlock( text: 'Text caption', color: TextCaptionColor.normal, ), colorValues: const { TextCaptionColor.normal: Colors.green, }, ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextCaption), matchesGoldenFile('text_caption_normal_color_provided.png'), ); }); testWidgets( 'renders correctly ' 'with provided light color', (tester) async { final widget = Center( child: TextCaption( block: TextCaptionBlock( text: 'Text caption', color: TextCaptionColor.light, ), colorValues: const { TextCaptionColor.light: Colors.green, }, ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextCaption), matchesGoldenFile('text_caption_light_color_provided.png'), ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_caption_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_caption_test.dart", "repo_id": "news_toolkit", "token_count": 1155 }
960
// ignore_for_file: prefer_const_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('LockIcon', () { testWidgets('renders correctly', (tester) async { await tester.pumpApp(LockIcon()); expect(find.byType(Icon), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/lock_icon_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/lock_icon_test.dart", "repo_id": "news_toolkit", "token_count": 163 }
961
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/news_repository/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_repository/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
962
/// {@template notification_exception} /// Exceptions from the notification client. /// {@endtemplate} abstract class NotificationException implements Exception { /// {@macro notification_exception} const NotificationException(this.error); /// The error which was caught. final Object error; } /// {@template subscribe_to_category_failure} /// Thrown during the subscription to category if a failure occurs. /// {@endtemplate} class SubscribeToCategoryFailure extends NotificationException { /// {@macro subscribe_to_category_failure} const SubscribeToCategoryFailure(super.error); } /// {@template unsubscribe_from_category_failure} /// Thrown during the subscription to category if a failure occurs. /// {@endtemplate} class UnsubscribeFromCategoryFailure extends NotificationException { /// {@macro unsubscribe_from_category_failure} const UnsubscribeFromCategoryFailure(super.error); } /// {@template notifications_client} /// A Generic Notifications Client Interface. /// {@endtemplate} abstract class NotificationsClient { /// Subscribes user to the notification group based on [category]. Future<void> subscribeToCategory(String category); /// Unsubscribes user from the notification group based on [category]. Future<void> unsubscribeFromCategory(String category); }
news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/lib/src/notifications_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/lib/src/notifications_client.dart", "repo_id": "news_toolkit", "token_count": 328 }
963
name: notifications_repository description: A repository that manages notification permissions and topic subscriptions. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: equatable: ^2.0.3 flutter: sdk: flutter flutter_news_example_api: path: ../../api notifications_client: path: ../notifications_client/notifications_client permission_client: path: ../permission_client storage: path: ../storage/storage test: ^1.21.4 dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/notifications_repository/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 227 }
964
// ignore_for_file: prefer_const_constructors import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:permission_client/permission_client.dart'; import 'package:permission_handler/permission_handler.dart'; void main() { final binding = TestWidgetsFlutterBinding.ensureInitialized(); group('PermissionClient', () { late PermissionClient permissionClient; late List<MethodCall> calls; const methodChannelName = 'flutter.baseflow.com/permissions/methods'; setUp(() { permissionClient = PermissionClient(); calls = []; binding.defaultBinaryMessenger.setMockMethodCallHandler( MethodChannel(methodChannelName), (call) async { calls.add(call); if (call.method == 'checkPermissionStatus') { return PermissionStatus.granted.index; } else if (call.method == 'requestPermissions') { return <dynamic, dynamic>{ for (final key in call.arguments as List<dynamic>) key: PermissionStatus.granted.index, }; } else if (call.method == 'openAppSettings') { return true; } return null; }, ); }); tearDown(() { binding.defaultBinaryMessenger.setMockMethodCallHandler( MethodChannel(methodChannelName), (call) async => null, ); }); Matcher permissionWasRequested(Permission permission) => contains( isA<MethodCall>() .having( (c) => c.method, 'method', 'requestPermissions', ) .having( (c) => c.arguments, 'arguments', contains(permission.value), ), ); Matcher permissionWasChecked(Permission permission) => contains( isA<MethodCall>() .having( (c) => c.method, 'method', 'checkPermissionStatus', ) .having( (c) => c.arguments, 'arguments', equals(permission.value), ), ); group('requestNotifications', () { test('calls correct method', () async { await permissionClient.requestNotifications(); expect(calls, permissionWasRequested(Permission.notification)); }); }); group('notificationsStatus', () { test('calls correct method', () async { await permissionClient.notificationsStatus(); expect(calls, permissionWasChecked(Permission.notification)); }); }); group('openPermissionSettings', () { test('calls correct method', () async { await permissionClient.openPermissionSettings(); expect( calls, contains( isA<MethodCall>().having( (c) => c.method, 'method', 'openAppSettings', ), ), ); }); }); }); }
news_toolkit/flutter_news_example/packages/permission_client/test/src/permission_client_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/permission_client/test/src/permission_client_test.dart", "repo_id": "news_toolkit", "token_count": 1423 }
965
# persistent_storage Storage that saves data in the device's persistent memory.
news_toolkit/flutter_news_example/packages/storage/persistent_storage/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/README.md", "repo_id": "news_toolkit", "token_count": 18 }
966
/// {@template storage_exception} /// Exception thrown if a storage operation fails. /// {@endtemplate} class StorageException implements Exception { /// {@macro storage_exception} const StorageException(this.error); /// Error thrown during the storage operation. final Object error; } /// A Dart Storage Client Interface abstract class Storage { /// Returns value for the provided [key]. /// Read returns `null` if no value is found for the given [key]. /// * Throws a [StorageException] if the read fails. Future<String?> read({required String key}); /// Writes the provided [key], [value] pair asynchronously. /// * Throws a [StorageException] if the write fails. Future<void> write({required String key, required String value}); /// Removes the value for the provided [key] asynchronously. /// * Throws a [StorageException] if the delete fails. Future<void> delete({required String key}); /// Removes all key, value pairs asynchronously. /// * Throws a [StorageException] if the delete fails. Future<void> clear(); }
news_toolkit/flutter_news_example/packages/storage/storage/lib/storage.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/storage/lib/storage.dart", "repo_id": "news_toolkit", "token_count": 282 }
967
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:fake_async/fake_async.dart'; import 'package:flutter_news_example/ads/ads.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart' as ads; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:platform/platform.dart'; class MockInterstitialAd extends Mock implements ads.InterstitialAd {} class FakeInterstitialAd extends Fake implements ads.InterstitialAd { ads.FullScreenContentCallback<ads.InterstitialAd>? contentCallback; bool disposeCalled = false; @override Future<void> show() async {} @override Future<void> dispose() async => disposeCalled = true; @override set fullScreenContentCallback( ads.FullScreenContentCallback<ads.InterstitialAd>? fullScreenContentCallback, ) { contentCallback = fullScreenContentCallback; } @override ads.FullScreenContentCallback<ads.InterstitialAd>? get fullScreenContentCallback => contentCallback; } class MockRewardedAd extends Mock implements ads.RewardedAd {} class FakeRewardedAd extends Fake implements ads.RewardedAd { ads.FullScreenContentCallback<ads.RewardedAd>? contentCallback; bool disposeCalled = false; @override Future<void> show({ required ads.OnUserEarnedRewardCallback onUserEarnedReward, }) async {} @override Future<void> dispose() async => disposeCalled = true; @override set fullScreenContentCallback( ads.FullScreenContentCallback<ads.RewardedAd>? fullScreenContentCallback, ) { contentCallback = fullScreenContentCallback; } @override ads.FullScreenContentCallback<ads.RewardedAd>? get fullScreenContentCallback => contentCallback; } class MockRewardItem extends Mock implements ads.RewardItem {} class MockLoadAdError extends Mock implements ads.LoadAdError {} class MockLocalPlatform extends Mock implements LocalPlatform {} void main() { group('FullScreenAdsBloc', () { String? capturedAdUnitId; late LocalPlatform localPlatform; late ads.InterstitialAd interstitialAd; late InterstitialAdLoader interstitialAdLoader; late ads.RewardedAd rewardedAd; late RewardedAdLoader rewardedAdLoader; setUp(() { localPlatform = MockLocalPlatform(); when(() => localPlatform.isAndroid).thenReturn(true); when(() => localPlatform.isIOS).thenReturn(false); interstitialAd = MockInterstitialAd(); when(interstitialAd.show).thenAnswer((_) async {}); when(interstitialAd.dispose).thenAnswer((_) async {}); interstitialAdLoader = ({ required String adUnitId, required ads.InterstitialAdLoadCallback adLoadCallback, required ads.AdRequest request, }) async { capturedAdUnitId = adUnitId; }; rewardedAd = MockRewardedAd(); when( () => rewardedAd.show( onUserEarnedReward: any(named: 'onUserEarnedReward'), ), ).thenAnswer((_) async {}); when(rewardedAd.dispose).thenAnswer((_) async {}); rewardedAdLoader = ({ required String adUnitId, required ads.RewardedAdLoadCallback rewardedAdLoadCallback, required ads.AdRequest request, }) async { capturedAdUnitId = adUnitId; }; }); group('LoadInterstitialAdRequested', () { blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly on Android', build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadInterstitialAdRequested()), verify: (bloc) { expect( capturedAdUnitId, equals(FullScreenAdsConfig.androidTestInterstitialAdUnitId), ); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly on iOS', setUp: () { when(() => localPlatform.isIOS).thenReturn(true); when(() => localPlatform.isAndroid).thenReturn(false); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadInterstitialAdRequested()), verify: (bloc) { expect( capturedAdUnitId, equals(FullScreenAdsConfig.iosTestInterstitialAdUnitId), ); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly using provided FullScreenAdsConfig', setUp: () { when(() => localPlatform.isIOS).thenReturn(true); when(() => localPlatform.isAndroid).thenReturn(false); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, fullScreenAdsConfig: FullScreenAdsConfig(interstitialAdUnitId: 'interstitialAdUnitId'), ), act: (bloc) => bloc.add(LoadInterstitialAdRequested()), verify: (bloc) { expect(capturedAdUnitId, equals('interstitialAdUnitId')); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'emits ad when ad is loaded', setUp: () { interstitialAdLoader = ({ required String adUnitId, required ads.InterstitialAdLoadCallback adLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => adLoadCallback.onAdLoaded(interstitialAd), ); }; }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadInterstitialAdRequested()), expect: () => [ FullScreenAdsState(status: FullScreenAdsStatus.loadingInterstitialAd), FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, interstitialAd: interstitialAd, ), ], ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'adds error when ad fails to load', setUp: () { interstitialAdLoader = ({ required String adUnitId, required ads.InterstitialAdLoadCallback adLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => adLoadCallback.onAdFailedToLoad( ads.LoadAdError(0, 'domain', 'message', null), ), ); }; }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadInterstitialAdRequested()), expect: () => [ FullScreenAdsState(status: FullScreenAdsStatus.loadingInterstitialAd), FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdFailed, ), ], errors: () => [isA<ads.LoadAdError>()], ); test('retries loading ad based on AdsRetryPolicy', () async { final fakeAsync = FakeAsync(); unawaited( fakeAsync.run((async) async { final adsRetryPolicy = AdsRetryPolicy(); interstitialAdLoader = ({ required String adUnitId, required ads.InterstitialAdLoadCallback adLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => adLoadCallback.onAdFailedToLoad( ads.LoadAdError(0, 'domain', 'message', null), ), ); }; final bloc = FullScreenAdsBloc( adsRetryPolicy: adsRetryPolicy, localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, )..add(LoadInterstitialAdRequested()); expect( (await bloc.stream.first).status, equals(FullScreenAdsStatus.loadingInterstitialAd), ); expect( (await bloc.stream.first).status, equals(FullScreenAdsStatus.loadingInterstitialAdFailed), ); for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++) { expect( bloc.stream, emitsInOrder( <FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAd, ), FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdFailed, ), ], ), ); async.elapse(adsRetryPolicy.getIntervalForRetry(i)); } }), ); fakeAsync.flushMicrotasks(); }); }); group('ShowInterstitialAdRequested', () { final ad = FakeInterstitialAd(); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'shows ad and loads next ad', seed: () => FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, interstitialAd: interstitialAd, ), build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(ShowInterstitialAdRequested()), expect: () => [ FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAd, interstitialAd: interstitialAd, ), FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAdSucceeded, interstitialAd: interstitialAd, ), FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAd, interstitialAd: interstitialAd, ), ], verify: (bloc) { verify(interstitialAd.show).called(1); }, ); test('disposes ad on ad dismissed', () async { final bloc = FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ) ..emit( FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, interstitialAd: ad, ), ) ..add(ShowInterstitialAdRequested()); await expectLater( bloc.stream, emitsInOrder(<FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAd, interstitialAd: ad, ), FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAdSucceeded, interstitialAd: ad, ), ]), ); ad.fullScreenContentCallback!.onAdDismissedFullScreenContent!(ad); expect(ad.disposeCalled, isTrue); }); test('disposes ad when ads fails to show', () async { final bloc = FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ) ..emit( FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, interstitialAd: ad, ), ) ..add(ShowInterstitialAdRequested()); await expectLater( bloc.stream, emitsInOrder(<FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAd, interstitialAd: ad, ), FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAdSucceeded, interstitialAd: ad, ), ]), ); final error = MockLoadAdError(); ad.fullScreenContentCallback!.onAdFailedToShowFullScreenContent!( ad, error, ); expect(ad.disposeCalled, isTrue); }); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'adds error when ad fails to show', seed: () => FullScreenAdsState( status: FullScreenAdsStatus.loadingInterstitialAdSucceeded, interstitialAd: interstitialAd, ), setUp: () { when(interstitialAd.show).thenThrow(Exception('Oops')); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(ShowInterstitialAdRequested()), expect: () => [ FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAd, interstitialAd: interstitialAd, ), FullScreenAdsState( status: FullScreenAdsStatus.showingInterstitialAdFailed, interstitialAd: interstitialAd, ), ], errors: () => [isA<Exception>()], ); }); group('LoadRewardedAdRequested', () { blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly on Android', build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadRewardedAdRequested()), verify: (bloc) { expect( capturedAdUnitId, equals(FullScreenAdsConfig.androidTestRewardedAdUnitId), ); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly on iOS', setUp: () { when(() => localPlatform.isIOS).thenReturn(true); when(() => localPlatform.isAndroid).thenReturn(false); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadRewardedAdRequested()), verify: (bloc) { expect( capturedAdUnitId, equals(FullScreenAdsConfig.iosTestRewardedAdUnitId), ); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'loads ad object correctly using provided FullScreenAdsConfig', setUp: () { when(() => localPlatform.isIOS).thenReturn(true); when(() => localPlatform.isAndroid).thenReturn(false); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, fullScreenAdsConfig: FullScreenAdsConfig(rewardedAdUnitId: 'rewardedAdUnitId'), ), act: (bloc) => bloc.add(LoadRewardedAdRequested()), verify: (bloc) { expect(capturedAdUnitId, equals('rewardedAdUnitId')); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'emits ad when ad is loaded', setUp: () { rewardedAdLoader = ({ required String adUnitId, required ads.RewardedAdLoadCallback rewardedAdLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => rewardedAdLoadCallback.onAdLoaded(rewardedAd), ); }; }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadRewardedAdRequested()), expect: () => [ FullScreenAdsState(status: FullScreenAdsStatus.loadingRewardedAd), FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: rewardedAd, ), ], ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'adds error when ad fails to load', setUp: () { rewardedAdLoader = ({ required String adUnitId, required ads.RewardedAdLoadCallback rewardedAdLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => rewardedAdLoadCallback.onAdFailedToLoad( ads.LoadAdError(0, 'domain', 'message', null), ), ); }; }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(LoadRewardedAdRequested()), expect: () => [ FullScreenAdsState(status: FullScreenAdsStatus.loadingRewardedAd), FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdFailed, ), ], errors: () => [isA<ads.LoadAdError>()], ); test('retries loading ad based on AdsRetryPolicy', () async { final fakeAsync = FakeAsync(); unawaited( fakeAsync.run((async) async { final adsRetryPolicy = AdsRetryPolicy(); rewardedAdLoader = ({ required String adUnitId, required ads.RewardedAdLoadCallback rewardedAdLoadCallback, required ads.AdRequest request, }) async { await Future.microtask( () => rewardedAdLoadCallback.onAdFailedToLoad( ads.LoadAdError(0, 'domain', 'message', null), ), ); }; final bloc = FullScreenAdsBloc( adsRetryPolicy: adsRetryPolicy, localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, )..add(LoadRewardedAdRequested()); expect( (await bloc.stream.first).status, equals(FullScreenAdsStatus.loadingRewardedAd), ); expect( (await bloc.stream.first).status, equals(FullScreenAdsStatus.loadingRewardedAdFailed), ); for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++) { expect( bloc.stream, emitsInOrder( <FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAd, ), FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdFailed, ), ], ), ); async.elapse(adsRetryPolicy.getIntervalForRetry(i)); } }), ); fakeAsync.flushMicrotasks(); }); }); group('ShowRewardedAdRequested', () { final ad = FakeRewardedAd(); final rewardItem = MockRewardItem(); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'shows ad and loads next ad', seed: () => FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: rewardedAd, ), build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(ShowRewardedAdRequested()), expect: () => [ FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAd, rewardedAd: rewardedAd, ), FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAdSucceeded, rewardedAd: rewardedAd, ), FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAd, rewardedAd: rewardedAd, ), ], verify: (bloc) { verify( () => rewardedAd.show( onUserEarnedReward: any(named: 'onUserEarnedReward'), ), ).called(1); }, ); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'emits earned reward when ad is watched', seed: () => FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: rewardedAd, ), setUp: () { when( () => rewardedAd.show( onUserEarnedReward: any(named: 'onUserEarnedReward'), ), ).thenAnswer((invocation) async { (invocation.namedArguments[Symbol('onUserEarnedReward')] as ads.OnUserEarnedRewardCallback) .call(ad, rewardItem); }); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(ShowRewardedAdRequested()), // Skip showingRewardedAd, showingRewardedAdSucceeded // and loadingRewardedAd. skip: 3, expect: () => [ FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAd, rewardedAd: rewardedAd, earnedReward: rewardItem, ), ], ); test('disposes ad on ad dismissed', () async { final bloc = FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ) ..emit( FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: ad, ), ) ..add(ShowRewardedAdRequested()); await expectLater( bloc.stream, emitsInOrder(<FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAd, rewardedAd: ad, ), FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAdSucceeded, rewardedAd: ad, ), ]), ); ad.fullScreenContentCallback!.onAdDismissedFullScreenContent!(ad); expect(ad.disposeCalled, isTrue); }); test('disposes ad when ads fails to show', () async { final bloc = FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ) ..emit( FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: ad, ), ) ..add(ShowRewardedAdRequested()); await expectLater( bloc.stream, emitsInOrder(<FullScreenAdsState>[ FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAd, rewardedAd: ad, ), FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAdSucceeded, rewardedAd: ad, ), ]), ); final error = MockLoadAdError(); ad.fullScreenContentCallback!.onAdFailedToShowFullScreenContent!( ad, error, ); expect(ad.disposeCalled, isTrue); }); blocTest<FullScreenAdsBloc, FullScreenAdsState>( 'adds error when ad fails to show', seed: () => FullScreenAdsState( status: FullScreenAdsStatus.loadingRewardedAdSucceeded, rewardedAd: rewardedAd, ), setUp: () { when( () => rewardedAd.show( onUserEarnedReward: any(named: 'onUserEarnedReward'), ), ).thenThrow(Exception('Oops')); }, build: () => FullScreenAdsBloc( adsRetryPolicy: AdsRetryPolicy(), localPlatform: localPlatform, interstitialAdLoader: interstitialAdLoader, rewardedAdLoader: rewardedAdLoader, ), act: (bloc) => bloc.add(ShowRewardedAdRequested()), expect: () => [ FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAd, rewardedAd: rewardedAd, ), FullScreenAdsState( status: FullScreenAdsStatus.showingRewardedAdFailed, rewardedAd: rewardedAd, ), ], errors: () => [isA<Exception>()], ); }); }); }
news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 12241 }
968
export 'fake_video_player_platform.dart';
news_toolkit/flutter_news_example/test/article/helpers/helpers.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/helpers/helpers.dart", "repo_id": "news_toolkit", "token_count": 14 }
969
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' hide Spacer; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_news_example/feed/feed.dart'; 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 '../../helpers/helpers.dart'; class MockFeedBloc extends MockBloc<FeedEvent, FeedState> implements FeedBloc {} class MockCategoriesBloc extends MockBloc<CategoriesEvent, CategoriesState> implements CategoriesBloc {} void main() { group('FeedView', () { late CategoriesBloc categoriesBloc; late FeedBloc feedBloc; const categories = [Category.top, Category.technology]; final feed = <Category, List<NewsBlock>>{ Category.top: [ SectionHeaderBlock(title: 'Top'), SpacerBlock(spacing: Spacing.medium), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), SpacerBlock(spacing: Spacing.extraLarge), DividerHorizontalBlock(), ], Category.technology: [ SectionHeaderBlock(title: 'Technology'), DividerHorizontalBlock(), SpacerBlock(spacing: Spacing.medium), ], }; setUp(() { categoriesBloc = MockCategoriesBloc(); feedBloc = MockFeedBloc(); when(() => categoriesBloc.state).thenReturn( CategoriesState( categories: categories, status: CategoriesStatus.populated, ), ); when(() => feedBloc.state).thenReturn( FeedState( feed: feed, status: FeedStatus.populated, ), ); }); testWidgets( 'renders empty feed ' 'when categories are empty', (tester) async { when(() => categoriesBloc.state).thenReturn( CategoriesState( categories: const [], status: CategoriesStatus.populated, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedView(), ), ); expect(find.byKey(Key('feedView_empty')), findsOneWidget); expect(find.byType(FeedViewPopulated), findsNothing); }); testWidgets( 'renders FeedViewPopulated ' 'when categories are available', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedView(), ), ); expect( find.byWidgetPredicate( (widget) => widget is FeedViewPopulated && widget.categories == categories, ), findsOneWidget, ); expect(find.byKey(Key('feedView_empty')), findsNothing); }); testWidgets( 'adds FeedResumed when the app is resumed', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedView(), ), ); tester.binding.handleAppLifecycleStateChanged( AppLifecycleState.resumed, ); verify( () => feedBloc.add(FeedResumed()), ).called(1); }, ); group('FeedViewPopulated', () { testWidgets('renders CategoryTabBar with CategoryTab for each category', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedViewPopulated(categories: categories), ), ); expect(find.byType(CategoriesTabBar), findsOneWidget); for (final category in categories) { expect( find.descendant( of: find.byType(CategoriesTabBar), matching: find.byWidgetPredicate( (widget) => widget is CategoryTab && widget.categoryName == category.name, ), ), findsOneWidget, ); } }); testWidgets('renders TabBarView', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedViewPopulated(categories: categories), ), ); expect(find.byType(TabBarView), findsOneWidget); expect(find.byType(CategoryFeed), findsOneWidget); }); testWidgets( 'adds CategorySelected to CategoriesBloc ' 'when CategoryTab is tapped', (tester) async { final selectedCategory = categories[1]; await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedViewPopulated(categories: categories), ), ); final categoryTab = find.byWidgetPredicate( (widget) => widget is CategoryTab && widget.categoryName == selectedCategory.name, ); await tester.ensureVisible(categoryTab); await tester.tap(categoryTab); await tester.pump(kTabScrollDuration); verify( () => categoriesBloc.add( CategorySelected(category: selectedCategory), ), ).called(1); }); testWidgets( 'animates to CategoryFeed in TabBarView ' 'when selectedCategory changes', (tester) async { final categoriesStateController = StreamController<CategoriesState>.broadcast(); final categoriesState = CategoriesState( categories: categories, status: CategoriesStatus.populated, ); whenListen( categoriesBloc, categoriesStateController.stream, initialState: categoriesState, ); final defaultCategory = categories.first; final selectedCategory = categories[1]; await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedViewPopulated(categories: categories), ), ); Finder findCategoryFeed(Category category) => find.byWidgetPredicate( (widget) => widget is CategoryFeed && widget.category == category, ); expect(findCategoryFeed(defaultCategory), findsOneWidget); expect(findCategoryFeed(selectedCategory), findsNothing); categoriesStateController.add( categoriesState.copyWith(selectedCategory: selectedCategory), ); await tester.pump(kTabScrollDuration); await tester.pump(kTabScrollDuration); expect(findCategoryFeed(defaultCategory), findsNothing); expect(findCategoryFeed(selectedCategory), findsOneWidget); }); testWidgets( 'scrolls to the top of CategoryFeed on double tap on CategoryTab', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: categoriesBloc), BlocProvider.value(value: feedBloc), ], child: FeedViewPopulated(categories: categories), ), ); expect( find.byType(DividerHorizontal), findsNothing, ); expect( find.text('Top'), findsOneWidget, ); await tester.dragUntilVisible( find.byType(DividerHorizontal), find.byType(FeedViewPopulated), Offset(0, -100), duration: Duration.zero, ); expect( find.byType(DividerHorizontal), findsOneWidget, ); final tab = find.widgetWithText( CategoryTab, categories.first.name.toUpperCase(), ); await tester.tap(tab); await tester.pump(kDoubleTapMinTime); await tester.tap(tab); await tester.pump(Duration(milliseconds: 300)); await tester.pump(Duration(milliseconds: 300)); expect( find.byType(DividerHorizontal), findsNothing, ); expect( find.text('Top'), findsOneWidget, ); }, ); }); }); }
news_toolkit/flutter_news_example/test/feed/view/feed_view_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/feed/view/feed_view_test.dart", "repo_id": "news_toolkit", "token_count": 4430 }
970