text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; part 'match_state.g.dart'; const _maxTurns = 3; /// Enum listing the possible outcomes of a match. enum MatchResult { /// Host won. host, /// Guest won. guest, /// Draw. draw; /// Tries to match the string with an entry of the enum. /// /// Returns null if no match is found. static MatchResult? valueOf(String? value) { if (value != null) { for (final enumValue in MatchResult.values) { if (enumValue.name == value) { return enumValue; } } } return null; } } /// {@template match_state} /// A model that represents the state of a match. /// {@endtemplate} @JsonSerializable(ignoreUnannotated: true, explicitToJson: true) class MatchState extends Equatable { /// {@template match_state} const MatchState({ required this.id, required this.matchId, required this.hostPlayedCards, required this.guestPlayedCards, this.result, }); /// {@template match_state} factory MatchState.fromJson(Map<String, dynamic> json) => _$MatchStateFromJson(json); /// Match State id; @JsonKey() final String id; /// Id of the match that this state is tied to. @JsonKey() final String matchId; /// List of cards played by the host @JsonKey() final List<String> hostPlayedCards; /// List of cards played by the guest. @JsonKey() final List<String> guestPlayedCards; /// Result of the match. @JsonKey() final MatchResult? result; /// Returns if the match is over. bool isOver() { return hostPlayedCards.length == _maxTurns && guestPlayedCards.length == _maxTurns; } /// Copy this instance, adding the given [cardId] to the [hostPlayedCards]. MatchState addHostPlayedCard(String cardId) { return MatchState( id: id, matchId: matchId, guestPlayedCards: guestPlayedCards, hostPlayedCards: [...hostPlayedCards, cardId], result: result, ); } /// Copy this instance, adding the given [cardId] to the [guestPlayedCards]. MatchState addGuestPlayedCard(String cardId) { return MatchState( id: id, matchId: matchId, guestPlayedCards: [...guestPlayedCards, cardId], hostPlayedCards: hostPlayedCards, result: result, ); } /// Copy this instance, setting the given [result]. MatchState setResult(MatchResult result) { return MatchState( id: id, matchId: matchId, guestPlayedCards: guestPlayedCards, hostPlayedCards: hostPlayedCards, result: result, ); } /// Returns a json representation from this instance. Map<String, dynamic> toJson() => _$MatchStateToJson(this); @override List<Object?> get props => [ id, matchId, hostPlayedCards, guestPlayedCards, result, ]; }
io_flip/api/packages/game_domain/lib/src/models/match_state.dart/0
{ "file_path": "io_flip/api/packages/game_domain/lib/src/models/match_state.dart", "repo_id": "io_flip", "token_count": 1090 }
850
// ignore_for_file: prefer_const_constructors import 'package:game_domain/game_domain.dart'; import 'package:test/test.dart'; void main() { group('Deck', () { const card1 = Card( id: 'card1', name: '', description: '', image: '', rarity: false, power: 1, suit: Suit.air, ); const card2 = Card( id: 'card2', name: '', description: '', image: '', rarity: false, power: 1, suit: Suit.fire, ); test('can be instantiated', () { expect( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ), isNotNull, ); }); test('toJson returns the instance as json', () { expect( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ).toJson(), equals({ 'id': 'deckId', 'userId': 'userId', 'cards': [ { 'id': 'card1', 'name': '', 'description': '', 'image': '', 'rarity': false, 'power': 1, 'suit': 'air', 'shareImage': null, }, { 'id': 'card2', 'name': '', 'description': '', 'image': '', 'rarity': false, 'power': 1, 'suit': 'fire', 'shareImage': null, }, ], 'shareImage': null, }), ); }); test('fromJson returns the correct instance', () { expect( Deck.fromJson(const { 'id': 'deckId', 'userId': 'userId', 'cards': [ { 'id': 'card1', 'name': '', 'description': '', 'image': '', 'rarity': false, 'power': 1, 'suit': 'air', }, { 'id': 'card2', 'name': '', 'description': '', 'image': '', 'rarity': false, 'power': 1, 'suit': 'fire', }, ], }), equals( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ), ), ); }); test('supports equality', () { expect( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ), equals( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ), ), ); expect( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ), isNot( equals( Deck( id: 'deckId2', userId: 'userId', cards: const [card2, card1], ), ), ), ); }); test( 'copyWithShareImage returns a new instance with the new value', () { expect( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], ).copyWithShareImage('shareImage'), equals( Deck( id: 'deckId', userId: 'userId', cards: const [card1, card2], shareImage: 'shareImage', ), ), ); }, ); }); }
io_flip/api/packages/game_domain/test/src/models/deck_test.dart/0
{ "file_path": "io_flip/api/packages/game_domain/test/src/models/deck_test.dart", "repo_id": "io_flip", "token_count": 2201 }
851
name: game_script_machine description: Holds and proccess the scripts responsible for calculating the result of a game match version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: game_domain: path: ../game_domain hetu_script: ^0.4.2+1 dev_dependencies: mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^4.0.0
io_flip/api/packages/game_script_machine/pubspec.yaml/0
{ "file_path": "io_flip/api/packages/game_script_machine/pubspec.yaml", "repo_id": "io_flip", "token_count": 147 }
852
import 'dart:convert' show base64Url, json, utf8; import 'dart:typed_data'; import 'package:clock/clock.dart'; import 'package:x509/x509.dart'; Uint8List _base64Decode(String encoded) { final String padding; if (encoded.length % 4 != 0) { padding = '=' * (4 - encoded.length % 4); } else { padding = ''; } return base64Url.decode(encoded + padding); } Map<String, dynamic> _jsonBase64Decode(String encoded) { return Map<String, dynamic>.from( json.decode(utf8.decode(_base64Decode(encoded))) as Map, ); } /// {@template jwt} /// Represents a JSON Web Token. /// {@endtemplate} class JWT { /// {@macro jwt} JWT({ required Uint8List body, required Signature? signature, required Map<String, dynamic> payload, required Map<String, dynamic> header, }) : _body = body, _signature = signature, _payload = payload, _header = header; /// Parses a [JWT] from an encoded token string. factory JWT.from(String token) { final segments = token.split('.'); final header = _jsonBase64Decode(segments[0]); final body = utf8.encode('${segments[0]}.${segments[1]}'); final signature = segments[2].isNotEmpty ? Signature(_base64Decode(segments[2])) : null; return JWT( body: Uint8List.fromList(body), signature: signature, payload: _jsonBase64Decode(segments[1]), header: header, ); } final Uint8List _body; final Signature? _signature; final Map<String, dynamic> _payload; final Map<String, dynamic> _header; /// The user id stored in this token. String? get userId => _payload['user_id'] as String?; /// The key id of the key used to sign this token. String? get keyId => _header['kid'] as String?; /// Verifies the signature of this token with the given [verifier]. bool verifyWith(Verifier<PublicKey> verifier) { if (_signature == null) return false; return verifier.verify(_body, _signature!); } /// Validates the fields of this token. bool validate(String projectId) { if (_header['alg'] != 'RS256') { return false; } final nowSeconds = clock.now().millisecondsSinceEpoch ~/ 1000; final exp = _payload['exp'] as int?; final iat = _payload['iat'] as int?; final aud = _payload['aud'] as String?; final iss = _payload['iss'] as String?; final sub = _payload['sub'] as String?; final authTime = _payload['auth_time'] as int?; final userId = _payload['user_id'] as String?; if (exp == null || iat == null || aud == null || iss == null || sub == null || authTime == null || userId == null) return false; if (exp <= nowSeconds) { return false; } if (iat > nowSeconds) { return false; } if (aud != projectId) { return false; } if (iss != 'https://securetoken.google.com/$projectId') { return false; } if (authTime > nowSeconds) { return false; } if (sub != userId) { return false; } return true; } }
io_flip/api/packages/jwt_middleware/lib/src/jwt.dart/0
{ "file_path": "io_flip/api/packages/jwt_middleware/lib/src/jwt.dart", "repo_id": "io_flip", "token_count": 1193 }
853
/// Access to Prompt datasource. library prompt_repository; export 'src/prompt_repository.dart';
io_flip/api/packages/prompt_repository/lib/prompt_repository.dart/0
{ "file_path": "io_flip/api/packages/prompt_repository/lib/prompt_repository.dart", "repo_id": "io_flip", "token_count": 32 }
854
name: api description: I/O FLIP Game APIs version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: card_renderer: path: packages/card_renderer cards_repository: path: packages/cards_repository collection: ^1.17.1 config_repository: path: packages/config_repository dart_frog: ^0.3.0 dart_frog_web_socket: ^0.1.0-dev.3 db_client: path: packages/db_client encryption_middleware: path: packages/encryption_middleware firebase_cloud_storage: path: packages/firebase_cloud_storage game_domain: path: packages/game_domain game_script_machine: path: packages/game_script_machine gcp: ^0.1.0 image_model_repository: path: packages/image_model_repository json_annotation: ^4.8.0 jwt_middleware: path: packages/jwt_middleware language_model_repository: path: packages/language_model_repository leaderboard_repository: path: packages/leaderboard_repository logging: ^1.1.1 match_repository: path: packages/match_repository mustache_template: ^2.0.0 prompt_repository: path: packages/prompt_repository scripts_repository: path: packages/scripts_repository shelf_cors_headers: ^0.1.4 shelf_web_socket: ^1.0.3 dev_dependencies: build_runner: ^2.3.3 json_serializable: ^6.6.1 mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^4.0.0 web_socket_client: ^0.1.0-dev.1
io_flip/api/pubspec.yaml/0
{ "file_path": "io_flip/api/pubspec.yaml", "repo_id": "io_flip", "token_count": 579 }
855
import 'package:api/game_url.dart'; import 'package:card_renderer/card_renderer.dart'; import 'package:cards_repository/cards_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:dart_frog_web_socket/dart_frog_web_socket.dart' as ws; import 'package:firebase_cloud_storage/firebase_cloud_storage.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:gcp/gcp.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:logging/logging.dart'; import 'package:match_repository/match_repository.dart'; import 'package:prompt_repository/prompt_repository.dart'; import 'package:scripts_repository/scripts_repository.dart'; import '../../headers/headers.dart'; import '../../main.dart'; import 'connect.dart'; Handler middleware(Handler handler) { return handler .use(requestLogger()) .use(provider<Logger>((_) => Logger.root)) .use(fromShelfMiddleware(cloudLoggingMiddleware(projectId))) .use(provider<CardsRepository>((_) => cardsRepository)) .use(provider<MatchRepository>((_) => matchRepository)) .use(provider<PromptRepository>((_) => promptRepository)) .use(provider<ScriptsRepository>((_) => scriptsRepository)) .use(provider<LeaderboardRepository>((_) => leaderboardRepository)) .use(provider<GameScriptMachine>((_) => gameScriptMachine)) .use(provider<GameUrl>((_) => gameUrl)) .use(provider<CardRenderer>((_) => CardRenderer())) .use(provider<FirebaseCloudStorage>((_) => firebaseCloudStorage)) .use(provider<WebSocketHandlerFactory>((_) => ws.webSocketHandler)) .use(corsHeaders()) .use(allowHeaders()); }
io_flip/api/routes/public/_middleware.dart/0
{ "file_path": "io_flip/api/routes/public/_middleware.dart", "repo_id": "io_flip", "token_count": 641 }
856
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]/state.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]/state', () { late MatchRepository matchRepository; late Request request; late RequestContext context; late Logger logger; const matchState = MatchState( id: 'matchStateId', matchId: 'matchId', guestPlayedCards: [], hostPlayedCards: [], ); setUp(() { matchRepository = _MockMatchRepository(); when(() => matchRepository.getMatchState(any())).thenAnswer( (_) async => matchState, ); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.get); when(request.json).thenAnswer( (_) async => matchState.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, matchState.matchId); expect(response.statusCode, equals(HttpStatus.ok)); }); test('responds with the match state', () async { final response = await route.onRequest(context, matchState.matchId); final json = await response.json() as Map<String, dynamic>; expect( json, equals(matchState.toJson()), ); }); test("responds 404 when the match doesn't exists", () async { when(() => matchRepository.getMatchState(any())).thenAnswer( (_) async => null, ); final response = await route.onRequest(context, matchState.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, matchState.id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); }
io_flip/api/test/routes/game/matches/[matchId]/state_test.dart/0
{ "file_path": "io_flip/api/test/routes/game/matches/[matchId]/state_test.dart", "repo_id": "io_flip", "token_count": 953 }
857
// 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'; import 'package:path/path.dart' as path; /// {@template character_folder_validator} /// Dart tool that checks if the character folder is valid /// given the prompts stored in csv file. /// {@endtemplate} class CreateImageLookup { /// {@macro character_folder_validator} const CreateImageLookup({ required DbClient dbClient, required File csv, required Directory imagesFolder, required String character, required int variations, }) : _dbClient = dbClient, _csv = csv, _imagesFolder = imagesFolder, _character = character, _variations = variations; final DbClient _dbClient; final File _csv; final Directory _imagesFolder; final String _character; final int _variations; /// Uses the prompts stored in the csv file to generate /// a lookup table in case there are missing images for a given prompt /// combination. /// [onProgress] is called everytime there is progress, /// it takes in the current inserted and the total to insert. Future<void> generateLookupTable( void Function(int, int) onProgress, ) async { final lines = await _csv.readAsLines(); final map = mapCsvToPrompts(lines); final tables = <String, List<String>>{}; final classes = map[PromptTermType.characterClass]!; final locations = map[PromptTermType.location]!; final total = classes.length * locations.length; var progress = 0; for (final characterClass in classes) { for (final location in locations) { // First we check if the combination has all the images. final key = [ _character, characterClass, location, ].join('_').replaceAll(' ', '_').toLowerCase(); final fileNames = <String>[]; for (var i = 0; i < _variations; i++) { final baseFileName = [ key, '$i.png', ].join('_').replaceAll(' ', '_'); final fileName = path.join( _imagesFolder.path, baseFileName, ); if (File(fileName).existsSync()) { fileNames.add(baseFileName); } } if (fileNames.length != _variations) { tables[key] = fileNames; } progress++; onProgress(progress, total); } } for (final entry in tables.entries) { print( '${entry.key} is missing ${_variations - entry.value.length} images', ); await _dbClient.add( 'image_lookup_table', { 'prompt': entry.key, 'available_images': entry.value, }, ); // So we don't get rate limited. await Future<void>.delayed(const Duration(milliseconds: 50)); } print('Done'); } }
io_flip/api/tools/data_loader/lib/src/create_image_lookup.dart/0
{ "file_path": "io_flip/api/tools/data_loader/lib/src/create_image_lookup.dart", "repo_id": "io_flip", "token_count": 1165 }
858
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { function getMatch(matchId) { return get(/databases/$(database)/documents/matches/$(matchId)); } function getDeck(deckId) { return get(/databases/$(database)/documents/decks/$(deckId)); } function isAuthenticated() { return request.auth != null; } match /prompt_terms/{script} { allow read: if isAuthenticated(); } match /scripts/{script} { allow read: if isAuthenticated(); } match /cards/{card} { allow read, write: if false; } match /decks/{deck_id} { allow read, write: if false; } match /initial_blacklist/{doc} { allow read: if isAuthenticated(); } match /match_states/{match_state_id} { allow read: if isAuthenticated(); allow create: if isAuthenticated() && request.auth.uid == getDeck(getMatch(request.resource.data.matchId).data.host).data.userId; } match /matches/{match_id} { allow read: if isAuthenticated(); allow create: if isAuthenticated() && request.auth.uid == getDeck(request.resource.data.host).data.userId; allow update: if isAuthenticated() && request.auth.uid == getDeck(request.resource.data.guest).data.userId && (resource.data.guest == 'EMPTY' || resource.data.guest == 'RESERVED_EMPTY' || resource.data.guest == 'INVITE'); } match /score_cards/{score_card} { allow read, write: if isAuthenticated() && request.auth.uid == score_card; } match /config/{doc} { allow read: if isAuthenticated(); } } }
io_flip/firestore.rules/0
{ "file_path": "io_flip/firestore.rules", "repo_id": "io_flip", "token_count": 674 }
859
part of 'flop_bloc.dart'; enum FlopStatus { running, success, error, } enum FlopStep { initial, authentication, deckDraft, matchmaking, joinedMatch, playing, } class FlopState extends Equatable { const FlopState({ required this.steps, required this.messages, this.status = FlopStatus.running, }); const FlopState.initial() : this( steps: const [], messages: const [], ); final List<FlopStep> steps; final List<String> messages; final FlopStatus status; FlopState copyWith({ List<FlopStep>? steps, List<String>? messages, FlopStatus? status, }) { return FlopState( steps: steps ?? this.steps, messages: messages ?? this.messages, status: status ?? this.status, ); } FlopState withNewMessage(String message) { return copyWith( messages: [message, ...messages], ); } @override List<Object> get props => [steps, messages, status]; }
io_flip/flop/lib/flop/bloc/flop_state.dart/0
{ "file_path": "io_flip/flop/lib/flop/bloc/flop_state.dart", "repo_id": "io_flip", "token_count": 381 }
860
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. const Set<Song> songs = { // Filenames with whitespace break package:audioplayers on iOS // (as of February 2022), so we use no whitespace. Song( 'GoogleIO-GameMusic-JN-TimeToRumble-JN-Rev1-Ext-LOOPEDonce.mp3', 'TimeToRumble', artist: 'GoogleIO-GameMUsic', ), }; class Song { const Song(this.filename, this.name, {this.artist}); final String filename; final String name; final String? artist; @override String toString() => 'Song<$filename>'; }
io_flip/lib/audio/songs.dart/0
{ "file_path": "io_flip/lib/audio/songs.dart", "repo_id": "io_flip", "token_count": 228 }
861
import 'package:flutter/material.dart' hide Card; 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/audio/audio_controller.dart'; import 'package:io_flip/draft/draft.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip/how_to_play/how_to_play.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/match_making/match_making.dart'; import 'package:io_flip/share/share.dart'; import 'package:io_flip/utils/utils.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; const _handSize = GameCardSize.xs(); const _stackSize = GameCardSize.lg(); typedef CacheImageFunction = Future<void> Function( ImageProvider<Object> provider, BuildContext context, ); class DraftView extends StatefulWidget { const DraftView({ super.key, RouterNeglectCall routerNeglectCall = Router.neglect, String allowPrivateMatch = const String.fromEnvironment('ALLOW_PRIVATE_MATCHES'), CacheImageFunction cacheImage = precacheImage, }) : _routerNeglectCall = routerNeglectCall, _allowPrivateMatch = allowPrivateMatch, _cacheImage = cacheImage; final RouterNeglectCall _routerNeglectCall; final String _allowPrivateMatch; final CacheImageFunction _cacheImage; @override State<DraftView> createState() => _DraftViewState(); } class _DraftViewState extends State<DraftView> { bool imagesLoaded = false; final Map<String, ImageProvider> _toEvict = {}; @override void didChangeDependencies() { super.didChangeDependencies(); if (!imagesLoaded) { final bloc = context.read<DraftBloc>(); if (bloc.state.status == DraftStateStatus.deckLoaded || bloc.state.status == DraftStateStatus.deckSelected) { final providers = { for (final card in bloc.state.cards) card.id: NetworkImage(card.image) }; _toEvict.addAll(providers); Future.wait([ for (final provider in providers.values) widget._cacheImage(provider, context), ]).then((_) { if (mounted) { setState(() { imagesLoaded = true; }); } }); } } } @override void dispose() { for (final provider in _toEvict.values) { provider.evict(); } super.dispose(); } @override Widget build(BuildContext context) { final bloc = context.watch<DraftBloc>(); final state = bloc.state; final l10n = context.l10n; Widget child; if (state.status == DraftStateStatus.deckFailed) { child = IoFlipScaffold( body: Center( child: Text(l10n.cardGenerationError), ), ); } else if (state.status == DraftStateStatus.deckLoading || state.status == DraftStateStatus.initial || !imagesLoaded) { child = const IoFlipScaffold( body: Center( child: CircularProgressIndicator(), ), ); } else { child = DraftLoadedView( routerNeglectCall: widget._routerNeglectCall, allowPrivateMatch: widget._allowPrivateMatch, ); } return BlocListener<DraftBloc, DraftState>( listenWhen: (previous, current) => (previous.status != current.status) && (current.status == DraftStateStatus.playerDeckCreated), listener: (context, state) { for (final card in state.deck?.cards ?? <Card>[]) { _toEvict.remove(card.id); } widget._routerNeglectCall( context, () => GoRouter.of(context).goNamed( 'match_making', extra: MatchMakingPageData( deck: state.deck!, createPrivateMatch: state.createPrivateMatch, inviteCode: state.privateMatchInviteCode, ), ), ); }, child: child, ); } } class DraftLoadedView extends StatefulWidget { const DraftLoadedView({ required RouterNeglectCall routerNeglectCall, required String allowPrivateMatch, super.key, }) : _routerNeglectCall = routerNeglectCall, _allowPrivateMatch = allowPrivateMatch; final RouterNeglectCall _routerNeglectCall; final String _allowPrivateMatch; @override State<DraftLoadedView> createState() => _DraftLoadedViewState(); } class _DraftLoadedViewState extends State<DraftLoadedView> { static const _fadeInDuration = Duration(milliseconds: 450); static const _fadeInCurve = Curves.easeInOut; double get _uiOffset => uiVisible ? 0 : 48; bool uiVisible = false; @override Widget build(BuildContext context) { final stackHeight = 80 - (_stackSize.height * 0.1); final totalStackHeight = _stackSize.height + stackHeight; final uiHeight = totalStackHeight + _handSize.height; final screenSize = MediaQuery.sizeOf(context); final showArrows = screenSize.width > 500 && uiVisible; final center = screenSize.center(Offset.zero); return IoFlipScaffold( bottomBar: AnimatedSlide( duration: _fadeInDuration, curve: _fadeInCurve, offset: Offset(0, uiVisible ? 0 : 0.25), child: AnimatedOpacity( curve: _fadeInCurve, duration: _fadeInDuration, opacity: uiVisible ? 1 : 0, child: _BottomBar( routerNeglectCall: widget._routerNeglectCall, allowPrivateMatch: widget._allowPrivateMatch == 'true', ), ), ), body: Center( child: SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints( maxHeight: uiHeight + IoFlipSpacing.xxxlg, minHeight: uiHeight + IoFlipSpacing.lg, ), child: Stack( children: [ AnimatedPositioned( duration: _fadeInDuration, curve: _fadeInCurve, right: center.dx + _stackSize.width / 2 + IoFlipSpacing.xs, top: _stackSize.height / 2 + _uiOffset, child: AnimatedOpacity( curve: _fadeInCurve, duration: _fadeInDuration, opacity: showArrows ? 1 : 0, child: IconButton( onPressed: () { context .read<AudioController>() .playSfx(Assets.sfx.cardMovement); context.read<DraftBloc>().add(const PreviousCard()); }, icon: const Icon( Icons.arrow_back_ios_new, color: IoFlipColors.seedWhite, ), iconSize: 20, ), ), ), AnimatedPositioned( duration: _fadeInDuration, curve: _fadeInCurve, left: center.dx + _stackSize.width / 2 + IoFlipSpacing.xs, top: _stackSize.height / 2 + _uiOffset, child: AnimatedOpacity( curve: _fadeInCurve, duration: _fadeInDuration, opacity: showArrows ? 1 : 0, child: IconButton( onPressed: () { context .read<AudioController>() .playSfx(Assets.sfx.cardMovement); context.read<DraftBloc>().add(const NextCard()); }, icon: const Icon( Icons.arrow_forward_ios, color: IoFlipColors.seedWhite, ), iconSize: 20, ), ), ), Align( alignment: Alignment.bottomCenter, child: AnimatedSlide( duration: _fadeInDuration, curve: _fadeInCurve, offset: Offset(0, uiVisible ? 0 : 0.25), child: AnimatedOpacity( curve: _fadeInCurve, duration: _fadeInDuration, opacity: uiVisible ? 1 : 0, child: const _SelectedDeck(), ), ), ), AnimatedAlign( curve: _fadeInCurve, duration: _fadeInDuration, alignment: uiVisible ? Alignment.topCenter : Alignment.center, child: AnimatedOpacity( duration: _fadeInDuration, opacity: uiVisible ? 1 : 0, child: BlocBuilder<DraftBloc, DraftState>( builder: (context, state) { final cards = state.cards; return _BackgroundCards(cards); }, ), ), ), AnimatedAlign( curve: _fadeInCurve, duration: _fadeInDuration, alignment: uiVisible ? Alignment.topCenter : Alignment.center, child: DeckPack( onComplete: () { setState(() { uiVisible = true; }); }, size: _stackSize.size, child: const _TopCard(), ), ), ], ), ), ), ), ); } } class _TopCard extends StatelessWidget { const _TopCard(); @override Widget build(BuildContext context) { final card = context.select<DraftBloc, Card>((bloc) => bloc.state.cards.first); final opacity = context .select<DraftBloc, double>((bloc) => bloc.state.firstCardOpacity); return Dismissible( key: ValueKey(card.id), onDismissed: (direction) { context.read<DraftBloc>().add(const CardSwiped()); }, onUpdate: (details) { context.read<DraftBloc>().add(CardSwipeStarted(details.progress)); }, child: Opacity( opacity: opacity, child: Stack( children: [ GameCard( image: card.image, name: card.name, description: card.description, power: card.power, suitName: card.suit.name, isRare: card.rarity, ), Positioned( top: IoFlipSpacing.sm, left: IoFlipSpacing.md, child: RoundedButton.icon( Icons.share_outlined, onPressed: () => IoFlipDialog.show( context, child: ShareCardDialog(card: card), ), ), ) ], ), ), ); } } class _BackgroundCards extends StatelessWidget { const _BackgroundCards(this.cards); final List<Card> cards; @override Widget build(BuildContext context) { final translateTween = Tween<Offset>( begin: Offset.zero, end: const Offset(0, 80), ); final scaleTween = Tween<double>( begin: 1, end: .8, ); final bottomPadding = translateTween.transform(1).dy - ((_stackSize.height * (1 - scaleTween.transform(1))) / 2); return Padding( // Padding required to avoid widgets overlapping due to Stack child's // translations padding: EdgeInsets.only(bottom: bottomPadding), child: Stack( alignment: Alignment.topCenter, children: [ for (var i = cards.length - 1; i > 0; i--) Transform.translate( offset: translateTween.transform( i / cards.length, ), child: Transform.scale( scale: scaleTween.transform( i / cards.length, ), child: GameCard( image: cards[i].image, name: cards[i].name, description: cards[i].description, power: cards[i].power, suitName: cards[i].suit.name, isRare: cards[i].rarity, ), ), ), ], ), ); } } class _SelectedDeck extends StatelessWidget { const _SelectedDeck(); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (var i = 0; i < 3; i++) ...[ Padding( padding: const EdgeInsets.symmetric(horizontal: IoFlipSpacing.xs), child: SelectedCard( i, key: ValueKey('SelectedCard$i'), ), ), ] ], ); } } class SelectedCard extends StatelessWidget { const SelectedCard(this.index, {super.key}); final int index; @override Widget build(BuildContext context) { final bloc = context.watch<DraftBloc>(); final selectedCards = bloc.state.selectedCards; final card = index < selectedCards.length ? selectedCards[index] : null; return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { bloc.add(SelectCard(index)); }, child: Container( width: _handSize.width, height: _handSize.height, decoration: card == null ? BoxDecoration( borderRadius: BorderRadius.circular(IoFlipSpacing.sm), border: Border.all(color: IoFlipColors.seedGrey90), ) : null, child: Stack( children: [ if (card != null) GameCard( image: card.image, name: card.name, description: card.description, suitName: card.suit.name, power: card.power, isRare: card.rarity, size: const GameCardSize.xs(), ) else Positioned( bottom: IoFlipSpacing.xs, right: IoFlipSpacing.xs, child: DecoratedBox( decoration: BoxDecoration( color: IoFlipColors.seedWhite, borderRadius: BorderRadius.circular(4), border: Border.all( width: 2, color: IoFlipColors.seedBlack, ), boxShadow: const [ BoxShadow( offset: Offset(-2, 2), spreadRadius: 1, ), ], ), child: const Icon(Icons.add, size: 32), ), ), ], ), ), ), ); } } class _BottomBar extends StatelessWidget { const _BottomBar({ required this.routerNeglectCall, required this.allowPrivateMatch, }); final RouterNeglectCall routerNeglectCall; final bool allowPrivateMatch; @override Widget build(BuildContext context) { final bloc = context.watch<DraftBloc>(); final state = bloc.state; final l10n = context.l10n; return IoFlipBottomBar( leading: const AudioToggleButton(), middle: state.status == DraftStateStatus.deckSelected ? RoundedButton.text( l10n.joinMatch.toUpperCase(), onPressed: () => routerNeglectCall( context, () { final cardIds = state.selectedCards .cast<Card>() .map((e) => e.id) .toList(); context.read<DraftBloc>().add(PlayerDeckRequested(cardIds)); }, ), onLongPress: allowPrivateMatch ? () => showPrivateMatchDialog(context) : null, ) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( l10n.deckBuildingTitle, style: IoFlipTextStyles.mobileH6Light, ), const SizedBox(height: IoFlipSpacing.xs), Text( l10n.deckBuildingSubtitle, style: IoFlipTextStyles.bodySM, ), ], ), trailing: RoundedButton.icon( Icons.question_mark_rounded, onPressed: () => IoFlipDialog.show( context, child: const HowToPlayDialog(), ), ), ); } void showPrivateMatchDialog(BuildContext context) { final bloc = context.read<DraftBloc>(); final state = bloc.state; showDialog<String?>( context: context, builder: (_) => _JoinPrivateMatchDialog( draftBloc: bloc, selectedCards: state.selectedCards.cast<Card>(), routerNeglectCall: routerNeglectCall, ), ).then((inviteCode) { if (inviteCode != null) { routerNeglectCall( context, () => bloc.add( PlayerDeckRequested( state.selectedCards.cast<Card>().map((e) => e.id).toList(), privateMatchInviteCode: inviteCode, ), ), ); } return inviteCode; }); } } class _JoinPrivateMatchDialog extends StatefulWidget { const _JoinPrivateMatchDialog({ required this.draftBloc, required this.selectedCards, required this.routerNeglectCall, }); final DraftBloc draftBloc; final List<Card> selectedCards; final RouterNeglectCall routerNeglectCall; @override State<_JoinPrivateMatchDialog> createState() => _JoinPrivateMatchDialogState(); } class _JoinPrivateMatchDialogState extends State<_JoinPrivateMatchDialog> { String? inviteCode; @override Widget build(BuildContext context) { return Dialog( child: Container( padding: const EdgeInsets.all(16), width: 400, height: 300, child: Column( children: [ TextField( decoration: const InputDecoration( labelText: 'Invite code', ), onChanged: (value) { setState(() { inviteCode = value; }); }, ), const SizedBox(height: 32), ElevatedButton( onPressed: () { Navigator.of(context).pop(inviteCode); }, child: const Text('Join'), ), ElevatedButton( onPressed: () { Navigator.of(context).pop(null); }, child: const Text('Cancel'), ), const SizedBox(height: 24), ElevatedButton( onPressed: () => widget.routerNeglectCall( context, () => widget.draftBloc.add( PlayerDeckRequested( widget.selectedCards.map((e) => e.id).toList(), createPrivateMatch: true, ), ), ), child: const Text('Create private match'), ), ], ), ), ); } }
io_flip/lib/draft/views/draft_view.dart/0
{ "file_path": "io_flip/lib/draft/views/draft_view.dart", "repo_id": "io_flip", "token_count": 10194 }
862
import 'package:flutter/material.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class QuitGameDialog extends StatelessWidget { const QuitGameDialog({ required this.onConfirm, required this.onCancel, super.key, }); final VoidCallback onConfirm; final VoidCallback onCancel; @override Widget build(BuildContext context) { final l10n = context.l10n; return Column( mainAxisSize: MainAxisSize.min, children: [ Text( l10n.quitGameDialogTitle, style: IoFlipTextStyles.headlineH4, ), const SizedBox(height: IoFlipSpacing.sm), Text( l10n.quitGameDialogDescription, textAlign: TextAlign.center, style: IoFlipTextStyles.bodyLG, ), const SizedBox(height: IoFlipSpacing.xlg), RoundedButton.text( l10n.continueLabel, onPressed: onConfirm, ), const SizedBox(height: IoFlipSpacing.sm), RoundedButton.text( l10n.cancel, backgroundColor: IoFlipColors.seedWhite, onPressed: onCancel, ), ], ); } }
io_flip/lib/game/widgets/quit_game_dialog.dart/0
{ "file_path": "io_flip/lib/game/widgets/quit_game_dialog.dart", "repo_id": "io_flip", "token_count": 558 }
863
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/utils/utils.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class InfoView extends StatelessWidget { const InfoView({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final links = { l10n.ioLinkLabel: ExternalLinks.googleIO, l10n.privacyPolicyLinkLabel: ExternalLinks.privacyPolicy, l10n.termsOfServiceLinkLabel: ExternalLinks.termsOfService, l10n.faqLinkLabel: ExternalLinks.faq, }; final descriptionStyle = IoFlipTextStyles.bodyLG.copyWith( color: IoFlipColors.seedWhite, ); final linkStyle = IoFlipTextStyles.linkLG.copyWith( color: IoFlipColors.seedYellow, ); return Column( mainAxisSize: MainAxisSize.min, children: [ IoFlipLogo(height: 93), const SizedBox(height: IoFlipSpacing.xxlg + IoFlipSpacing.sm), Text( l10n.infoDialogTitle, style: IoFlipTextStyles.mobileH6Light, ), const SizedBox(height: IoFlipSpacing.md), RichText( textAlign: TextAlign.center, text: TextSpan( text: l10n.infoDialogDescriptionPrefix, style: descriptionStyle, children: [ const TextSpan(text: ' '), TextSpan( text: l10n.infoDialogDescriptionInfixOne, recognizer: TapGestureRecognizer() ..onTap = () => openLink(ExternalLinks.howItsMade), style: linkStyle, ), const TextSpan(text: ' '), TextSpan( text: l10n.infoDialogDescriptionInfixTwo, style: descriptionStyle, ), const TextSpan(text: ' '), TextSpan( text: l10n.infoDialogDescriptionSuffix, recognizer: TapGestureRecognizer() ..onTap = () => openLink(ExternalLinks.openSourceCode), style: linkStyle, ), ], ), ), const SizedBox(height: IoFlipSpacing.xxlg + IoFlipSpacing.sm), Text( l10n.infoDialogOtherLinks, style: IoFlipTextStyles.mobileH6Light, ), for (final link in links.entries) ...[ const SizedBox(height: IoFlipSpacing.md), RichText( text: TextSpan( text: link.key, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => openLink(link.value), ), ) ], ], ); } }
io_flip/lib/info/view/info_view.dart/0
{ "file_path": "io_flip/lib/info/view/info_view.dart", "repo_id": "io_flip", "token_count": 1386 }
864
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class LeaderboardView extends StatelessWidget { const LeaderboardView({super.key}); @override Widget build(BuildContext context) { const highlightColor = IoFlipColors.seedYellow; final bloc = context.watch<LeaderboardBloc>(); final state = bloc.state; final l10n = context.l10n; final leaderboard = state.leaderboard; if (state.status == LeaderboardStateStatus.loading || state.status == LeaderboardStateStatus.initial) { return const Center(child: CircularProgressIndicator()); } if (state.status == LeaderboardStateStatus.failed) { return Center(child: Text(l10n.leaderboardFailedToLoad)); } return Padding( padding: const EdgeInsets.all(IoFlipSpacing.xlg), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 340), child: Column( children: [ Text( l10n.leaderboardLongestStreak, style: IoFlipTextStyles.buttonSM.copyWith(color: highlightColor), ), const SizedBox(height: IoFlipSpacing.sm), const Divider(thickness: 2, color: highlightColor), const SizedBox(height: IoFlipSpacing.xs), LeaderboardPlayers( players: leaderboard .map( (e) => LeaderboardPlayer( index: leaderboard.indexOf(e), initials: e.initials, value: e.longestStreak, ), ) .toList(), ) ], ), ), ); } }
io_flip/lib/leaderboard/views/leaderboard_view.dart/0
{ "file_path": "io_flip/lib/leaderboard/views/leaderboard_view.dart", "repo_id": "io_flip", "token_count": 860 }
865
import 'package:api_client/api_client.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:game_domain/game_domain.dart'; part 'prompt_form_event.dart'; part 'prompt_form_state.dart'; class PromptFormBloc extends Bloc<PromptFormEvent, PromptFormState> { PromptFormBloc({ required PromptResource promptResource, }) : _promptResource = promptResource, super(const PromptFormState.initial()) { on<PromptTermsRequested>(_onPromptTermsRequested); on<PromptSubmitted>(_onPromptSubmitted); } final PromptResource _promptResource; Future<void> _onPromptTermsRequested( PromptTermsRequested event, Emitter<PromptFormState> emit, ) async { try { emit(state.copyWith(status: PromptTermsStatus.loading)); final result = await Future.wait<List<String>>([ _promptResource.getPromptTerms(PromptTermType.characterClass), _promptResource.getPromptTerms(PromptTermType.power), ]); emit( state.copyWith( characterClasses: result[0]..sort(), powers: result[1]..sort(), status: PromptTermsStatus.loaded, ), ); } catch (e, s) { addError(e, s); emit(state.copyWith(status: PromptTermsStatus.failed)); } } void _onPromptSubmitted( PromptSubmitted event, Emitter<PromptFormState> emit, ) { emit(state.copyWith(prompts: event.data)); } }
io_flip/lib/prompt/bloc/prompt_form_bloc.dart/0
{ "file_path": "io_flip/lib/prompt/bloc/prompt_form_bloc.dart", "repo_id": "io_flip", "token_count": 574 }
866
export 'cubit/scripts_cubit.dart'; export 'views/views.dart';
io_flip/lib/scripts/scripts.dart/0
{ "file_path": "io_flip/lib/scripts/scripts.dart", "repo_id": "io_flip", "token_count": 26 }
867
import 'package:api_client/api_client.dart'; import 'package:flutter/material.dart' hide Card; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/share/widgets/widgets.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:provider/provider.dart'; class ShareHandDialog extends StatelessWidget { const ShareHandDialog({ required this.wins, required this.initials, required this.deck, super.key, }); final Deck deck; final int wins; final String initials; @override Widget build(BuildContext context) { final shareResource = context.watch<ShareResource>(); final twitterLink = shareResource.twitterShareHandUrl(deck.id); final facebookLink = shareResource.facebookShareHandUrl(deck.id); return ShareDialog( twitterShareUrl: twitterLink, facebookShareUrl: facebookLink, downloadCards: deck.cards, downloadDeck: deck, content: _DialogContent( cards: deck.cards, wins: wins, initials: initials, ), ); } } class _DialogContent extends StatelessWidget { const _DialogContent({ required this.cards, required this.wins, required this.initials, }); final List<Card> cards; final int wins; final String initials; @override Widget build(BuildContext context) { final l10n = context.l10n; return Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.all(IoFlipSpacing.lg), child: FittedBox( fit: BoxFit.scaleDown, child: CardFan(cards: cards), ), ), const SizedBox(height: IoFlipSpacing.lg), Text( l10n.shareTeamDialogDescription, style: IoFlipTextStyles.mobileH4, textAlign: TextAlign.center, ), const SizedBox(height: IoFlipSpacing.lg), Text( initials, style: IoFlipTextStyles.mobileH1, textAlign: TextAlign.center, ), Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( Assets.images.tempPreferencesCustom.path, color: IoFlipColors.seedGreen, ), const SizedBox(width: IoFlipSpacing.sm), Text( '$wins ${l10n.winStreakLabel}', style: IoFlipTextStyles.mobileH6 .copyWith(color: IoFlipColors.seedGreen), ), ], ), ], ); } }
io_flip/lib/share/views/share_hand_dialog.dart/0
{ "file_path": "io_flip/lib/share/views/share_hand_dialog.dart", "repo_id": "io_flip", "token_count": 1204 }
868
export 'external_links.dart'; export 'maybe_pop_extension.dart'; export 'router_neglect_call.dart'; export 'text_size.dart';
io_flip/lib/utils/utils.dart/0
{ "file_path": "io_flip/lib/utils/utils.dart", "repo_id": "io_flip", "token_count": 47 }
869
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:api_client/api_client.dart'; import 'package:encrypt/encrypt.dart'; import 'package:game_domain/game_domain.dart'; import 'package:http/http.dart' as http; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:web_socket_client/web_socket_client.dart'; class _MockHttpClient extends Mock { Future<http.Response> get(Uri uri, {Map<String, String>? headers}); Future<http.Response> post( Uri uri, { Object? body, Map<String, String>? headers, }); Future<http.Response> patch( Uri uri, { Object? body, Map<String, String>? headers, }); Future<http.Response> put( Uri uri, { Object? body, Map<String, String>? headers, }); } class _FakeConnection extends Fake implements Connection { _FakeConnection(this.stream); final Stream<ConnectionState> stream; @override Future<ConnectionState> firstWhere( bool Function(ConnectionState element) test, { ConnectionState Function()? orElse, }) => stream.firstWhere(test, orElse: orElse); @override Stream<ConnectionState> where(bool Function(ConnectionState event) test) => stream.where(test); } class _MockWebSocket extends Mock implements WebSocket {} class _MockWebSocketFactory extends Mock { WebSocket call(Uri uri, {Duration? timeout, String? binaryType}); } void main() { setUpAll(() { registerFallbackValue(Uri.parse('http://localhost')); }); group('ApiClient', () { const baseUrl = 'http://baseurl.com'; const webSocketTimeout = Duration(milliseconds: 200); const mockIdToken = 'mockIdToken'; const mockNewIdToken = 'mockNewIdToken'; const mockAppCheckToken = 'mockAppCheckToken'; // Since the key and iv are set from the environment variables, we can // reference the default values here. final key = Key.fromUtf8('encryption_key_not_set_123456789'); final iv = IV.fromUtf8('iv_not_set_12345'); final encrypter = Encrypter(AES(key)); final testJson = {'data': 'test'}; final encrypted = encrypter.encrypt(jsonEncode(testJson), iv: iv).base64; final encryptedResponse = http.Response(encrypted, 200); final expectedResponse = http.Response(testJson.toString(), 200); late ApiClient subject; late _MockHttpClient httpClient; late StreamController<String?> idTokenStreamController; late StreamController<String?> appCheckTokenStreamController; late WebSocketFactory webSocketFactory; late WebSocket webSocket; late StreamController<ConnectionState> connectionStreamController; Future<String?> Function() refreshIdToken = () async => null; setUp(() { httpClient = _MockHttpClient(); when( () => httpClient.get( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => encryptedResponse); when( () => httpClient.post( any(), body: any(named: 'body'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => encryptedResponse); when( () => httpClient.patch( any(), body: any(named: 'body'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => encryptedResponse); when( () => httpClient.put( any(), body: any(named: 'body'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => encryptedResponse); idTokenStreamController = StreamController.broadcast(); appCheckTokenStreamController = StreamController.broadcast(); webSocketFactory = _MockWebSocketFactory().call; connectionStreamController = StreamController.broadcast(); webSocket = _MockWebSocket(); when(() => webSocket.connection).thenAnswer( (_) => _FakeConnection(connectionStreamController.stream), ); when( () => webSocketFactory( any(), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).thenReturn(webSocket); subject = ApiClient( baseUrl: baseUrl, getCall: httpClient.get, postCall: httpClient.post, patchCall: httpClient.patch, putCall: httpClient.put, idTokenStream: idTokenStreamController.stream, refreshIdToken: () => refreshIdToken(), appCheckTokenStream: appCheckTokenStreamController.stream, webSocketFactory: webSocketFactory.call, webSocketTimeout: webSocketTimeout, ); }); test('can be instantiated', () { expect( ApiClient( baseUrl: 'http://localhost', idTokenStream: Stream.empty(), refreshIdToken: () async => null, appCheckTokenStream: Stream.empty(), ), isNotNull, ); }); group('GameResource', () { test('returns a GameResource', () { expect(subject.gameResource, isA<GameResource>()); }); }); group('ScriptsResource', () { test('returns a ScriptsResource', () { expect(subject.scriptsResource, isA<ScriptsResource>()); }); }); group('dispose', () { test('cancels id token stream subscription', () async { expect(idTokenStreamController.hasListener, isTrue); expect(appCheckTokenStreamController.hasListener, isTrue); await subject.dispose(); expect(idTokenStreamController.hasListener, isFalse); expect(appCheckTokenStreamController.hasListener, isFalse); }); }); group('get', () { test('returns the response', () async { final response = await subject.get('/'); expect(response.statusCode, equals(expectedResponse.statusCode)); expect(response.body, equals(expectedResponse.body)); }); test('sends the request correctly', () async { await subject.get( '/path/to/endpoint', queryParameters: { 'param1': 'value1', 'param2': 'value2', }, ); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint?param1=value1&param2=value2'), headers: {}, ), ).called(1); }); test('sends the authentication and app check token', () async { idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.get('/path/to/endpoint'); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken }, ), ).called(1); }); test('refreshes the authentication token when needed', () async { when( () => httpClient.get( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => http.Response('', 401)); refreshIdToken = () async => mockNewIdToken; idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.get('/path/to/endpoint'); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, }, ), ).called(1); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockNewIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, }, ), ).called(1); }); }); group('getPublic', () { setUp(() { when( () => httpClient.get( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => expectedResponse); }); test('returns the response', () async { final response = await subject.getPublic('/'); expect(response.statusCode, equals(expectedResponse.statusCode)); expect(response.body, equals(expectedResponse.body)); }); test('sends the request correctly', () async { await subject.getPublic( '/path/to/endpoint', queryParameters: { 'param1': 'value1', 'param2': 'value2', }, ); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint?param1=value1&param2=value2'), headers: {}, ), ).called(1); }); test('sends the authentication and app check token', () async { idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.getPublic('/path/to/endpoint'); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken }, ), ).called(1); }); test('refreshes the authentication token when needed', () async { when( () => httpClient.get( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => http.Response('', 401)); refreshIdToken = () async => mockNewIdToken; idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.getPublic('/path/to/endpoint'); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, }, ), ).called(1); verify( () => httpClient.get( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockNewIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, }, ), ).called(1); }); }); group('post', () { test('returns the response', () async { final response = await subject.post('/'); expect(response.statusCode, equals(expectedResponse.statusCode)); expect(response.body, equals(expectedResponse.body)); }); test('sends the request correctly', () async { await subject.post( '/path/to/endpoint', queryParameters: {'param1': 'value1', 'param2': 'value2'}, body: 'BODY_CONTENT', ); verify( () => httpClient.post( Uri.parse('$baseUrl/path/to/endpoint?param1=value1&param2=value2'), body: 'BODY_CONTENT', headers: {HttpHeaders.contentTypeHeader: ContentType.json.value}, ), ).called(1); }); test('sends the authentication and app check token', () async { idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.post('/path/to/endpoint'); verify( () => httpClient.post( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); test('refreshes the authentication token when needed', () async { when( () => httpClient.post( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => http.Response('', 401)); refreshIdToken = () async => mockNewIdToken; idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.post('/path/to/endpoint'); verify( () => httpClient.post( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); verify( () => httpClient.post( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockNewIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); }); group('patch', () { test('returns the response', () async { final response = await subject.patch('/'); expect(response.statusCode, equals(expectedResponse.statusCode)); expect(response.body, equals(expectedResponse.body)); }); test('sends the request correctly', () async { await subject.patch( '/path/to/endpoint', queryParameters: {'param1': 'value1', 'param2': 'value2'}, body: 'BODY_CONTENT', ); verify( () => httpClient.patch( Uri.parse('$baseUrl/path/to/endpoint?param1=value1&param2=value2'), body: 'BODY_CONTENT', headers: {HttpHeaders.contentTypeHeader: ContentType.json.value}, ), ).called(1); }); test('sends the authentication and app check token', () async { idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.patch('/path/to/endpoint'); verify( () => httpClient.patch( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); test('refreshes the authentication token when needed', () async { when( () => httpClient.patch( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => http.Response('', 401)); refreshIdToken = () async => mockNewIdToken; idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.patch('/path/to/endpoint'); verify( () => httpClient.patch( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); verify( () => httpClient.patch( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockNewIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); }); group('put', () { test('returns the response', () async { final response = await subject.put('/'); expect(response.statusCode, equals(expectedResponse.statusCode)); expect(response.body, equals(expectedResponse.body)); }); test('sends the request correctly', () async { await subject.put( '/path/to/endpoint', body: 'BODY_CONTENT', ); verify( () => httpClient.put( Uri.parse('$baseUrl/path/to/endpoint'), body: 'BODY_CONTENT', headers: {HttpHeaders.contentTypeHeader: ContentType.json.value}, ), ).called(1); }); test('sends the authentication and app check token', () async { idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.put('/path/to/endpoint'); verify( () => httpClient.put( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); test('refreshes the authentication token when needed', () async { when( () => httpClient.put( any(), headers: any(named: 'headers'), ), ).thenAnswer((_) async => http.Response('', 401)); refreshIdToken = () async => mockNewIdToken; idTokenStreamController.add(mockIdToken); appCheckTokenStreamController.add(mockAppCheckToken); await Future.microtask(() {}); await subject.put('/path/to/endpoint'); verify( () => httpClient.put( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); verify( () => httpClient.put( Uri.parse('$baseUrl/path/to/endpoint'), headers: { 'Authorization': 'Bearer $mockNewIdToken', 'X-Firebase-AppCheck': mockAppCheckToken, HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ).called(1); }); }); group('ws connect', () { const path = '/path'; setUp(() { connectionStreamController.onListen = () { connectionStreamController.add(Connected()); }; }); test('returns the connection with a "ws" scheme for http', () async { final response = await subject.connect(path); expect(response, equals(webSocket)); verify( () => webSocketFactory( Uri.parse('ws://baseurl.com/path'), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).called(1); }); test('returns the connection with a "wss" scheme for https', () async { subject = ApiClient( baseUrl: baseUrl.replaceAll('http', 'https'), getCall: httpClient.get, postCall: httpClient.post, putCall: httpClient.put, idTokenStream: idTokenStreamController.stream, refreshIdToken: () => refreshIdToken(), appCheckTokenStream: appCheckTokenStreamController.stream, webSocketFactory: webSocketFactory.call, ); final response = await subject.connect(path); expect(response, equals(webSocket)); verify( () => webSocketFactory( Uri.parse('wss://baseurl.com/path'), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).called(1); }); test('sends the token message after connection is established', () async { connectionStreamController.onListen = null; idTokenStreamController.add('token'); await Future.microtask(() {}); final response = subject.connect(path); connectionStreamController.add(Connected()); expect(await response, equals(webSocket)); await Future.microtask(() {}); verify( () => webSocket.send( jsonEncode( WebSocketMessage.token('token', reconnect: true), ), ), ).called(1); verify( () => webSocketFactory( Uri.parse('ws://baseurl.com/path'), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).called(1); }); test( 'sends the token reconnect message every time the client reconnects', () async { connectionStreamController.onListen = null; idTokenStreamController.add('token'); await Future.microtask(() {}); final response = subject.connect(path); connectionStreamController.add(Connected()); expect(await response, equals(webSocket)); await Future.microtask(() {}); verify( () => webSocket.send( jsonEncode(WebSocketMessage.token('token', reconnect: true)), ), ).called(1); connectionStreamController.add(Reconnected()); await Future.microtask(() {}); verify( () => webSocket.send( jsonEncode( WebSocketMessage.token('token', reconnect: true), ), ), ).called(1); connectionStreamController.add(Reconnected()); await Future.microtask(() {}); verify( () => webSocket.send( jsonEncode( WebSocketMessage.token('token', reconnect: true), ), ), ).called(1); connectionStreamController.add(Reconnected()); await Future.microtask(() {}); verify( () => webSocket.send( jsonEncode( WebSocketMessage.token('token', reconnect: true), ), ), ).called(1); verify( () => webSocketFactory( Uri.parse('ws://baseurl.com/path'), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).called(1); }, ); test('throws ApiClientError on error', () async { when( () => webSocketFactory( any(), timeout: any(named: 'timeout'), binaryType: 'blob', ), ).thenThrow(Exception('oops')); await expectLater( () => subject.connect(path), throwsA(isA<ApiClientError>()), ); }); }); group('shareHandUrl', () { test('returns the correct url', () { expect( subject.shareHandUrl('id'), equals('http://baseurl.com/public/share?deckId=id'), ); }); }); group('shareCardUrl', () { test('returns the correct url', () { expect( subject.shareCardUrl('id'), equals('http://baseurl.com/public/share?cardId=id'), ); }); }); group('ApiClientError', () { test('toString returns the cause', () { expect( ApiClientError('Ops', StackTrace.empty).toString(), equals('Ops'), ); }); }); }); }
io_flip/packages/api_client/test/src/api_client_test.dart/0
{ "file_path": "io_flip/packages/api_client/test/src/api_client_test.dart", "repo_id": "io_flip", "token_count": 10705 }
870
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('User', () { test('supports value equality', () { const userA = User(id: 'A'); const secondUserA = User(id: 'A'); const userB = User(id: 'B'); expect(userA, equals(secondUserA)); expect(userA, isNot(equals(userB))); }); }); }
io_flip/packages/authentication_repository/test/src/models/user_test.dart/0
{ "file_path": "io_flip/packages/authentication_repository/test/src/models/user_test.dart", "repo_id": "io_flip", "token_count": 167 }
871
import 'dart:async'; import 'dart:convert'; import 'package:api_client/api_client.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:game_domain/game_domain.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:web_socket_client/web_socket_client.dart'; class _MockApiClient extends Mock implements ApiClient {} class _MockWebSocket extends Mock implements WebSocket {} void main() { late ApiClient apiClient; late WebSocket webSocket; late StreamController<dynamic> webSocketMessages; late ConnectionRepository subject; setUp(() { apiClient = _MockApiClient(); webSocket = _MockWebSocket(); webSocketMessages = StreamController<dynamic>(); when(() => apiClient.connect(any())).thenAnswer((_) async => webSocket); when(() => webSocket.messages).thenAnswer((_) => webSocketMessages.stream); when(webSocket.close).thenAnswer((_) async {}); when(() => webSocket.send(any<String>())).thenAnswer((_) async {}); subject = ConnectionRepository(apiClient: apiClient); }); group('ConnectionRepository', () { group('connect', () { test('calls connect on api client with correct path', () async { await subject.connect(); verify(() => apiClient.connect('/public/connect')).called(1); }); }); group('messages', () { test('emits all WebSocketMessages and ignores other messages', () async { await subject.connect(); webSocketMessages ..add(jsonEncode(const WebSocketMessage.connected())) ..add('not a WebSocketMessage') ..add(jsonEncode(const WebSocketMessage.matchLeft())) ..add(jsonEncode({'not': 'a WebSocketMessage'})); await expectLater( subject.messages, emitsInOrder([ const WebSocketMessage.connected(), const WebSocketMessage.matchLeft(), ]), ); }); }); group('send', () { test('calls send on web socket with correct message', () async { await subject.connect(); subject.send(const WebSocketMessage.connected()); verify( () => webSocket.send(jsonEncode(const WebSocketMessage.connected())), ).called(1); }); }); group('close', () { test('calls close on web socket', () async { await subject.connect(); subject.close(); verify(() => webSocket.close()).called(1); }); }); }); }
io_flip/packages/connection_repository/test/src/connection_repository_test.dart/0
{ "file_path": "io_flip/packages/connection_repository/test/src/connection_repository_test.dart", "repo_id": "io_flip", "token_count": 944 }
872
import 'package:flutter/material.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class StoryScaffold extends StatelessWidget { const StoryScaffold({ super.key, required this.title, required this.body, this.backgroundColor, }); final String title; final Widget body; final Color? backgroundColor; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: backgroundColor, appBar: AppBar( title: Text(title), titleTextStyle: IoFlipTextStyles.mobile.titleSmall, ), body: body, ); } }
io_flip/packages/io_flip_ui/gallery/lib/story_scaffold.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/lib/story_scaffold.dart", "repo_id": "io_flip", "token_count": 228 }
873
import 'package:flutter/material.dart'; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class _FlowData { _FlowData( this.step1, this.step2, this.step3, ); final String? step1; final String? step2; final String? step3; _FlowData copyWith({ String? step1, String? step2, String? step3, }) { return _FlowData( step1 ?? this.step1, step2 ?? this.step2, step3 ?? this.step3, ); } @override String toString() { return ''' step 1: $step1 step 2: $step2 step 3: $step3'''; } } class SimpleFlowStory extends StatelessWidget { const SimpleFlowStory({super.key}); @override Widget build(BuildContext context) { return StoryScaffold( title: 'Simple flow', body: SimpleFlow( initialData: () => _FlowData(null, null, null), onComplete: (data) { // open alert showing the complete data showDialog<void>( context: context, builder: (context) { return AlertDialog( title: const Text('Flow completed!'), content: Text(data.toString()), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('OK'), ), ], ); }, ); }, stepBuilder: (context, data, _) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(data.toString()), TextField( key: ValueKey(data), onSubmitted: (value) { if (data.step1 == null) { return context.updateFlow<_FlowData>((current) { return current.copyWith(step1: value); }); } if (data.step2 == null) { return context.updateFlow<_FlowData>((current) { return current.copyWith(step2: value); }); } return context.completeFlow<_FlowData>((current) { return current.copyWith(step3: value); }); }, ), ], ); }, ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/widgets/simple_flow_story.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/lib/widgets/simple_flow_story.dart", "repo_id": "io_flip", "token_count": 1329 }
874
import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; /// {@template air_damage} // ignore: comment_references /// A widget that renders several [SpriteAnimation]s for the damages /// of a card on another. /// {@endtemplate} class AirDamage extends ElementalDamage { /// {@macro air_damage} AirDamage({required super.size}) : super( chargeBackPath: Assets.images.elements.desktop.air.chargeBack.keyName, chargeFrontPath: Assets.images.elements.desktop.air.chargeFront.keyName, damageReceivePath: Assets.images.elements.desktop.air.damageReceive.keyName, damageSendPath: Assets.images.elements.desktop.air.damageSend.keyName, victoryChargeBackPath: Assets.images.elements.desktop.air.victoryChargeBack.keyName, victoryChargeFrontPath: Assets.images.elements.desktop.air.victoryChargeFront.keyName, badgePath: Assets.images.suits.card.air.keyName, animationColor: IoFlipColors.seedSilver, ); }
io_flip/packages/io_flip_ui/lib/src/animations/damages/air_damage.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/animations/damages/air_damage.dart", "repo_id": "io_flip", "token_count": 439 }
875
/// Spacing used in the I/O FLIP UI. abstract class IoFlipSpacing { /// The default unit of spacing static const double spaceUnit = 16; /// xxxs spacing value (1pt) static const double xxxs = 0.0625 * spaceUnit; /// xxs spacing value (2pt) static const double xxs = 0.125 * spaceUnit; /// xs spacing value (4pt) static const double xs = 0.25 * spaceUnit; /// sm spacing value (8pt) static const double sm = 0.5 * spaceUnit; /// md spacing value (12pt) static const double md = 0.75 * spaceUnit; /// lg spacing value (16pt) static const double lg = spaceUnit; /// smxlg spacing value (20pt) static const double xlgsm = 1.25 * spaceUnit; /// xlg spacing value (24pt) static const double xlg = 1.5 * spaceUnit; /// xxlg spacing value (40pt) static const double xxlg = 2.5 * spaceUnit; /// xxxlg pacing value (64pt) static const double xxxlg = 4 * spaceUnit; }
io_flip/packages/io_flip_ui/lib/src/theme/io_flip_spacing.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/theme/io_flip_spacing.dart", "repo_id": "io_flip", "token_count": 309 }
876
import 'package:flame/cache.dart'; import 'package:flame/extensions.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:provider/provider.dart'; /// {@template victory_charge_back} /// A widget that renders a [SpriteAnimation] for the victory charge /// behind the card. /// {@endtemplate} class VictoryChargeBack extends StatelessWidget { /// {@macro victory_charge_back} const VictoryChargeBack( this.path, { required this.size, required this.assetSize, required this.animationColor, super.key, this.onComplete, }); /// The size of the card. final GameCardSize size; /// Optional callback to be called when the animation is complete. final VoidCallback? onComplete; /// Path of the asset containing the sprite sheet. final String path; /// The color of the animation, used on mobile animation. final Color animationColor; /// Size of the assets to use, large or small final AssetSize assetSize; @override Widget build(BuildContext context) { final images = context.read<Images>(); final width = 1.5 * size.width; final height = 1.22 * size.height; final textureSize = Vector2(607, 695); if (assetSize == AssetSize.large) { return SizedBox( width: width, height: height, child: FittedBox( fit: BoxFit.fill, child: SizedBox( width: textureSize.x, height: textureSize.y, child: SpriteAnimationWidget.asset( path: path, images: images, anchor: Anchor.center, onComplete: onComplete, data: SpriteAnimationData.sequenced( amount: 18, amountPerRow: 6, textureSize: textureSize, stepTime: 0.04, loop: false, ), ), ), ), ); } else { return _MobileAnimation( onComplete: onComplete, animationColor: animationColor, width: width, height: height, cardSize: size, ); } } } class _MobileAnimation extends StatefulWidget { const _MobileAnimation({ required this.onComplete, required this.animationColor, required this.cardSize, required this.width, required this.height, }); final VoidCallback? onComplete; final Color animationColor; final GameCardSize cardSize; final double width; final double height; @override State<_MobileAnimation> createState() => _MobileAnimationState(); } class _MobileAnimationState extends State<_MobileAnimation> { var _top = 0.0; @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) { setState(() { _top = widget.cardSize.height; }); }); } void _onComplete() { widget.onComplete?.call(); } @override Widget build(BuildContext context) { return Align( alignment: const Alignment(0, -.8), child: SizedBox( width: widget.width, height: widget.height, child: Stack( children: [ AnimatedPositioned( onEnd: _onComplete, duration: const Duration(milliseconds: 400), top: _top, child: Container( width: widget.cardSize.width * 1.3, height: widget.cardSize.height * .05, decoration: BoxDecoration( color: widget.animationColor, borderRadius: BorderRadius.circular( widget.cardSize.width / 2, ), boxShadow: [ BoxShadow( color: widget.animationColor, blurRadius: widget.cardSize.height * .06, spreadRadius: widget.cardSize.height * .05, ), ], ), ), ), ], ), ), ); } }
io_flip/packages/io_flip_ui/lib/src/widgets/damages/victory_charge_back.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/damages/victory_charge_back.dart", "repo_id": "io_flip", "token_count": 1833 }
877
import 'dart:ui'; import 'package:flutter/widgets.dart'; /// Builds the widget for a [TiltBuilder] typedef OffsetWidgetBuilder = Widget Function( BuildContext context, Offset offset, ); /// {@template tilt_builder} /// Used to build another widget, passing down the pointer position /// as an [Offset] with dx and dy between -1 and 1. It also animates the /// offset back to [Offset.zero] when the pointer leaves. /// {@endtemplate} class TiltBuilder extends StatefulWidget { /// {@macro tilt_builder} const TiltBuilder({required this.builder, super.key}); /// Builds a child widget with an offset determined by the pointer position. final OffsetWidgetBuilder builder; @override State<TiltBuilder> createState() => _TiltBuilderState(); } class _TiltBuilderState extends State<TiltBuilder> with SingleTickerProviderStateMixin { late final AnimationController _animationController; final _tiltTween = Tween<Offset>(end: Offset.zero); Offset tilt = Offset.zero; bool entered = false; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 300), ); } void reset(_) { _tiltTween ..begin = tilt ..end = Offset.zero; _animationController ..addListener(onAnimationUpdate) ..forward(from: 0); } void startTilt(Offset mousePosition) { final newTilt = getTilt(mousePosition); if (newTilt != null) { _tiltTween ..begin = tilt ..end = newTilt; _animationController ..addListener(onAnimationUpdate) ..forward(from: 0).whenCompleteOrCancel(() { entered = true; }); } } void onUpdate(Offset pointerPosition) { if (entered) { final newTilt = getTilt(pointerPosition); if (newTilt != null) { setState(() { tilt = newTilt; }); } } } void onAnimationUpdate() { setState(() { tilt = _tiltTween .chain(CurveTween(curve: Curves.easeOutQuad)) .evaluate(_animationController); }); } Offset? getTilt(Offset mousePosition) { final size = context.size; if (size != null) { final dx = (mousePosition.dx / size.width) * 2 - 1; final dy = (mousePosition.dy / size.height) * 2 - 1; return Offset(dx, dy); } return null; } @override void dispose() { _animationController ..removeListener(onAnimationUpdate) ..dispose(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( onPanStart: (details) { if (details.kind == PointerDeviceKind.touch) { startTilt(details.localPosition); } }, onPanUpdate: (details) => onUpdate(details.localPosition), onPanEnd: reset, child: MouseRegion( onExit: reset, onEnter: (event) => startTilt(event.localPosition), onHover: (event) => onUpdate(event.localPosition), child: widget.builder(context, tilt), ), ); } }
io_flip/packages/io_flip_ui/lib/src/widgets/tilt_builder.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/tilt_builder.dart", "repo_id": "io_flip", "token_count": 1201 }
878
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:provider/provider.dart'; void main() { group('RoundedButton', () { testWidgets('renders the given icon and responds to taps', (tester) async { var wasTapped = false; await tester.pumpSubject( RoundedButton.icon( Icons.settings, onPressed: () => wasTapped = true, ), ); await tester.tap(find.byIcon(Icons.settings)); expect(wasTapped, isTrue); }); testWidgets('responds to long press', (tester) async { var wasTapped = false; await tester.pumpSubject( RoundedButton.icon( Icons.settings, onLongPress: () => wasTapped = true, ), ); await tester.longPress(find.byIcon(Icons.settings)); expect(wasTapped, isTrue); }); testWidgets('cancelling tap animates correctly', (tester) async { var wasTapped = false; await tester.pumpSubject( RoundedButton.icon( Icons.settings, onPressed: () => wasTapped = true, ), ); final state = tester.state(find.byType(RoundedButton)) as RoundedButtonState; await tester.drag(find.byIcon(Icons.settings), const Offset(0, 100)); expect(wasTapped, isFalse); expect(state.isPressed, isFalse); }); testWidgets('renders the given svg and responds to taps', (tester) async { var wasTapped = false; await tester.pumpSubject( RoundedButton.svg( Assets.images.ioFlipLogo.keyName, onPressed: () => wasTapped = true, ), ); await tester.tap(find.byType(SvgPicture)); expect(wasTapped, isTrue); }); testWidgets('renders the given text and responds to taps', (tester) async { var wasTapped = false; await tester.pumpSubject( RoundedButton.text( 'test', onPressed: () => wasTapped = true, ), ); await tester.tap(find.text('test')); expect(wasTapped, isTrue); }); testWidgets('plays a sound when tapped', (tester) async { var soundPlayed = false; await tester.pumpSubject( RoundedButton.text( 'test', onPressed: () {}, ), playButtonSound: () => soundPlayed = true, ); await tester.tap(find.text('test')); expect(soundPlayed, isTrue); }); testWidgets( 'no sound is played if no tap handler is attached', (tester) async { var soundPlayed = false; await tester.pumpSubject( RoundedButton.text('test'), playButtonSound: () => soundPlayed = true, ); await tester.tap(find.text('test')); expect(soundPlayed, isFalse); }, ); testWidgets('renders the given image and label and responds to taps', (tester) async { final file = File(''); var wasTapped = false; await tester.pumpSubject( RoundedButton.image( Image.file(file), label: 'test', onPressed: () { wasTapped = true; }, ), ); await tester.tap(find.text('test')); expect(find.byType(Image), findsOneWidget); expect(wasTapped, isTrue); }); }); } extension RoundedButtonTest on WidgetTester { Future<void> pumpSubject( Widget child, { void Function()? playButtonSound, }) { return pumpWidget( MaterialApp( home: Provider( create: (_) => UISoundAdapter( playButtonSound: playButtonSound ?? () {}, ), child: Scaffold( body: Center( child: child, ), ), ), ), ); } }
io_flip/packages/io_flip_ui/test/src/widgets/rounded_button_test.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/test/src/widgets/rounded_button_test.dart", "repo_id": "io_flip", "token_count": 1813 }
879
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/connection/connection.dart'; void main() { group('ConnectionState', () { group('ConnectionInitial', () { test('uses value equality', () { expect( ConnectionInitial(), equals(ConnectionInitial()), ); }); }); group('ConnectionInProgress', () { test('uses value equality', () { expect( ConnectionInProgress(), equals(ConnectionInProgress()), ); }); }); group('ConnectionSuccess', () { test('uses value equality', () { expect( ConnectionSuccess(), equals(ConnectionSuccess()), ); }); }); group('ConnectionFailure', () { test('uses value equality', () { expect( ConnectionFailure(WebSocketErrorCode.playerAlreadyConnected), equals(ConnectionFailure(WebSocketErrorCode.playerAlreadyConnected)), ); expect( ConnectionFailure(WebSocketErrorCode.playerAlreadyConnected), isNot( equals( ConnectionFailure(WebSocketErrorCode.firebaseException), ), ), ); }); }); }); }
io_flip/test/connection/bloc/connection_state_test.dart/0
{ "file_path": "io_flip/test/connection/bloc/connection_state_test.dart", "repo_id": "io_flip", "token_count": 567 }
880
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/game/game.dart'; import '../../helpers/helpers.dart'; void main() { group('QuitGameDialog', () { Widget buildSubject({ VoidCallback? onConfirm, VoidCallback? onCancel, }) => QuitGameDialog( onConfirm: onConfirm ?? () {}, onCancel: onCancel ?? () {}, ); testWidgets('renders correct texts', (tester) async { await tester.pumpApp(buildSubject()); expect(find.text(tester.l10n.quitGameDialogTitle), findsOneWidget); expect(find.text(tester.l10n.quitGameDialogDescription), findsOneWidget); }); testWidgets( 'calls onConfirm when the continue button is tapped', (tester) async { var onConfirmCalled = false; await tester.pumpApp( buildSubject( onConfirm: () => onConfirmCalled = true, ), ); await tester.tap(find.text(tester.l10n.continueLabel)); expect(onConfirmCalled, isTrue); }, ); testWidgets( 'calls onCancel when the cancel button is tapped', (tester) async { var onCancelCalled = false; await tester.pumpApp( buildSubject( onCancel: () => onCancelCalled = true, ), ); await tester.tap(find.text(tester.l10n.cancel)); expect(onCancelCalled, isTrue); }, ); }); }
io_flip/test/game/widgets/quit_game_dialog_test.dart/0
{ "file_path": "io_flip/test/game/widgets/quit_game_dialog_test.dart", "repo_id": "io_flip", "token_count": 669 }
881
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart' as gd; import 'package:io_flip/leaderboard/leaderboard.dart'; void main() { const leaderboardPlayers = [ gd.LeaderboardPlayer( id: 'id', longestStreak: 1, initials: 'AAA', ), gd.LeaderboardPlayer( id: 'id2', longestStreak: 2, initials: 'BBB', ), ]; group('LeaderboardState', () { test('can be instantiated', () { expect( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: const [], ), isNotNull, ); }); test('has the correct initial state', () { expect( LeaderboardState.initial(), equals( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: const [], ), ), ); }); test('supports equality', () { expect( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: leaderboardPlayers, ), equals( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: leaderboardPlayers, ), ), ); expect( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: const [], ), isNot( equals( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: leaderboardPlayers, ), ), ), ); }); test('copyWith returns a new instance with the same values', () { expect( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: leaderboardPlayers, ).copyWith(), equals( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: leaderboardPlayers, ), ), ); }); test('copyWith returns a new instance', () { expect( LeaderboardState( status: LeaderboardStateStatus.initial, leaderboard: const [], ).copyWith( status: LeaderboardStateStatus.loading, leaderboard: leaderboardPlayers, ), equals( LeaderboardState( status: LeaderboardStateStatus.loading, leaderboard: leaderboardPlayers, ), ), ); }); }); }
io_flip/test/leaderboard/bloc/leaderboard_state_test.dart/0
{ "file_path": "io_flip/test/leaderboard/bloc/leaderboard_state_test.dart", "repo_id": "io_flip", "token_count": 1204 }
882
import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/prompt/bloc/prompt_form_bloc.dart'; void main() { group('PromptFormState', () { group('copyWith', () { test('does not update omitted params', () { const state = PromptFormState.initial(); expect(state.copyWith(), equals(state)); }); }); }); }
io_flip/test/prompt/bloc/prompt_form_state_test.dart/0
{ "file_path": "io_flip/test/prompt/bloc/prompt_form_state_test.dart", "repo_id": "io_flip", "token_count": 142 }
883
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/share/bloc/download_bloc.dart'; void main() { group('DownloadState', () { test('can be instantiated', () { expect( DownloadState(), isNotNull, ); }); test('has the correct initial state', () { expect( DownloadState().status, equals( DownloadStatus.idle, ), ); }); test('supports equality', () { expect( DownloadState(), equals( DownloadState(), ), ); expect( DownloadState( status: DownloadStatus.completed, ), isNot( equals( DownloadState(), ), ), ); }); test('copyWith returns a new instance', () { final state = DownloadState(); expect( state.copyWith(status: DownloadStatus.completed), equals( DownloadState( status: DownloadStatus.completed, ), ), ); }); }); }
io_flip/test/share/bloc/download_state_test.dart/0
{ "file_path": "io_flip/test/share/bloc/download_state_test.dart", "repo_id": "io_flip", "token_count": 531 }
884
module.exports = { presets: [require.resolve('@docusaurus/core/lib/babel/preset')], };
news_toolkit/docs/babel.config.js/0
{ "file_path": "news_toolkit/docs/babel.config.js", "repo_id": "news_toolkit", "token_count": 35 }
885
--- sidebar_position: 8 description: Learn how to setup continous deployments for your API. --- # API deployment setup The Flutter News Toolkit uses [Dart Frog](https://dartfrog.vgv.dev/docs/overview) to simplify the backend build by aggregating, composing, and normalizing data from multiple sources. You must deploy your Dart Frog API to serve requests to the internet. ## Google Cloud You can deploy your Dart Frog API to [Cloud Run](https://cloud.google.com/run/docs/overview/what-is-cloud-run), a managed compute platform that lets you run containers directly on top of Google's scalable infrustructure. To deploy your API to Cloud Run, check out the Dart Frog instructions at [Google Cloud Run](https://dartfrog.vgv.dev/docs/deploy/google-cloud-run) and review the details below. Also, set up a [GitHub Action Service Account](https://cloud.google.com/blog/products/identity-security/enabling-keyless-authentication-from-github-actions) to ease the process of authenticating and authorizing GitHub Actions Workflows to Google Cloud. ### Deployment Steps If you've created a development and production flavor for your application, you'll want two corresponding Google Cloud Projects where the API must be deployed: - **Development:** - project_id: example-name-dev - service_name : example-name-api-dev - **Production:** - project_id: example-name-prod - service_name : example-name-api-prod Every time a change is made inside the API, a new version must be deployed to Cloud Run for both GCP projects. To do so, follow the steps below: 1. Make sure you have the [Google Cloud SDK](https://cloud.google.com/sdk/docs/install) installed and configured. 2. Make sure you have the [Dart SDK](https://dart.dev/get-dart) and the [Dart Frog](https://pub.dev/packages/dart_frog) packages installed and configured. 3. Login into the GCP account using the `gcloud auth login` command, selecting the email account that has access to your project's GCP accounts. 4. Run the `gcloud config set project <project_id>` command to set the project to be one of the app's projects. 5. Open a terminal inside the `api` folder, and run the `dart_frog build` command. This will create a `/build` directory with all the files needed to deploy the API. 6. Run the following command to deploy the API to Cloud Run: ```bash gcloud run deploy [service_name] \ --source build \ --project=[project_id] \ --region=us-central \ --allow-unauthenticated ``` _Note: the `--allow-unauthenticated` is needed because the api can be publicly accessed._ 7. If the deploy was made to the already existing service (by using the `service_name` values provided above), the URL will be the same as the previous version. Otherwise, it must be updated as `API_BASE_URL` inside the `launch.json` file of the project. :::note You can optionally configure [API authentication](https://cloud.google.com/docs/authentication) and [user authentication for your API](https://cloud.google.com/run/docs/authenticating/end-users#cicp-firebase-auth), if desired. ::: ## Other You can also deploy your Dart Frog API to other services, like [AWS App Runner](https://dartfrog.vgv.dev/docs/deploy/aws-app-runner) or [Digital Ocean App Platform](https://dartfrog.vgv.dev/docs/deploy/digital-ocean-app-platform). ## Accessing your API By default, your app expects to receive news data from `localhost`. In order to receive data from your deployed API, you must point your app towards your new URL. :::note If you're using an android emulator, you must set `http://10.0.2.2:8080` as the `baseUrl` instead of `http://localhost:8080`. ::: Create a new `ApiClient` class that extends `FlutterNewsExampleApiClient` and set the `baseUrl` field to your new API URL. Additionally, override any `FlutterNewsExampleApiClient` methods which diverge from your API request schema, and implement them to handle the request appropriately. Finally, edit the `main_flavor.dart` file for every app flavor you want receiving data from your deployed API. Remove the assignment of `apiClient` to `FlutterNewsExampleApiClient.localhost` and assign `apiClient` to an instance of your new API client. For example: ```dart final apiClient = YourNewsApiClient( tokenProvider: tokenStorage.readToken, baseURL: 'https://yourApiBaseURL', ); ```
news_toolkit/docs/docs/project_configuration/api_deployment.md/0
{ "file_path": "news_toolkit/docs/docs/project_configuration/api_deployment.md", "repo_id": "news_toolkit", "token_count": 1196 }
886
{ "name": "flutter-news-toolkit-docs", "version": "0.0.0", "private": true, "scripts": { "docusaurus": "docusaurus", "start": "docusaurus start", "build": "docusaurus build", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", "serve": "docusaurus serve", "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "typecheck": "tsc", "format": "prettier --write .", "format:check": "prettier --check .", "lint": "eslint --cache --cache-location ./node_modules/.cache/eslint ." }, "dependencies": { "@docusaurus/core": "3.1.1", "@docusaurus/preset-classic": "3.1.1", "@mdx-js/react": "^3.0.1", "clsx": "^2.1.0", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@babel/eslint-parser": "^7.23.10", "@docusaurus/eslint-plugin": "^3.1.1", "@docusaurus/module-type-aliases": "3.1.1", "@tsconfig/docusaurus": "^2.0.2", "eslint": "^8.57.0", "prettier": "^3.2.4", "typescript": "^5.4.2" }, "browserslist": { "production": [ ">0.5%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "engines": { "node": ">=18.19.1" } }
news_toolkit/docs/package.json/0
{ "file_path": "news_toolkit/docs/package.json", "repo_id": "news_toolkit", "token_count": 685 }
887
{ // This file is not used in compilation. It is here just for a nice editor experience. "extends": "@tsconfig/docusaurus/tsconfig.json", "compilerOptions": { "baseUrl": ".", }, }
news_toolkit/docs/tsconfig.json/0
{ "file_path": "news_toolkit/docs/tsconfig.json", "repo_id": "news_toolkit", "token_count": 65 }
888
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"> <path android:pathData="M0,0h108v108h-108z" android:fillColor="#000000"/> <path android:pathData="M0,0h108v108h-108z"> <aapt:attr name="android:fillColor"> <gradient android:startY="0" android:startX="54" android:endY="108" android:endX="54" android:type="linear"> <item android:offset="0" android:color="#FF00677F"/> <item android:offset="1" android:color="#FF0F4C5C"/> </gradient> </aapt:attr> </path> </vector>
news_toolkit/flutter_news_example/android/app/src/development/res/drawable-v24/ic_launcher_background.xml/0
{ "file_path": "news_toolkit/flutter_news_example/android/app/src/development/res/drawable-v24/ic_launcher_background.xml", "repo_id": "news_toolkit", "token_count": 353 }
889
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="splash_background">#011527</color> </resources>
news_toolkit/flutter_news_example/android/app/src/main/res/values/colors.xml/0
{ "file_path": "news_toolkit/flutter_news_example/android/app/src/main/res/values/colors.xml", "repo_id": "news_toolkit", "token_count": 43 }
890
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'article.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Article _$ArticleFromJson(Map<String, dynamic> json) => Article( title: json['title'] as String, blocks: const NewsBlocksConverter().fromJson(json['blocks'] as List), totalBlocks: json['totalBlocks'] as int, url: Uri.parse(json['url'] as String), ); Map<String, dynamic> _$ArticleToJson(Article instance) => <String, dynamic>{ 'title': instance.title, 'blocks': const NewsBlocksConverter().toJson(instance.blocks), 'totalBlocks': instance.totalBlocks, 'url': instance.url.toString(), };
news_toolkit/flutter_news_example/api/lib/src/data/models/article.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/data/models/article.g.dart", "repo_id": "news_toolkit", "token_count": 247 }
891
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'article_response.g.dart'; /// {@template article_response} /// A news article response object which contains news article content. /// {@endtemplate} @JsonSerializable() class ArticleResponse extends Equatable { /// {@macro article_response} const ArticleResponse({ required this.title, required this.content, required this.totalCount, required this.url, required this.isPremium, required this.isPreview, }); /// Converts a `Map<String, dynamic>` into a [ArticleResponse] instance. factory ArticleResponse.fromJson(Map<String, dynamic> json) => _$ArticleResponseFromJson(json); /// The title of the associated article. final String title; /// The article content blocks. @NewsBlocksConverter() final List<NewsBlock> content; /// The total number of available content blocks. final int totalCount; /// The url for the associated article. final Uri url; /// Whether this article is a premium article. final bool isPremium; /// Whether the [content] of this article is a preview of the full article. final bool isPreview; /// Converts the current instance to a `Map<String, dynamic>`. Map<String, dynamic> toJson() => _$ArticleResponseToJson(this); @override List<Object> get props => [ title, content, totalCount, url, isPremium, isPreview, ]; }
news_toolkit/flutter_news_example/api/lib/src/models/article_response/article_response.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/models/article_response/article_response.dart", "repo_id": "news_toolkit", "token_count": 489 }
892
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'subscriptions_response.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SubscriptionsResponse _$SubscriptionsResponseFromJson( Map<String, dynamic> json, ) => SubscriptionsResponse( subscriptions: (json['subscriptions'] as List<dynamic>) .map((e) => Subscription.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$SubscriptionsResponseToJson( SubscriptionsResponse instance, ) => <String, dynamic>{ 'subscriptions': instance.subscriptions.map((e) => e.toJson()).toList(), };
news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.g.dart", "repo_id": "news_toolkit", "token_count": 236 }
893
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'html_block.g.dart'; /// {@template html_block} /// A block which represents HTML content. /// {@endtemplate} @JsonSerializable() class HtmlBlock with EquatableMixin implements NewsBlock { /// {@macro html_block} const HtmlBlock({ required this.content, this.type = HtmlBlock.identifier, }); /// Converts a `Map<String, dynamic>` into /// an [HtmlBlock] instance. factory HtmlBlock.fromJson(Map<String, dynamic> json) => _$HtmlBlockFromJson(json); /// The HTML block type identifier. static const identifier = '__html__'; /// The html content. final String content; @override final String type; @override Map<String, dynamic> toJson() => _$HtmlBlockToJson(this); @override List<Object> get props => [content, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/html_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/html_block.dart", "repo_id": "news_toolkit", "token_count": 310 }
894
import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'post_medium_block.g.dart'; /// {@template post_medium_block} /// A block which represents a medium post block. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=391%3A18585 /// {@endtemplate} @JsonSerializable() class PostMediumBlock extends PostBlock { /// {@macro post_medium_block} const PostMediumBlock({ 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 = PostMediumBlock.identifier, super.isPremium, super.isContentOverlaid, }); /// Converts a `Map<String, dynamic>` into a [PostMediumBlock] instance. factory PostMediumBlock.fromJson(Map<String, dynamic> json) => _$PostMediumBlockFromJson(json); /// The medium post block type identifier. static const identifier = '__post_medium__'; @override Map<String, dynamic> toJson() => _$PostMediumBlockToJson(this); }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_medium_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_medium_block.dart", "repo_id": "news_toolkit", "token_count": 392 }
895
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'text_headline_block.g.dart'; /// {@template text_headline_block} /// A block which represents a text headline. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=35%3A5014 /// {@endtemplate} @JsonSerializable() class TextHeadlineBlock with EquatableMixin implements NewsBlock { /// {@macro text_headline_block} const TextHeadlineBlock({ required this.text, this.type = TextHeadlineBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [TextHeadlineBlock] instance. factory TextHeadlineBlock.fromJson(Map<String, dynamic> json) => _$TextHeadlineBlockFromJson(json); /// The text headline block type identifier. static const identifier = '__text_headline__'; /// The text of the text headline. final String text; @override final String type; @override Map<String, dynamic> toJson() => _$TextHeadlineBlockToJson(this); @override List<Object?> get props => [type, text]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_headline_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_headline_block.dart", "repo_id": "news_toolkit", "token_count": 383 }
896
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('BannerAdBlock', () { test('can be (de)serialized', () { final block = BannerAdBlock(size: BannerAdSize.normal); expect(BannerAdBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/banner_ad_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/banner_ad_block_test.dart", "repo_id": "news_toolkit", "token_count": 135 }
897
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('SectionHeaderBlock', () { test('can be (de)serialized', () { final action = NavigateToFeedCategoryAction(category: Category.top); final block = SectionHeaderBlock(title: 'example_title', action: action); expect(SectionHeaderBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/section_header_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/section_header_block_test.dart", "repo_id": "news_toolkit", "token_count": 158 }
898
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; Future<Response> onRequest(RequestContext context, String id) async { if (context.request.method != HttpMethod.get) { return Response(statusCode: HttpStatus.methodNotAllowed); } final queryParams = context.request.url.queryParameters; final limit = int.tryParse(queryParams['limit'] ?? '') ?? 20; final offset = int.tryParse(queryParams['offset'] ?? '') ?? 0; final previewRequested = queryParams['preview'] == 'true'; final newsDataSource = context.read<NewsDataSource>(); final isPremium = await newsDataSource.isPremiumArticle(id: id); if (isPremium == null) return Response(statusCode: HttpStatus.notFound); Future<bool> shouldShowFullArticle() async { if (previewRequested) return false; if (!isPremium) return true; final requestUser = context.read<RequestUser>(); if (isPremium && requestUser.isAnonymous) return false; final user = await newsDataSource.getUser(userId: requestUser.id); if (user == null) return false; if (user.subscription == SubscriptionPlan.none) return false; return true; } final showFullArticle = await shouldShowFullArticle(); final article = await newsDataSource.getArticle( id: id, limit: limit, offset: offset, preview: !showFullArticle, ); if (article == null) return Response(statusCode: HttpStatus.notFound); final response = ArticleResponse( title: article.title, content: article.blocks, totalCount: article.totalBlocks, url: article.url, isPremium: isPremium, isPreview: !showFullArticle, ); return Response.json(body: response); }
news_toolkit/flutter_news_example/api/routes/api/v1/articles/[id]/index.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/routes/api/v1/articles/[id]/index.dart", "repo_id": "news_toolkit", "token_count": 552 }
899
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../routes/api/v1/newsletter/subscription.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('POST /api/v1/newsletter/subscription', () { test('responds with a 201.', () { final request = Request('POST', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = route.onRequest(context); expect(response.statusCode, equals(HttpStatus.created)); }); }); test('responds with 405 when method is not POST.', () { final request = Request('GET', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }
news_toolkit/flutter_news_example/api/test/routes/newsletter/subscription_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/newsletter/subscription_test.dart", "repo_id": "news_toolkit", "token_count": 358 }
900
part of 'full_screen_ads_bloc.dart'; enum FullScreenAdsStatus { initial, loadingInterstitialAd, loadingInterstitialAdFailed, loadingInterstitialAdSucceeded, showingInterstitialAd, showingInterstitialAdFailed, showingInterstitialAdSucceeded, loadingRewardedAd, loadingRewardedAdFailed, loadingRewardedAdSucceeded, showingRewardedAd, showingRewardedAdFailed, showingRewardedAdSucceeded, } class FullScreenAdsState extends Equatable { const FullScreenAdsState({ required this.status, this.interstitialAd, this.rewardedAd, this.earnedReward, }); const FullScreenAdsState.initial() : this(status: FullScreenAdsStatus.initial); final ads.InterstitialAd? interstitialAd; final ads.RewardedAd? rewardedAd; final ads.RewardItem? earnedReward; final FullScreenAdsStatus status; @override List<Object?> get props => [interstitialAd, rewardedAd, earnedReward, status]; FullScreenAdsState copyWith({ ads.InterstitialAd? interstitialAd, ads.RewardedAd? rewardedAd, ads.RewardItem? earnedReward, FullScreenAdsStatus? status, }) => FullScreenAdsState( interstitialAd: interstitialAd ?? this.interstitialAd, rewardedAd: rewardedAd ?? this.rewardedAd, earnedReward: earnedReward ?? this.earnedReward, status: status ?? this.status, ); } class FullScreenAdsConfig { const FullScreenAdsConfig({ this.interstitialAdUnitId, this.rewardedAdUnitId, }); /// The unit id of an interstitial ad. final String? interstitialAdUnitId; /// The unit id of an interstitial ad. final String? rewardedAdUnitId; /// The Android test unit id of an interstitial ad. static const androidTestInterstitialAdUnitId = 'ca-app-pub-3940256099942544/1033173712'; /// The Android test unit id of a rewarded ad. static const androidTestRewardedAdUnitId = 'ca-app-pub-3940256099942544/5224354917'; /// The iOS test unit id of an interstitial ad. static const iosTestInterstitialAdUnitId = 'ca-app-pub-3940256099942544/4411468910'; /// The iOS test unit id of a rewarded ad. static const iosTestRewardedAdUnitId = 'ca-app-pub-3940256099942544/1712485313'; }
news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_state.dart", "repo_id": "news_toolkit", "token_count": 764 }
901
import 'dart:async'; import 'package:analytics_repository/analytics_repository.dart'; import 'package:article_repository/article_repository.dart'; import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:clock/clock.dart'; import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:share_launcher/share_launcher.dart'; part 'article_event.dart'; part 'article_state.dart'; part 'article_bloc.g.dart'; class ArticleBloc extends HydratedBloc<ArticleEvent, ArticleState> { ArticleBloc({ required String articleId, required ArticleRepository articleRepository, required ShareLauncher shareLauncher, }) : _articleId = articleId, _articleRepository = articleRepository, _shareLauncher = shareLauncher, super(const ArticleState.initial()) { on<ArticleRequested>(_onArticleRequested, transformer: sequential()); on<ArticleContentSeen>(_onArticleContentSeen); on<ArticleRewardedAdWatched>(_onArticleRewardedAdWatched); on<ArticleCommented>(_onArticleCommented); on<ShareRequested>(_onShareRequested); } final String _articleId; final ShareLauncher _shareLauncher; final ArticleRepository _articleRepository; /// The number of articles the user may view without being a subscriber. static const _articleViewsLimit = 4; /// The duration after which the number of article views will be reset. static const _resetArticleViewsAfterDuration = Duration(days: 1); /// The number of related articles the user may view in the article. static const _relatedArticlesLimit = 5; /// The number of article views before an interstitial ad is shown. static const _numberOfArticleViewsForNewInterstitialAd = 4; /// HydratedBloc identifier. @override String get id => _articleId; FutureOr<void> _onArticleRequested( ArticleRequested event, Emitter<ArticleState> emit, ) async { final isInitialRequest = state.status == ArticleStatus.initial; try { emit(state.copyWith(status: ArticleStatus.loading)); final totalArticleViews = await _updateTotalArticleViews(); final showInterstitialAd = _shouldShowInterstitialAd(totalArticleViews); emit(state.copyWith(showInterstitialAd: showInterstitialAd)); if (isInitialRequest) { await _updateArticleViews(); } final hasReachedArticleViewsLimit = await _hasReachedArticleViewsLimit(); final response = await _articleRepository.getArticle( id: _articleId, offset: state.content.length, preview: hasReachedArticleViewsLimit, ); // Append fetched article content blocks to the list of content blocks. final updatedContent = [...state.content, ...response.content]; final hasMoreContent = response.totalCount > updatedContent.length; RelatedArticlesResponse? relatedArticlesResponse; if (!hasMoreContent && state.relatedArticles.isEmpty) { relatedArticlesResponse = await _articleRepository.getRelatedArticles( id: _articleId, limit: _relatedArticlesLimit, ); } emit( state.copyWith( status: ArticleStatus.populated, title: response.title, content: updatedContent, contentTotalCount: response.totalCount, relatedArticles: relatedArticlesResponse?.relatedArticles ?? [], hasMoreContent: hasMoreContent, uri: response.url, hasReachedArticleViewsLimit: hasReachedArticleViewsLimit, isPreview: response.isPreview, isPremium: response.isPremium, ), ); } catch (error, stackTrace) { emit(state.copyWith(status: ArticleStatus.failure)); addError(error, stackTrace); } } Future<void> _onArticleContentSeen( ArticleContentSeen event, Emitter<ArticleState> emit, ) async { final contentSeenCount = event.contentIndex + 1; if (contentSeenCount > state.contentSeenCount) { emit(state.copyWith(contentSeenCount: contentSeenCount)); } } FutureOr<void> _onArticleRewardedAdWatched( ArticleRewardedAdWatched event, Emitter<ArticleState> emit, ) async { try { await _articleRepository.decrementArticleViews(); final hasReachedArticleViewsLimit = await _hasReachedArticleViewsLimit(); emit( state.copyWith( hasReachedArticleViewsLimit: hasReachedArticleViewsLimit, ), ); } catch (error, stackTrace) { emit(state.copyWith(status: ArticleStatus.rewardedAdWatchedFailure)); addError(error, stackTrace); } } /// This method is not implemented as the scope of this template /// is limited to presenting a static comment section. FutureOr<void> _onArticleCommented( ArticleCommented event, Emitter<ArticleState> emit, ) => Future.value(); FutureOr<void> _onShareRequested( ShareRequested event, Emitter<ArticleState> emit, ) async { try { await _shareLauncher.share(text: event.uri.toString()); } catch (error, stackTrace) { emit(state.copyWith(status: ArticleStatus.shareFailure)); addError(error, stackTrace); } } /// Resets the number of article views if the counter was never reset or if /// the counter was reset more than [_resetArticleViewsAfterDuration] ago. /// /// After, increments the total number of article views by 1 if the counter /// is less than or equal to [_articleViewsLimit]. Future<void> _updateArticleViews() async { final currentArticleViews = await _articleRepository.fetchArticleViews(); final resetAt = currentArticleViews.resetAt; final now = clock.now(); final shouldResetArticleViews = resetAt == null || now.isAfter(resetAt.add(_resetArticleViewsAfterDuration)); if (shouldResetArticleViews) { await _articleRepository.resetArticleViews(); await _articleRepository.incrementArticleViews(); } else if (currentArticleViews.views < _articleViewsLimit) { await _articleRepository.incrementArticleViews(); } } /// Increments the number of total article views and returns the count. Future<int> _updateTotalArticleViews() async { await _articleRepository.incrementTotalArticleViews(); return _articleRepository.fetchTotalArticleViews(); } // Show interstitial every `_numberOfArticleViewsForNewInterstitialAd` // article opens bool _shouldShowInterstitialAd(int totalArticleViews) => (totalArticleViews != 0) && totalArticleViews % _numberOfArticleViewsForNewInterstitialAd == 0; /// Returns whether the user has reached the limit of article views. Future<bool> _hasReachedArticleViewsLimit() async { final currentArticleViews = await _articleRepository.fetchArticleViews(); return currentArticleViews.views >= _articleViewsLimit; } @override ArticleState? fromJson(Map<String, dynamic> json) => ArticleState.fromJson(json); @override Map<String, dynamic>? toJson(ArticleState state) => state.toJson(); }
news_toolkit/flutter_news_example/lib/article/bloc/article_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/article/bloc/article_bloc.dart", "repo_id": "news_toolkit", "token_count": 2432 }
902
part of 'categories_bloc.dart'; enum CategoriesStatus { initial, loading, populated, failure, } @JsonSerializable() class CategoriesState extends Equatable { const CategoriesState({ required this.status, this.categories, this.selectedCategory, }); const CategoriesState.initial() : this( status: CategoriesStatus.initial, ); factory CategoriesState.fromJson(Map<String, dynamic> json) => _$CategoriesStateFromJson(json); final CategoriesStatus status; final List<Category>? categories; final Category? selectedCategory; @override List<Object?> get props => [ status, categories, selectedCategory, ]; CategoriesState copyWith({ CategoriesStatus? status, List<Category>? categories, Category? selectedCategory, }) { return CategoriesState( status: status ?? this.status, categories: categories ?? this.categories, selectedCategory: selectedCategory ?? this.selectedCategory, ); } Map<String, dynamic> toJson() => _$CategoriesStateToJson(this); }
news_toolkit/flutter_news_example/lib/categories/bloc/categories_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/categories/bloc/categories_state.dart", "repo_id": "news_toolkit", "token_count": 375 }
903
part of 'home_cubit.dart'; enum HomeState { topStories(0), search(1), subscribe(2); const HomeState(this.tabIndex); final int tabIndex; }
news_toolkit/flutter_news_example/lib/home/cubit/home_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/home/cubit/home_state.dart", "repo_id": "news_toolkit", "token_count": 59 }
904
export 'login_modal.dart'; export 'login_with_email_page.dart';
news_toolkit/flutter_news_example/lib/login/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/view/view.dart", "repo_id": "news_toolkit", "token_count": 25 }
905
export 'bottom_nav_bar.dart'; export 'nav_drawer.dart';
news_toolkit/flutter_news_example/lib/navigation/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/navigation/view/view.dart", "repo_id": "news_toolkit", "token_count": 23 }
906
export 'notification_preferences_page.dart';
news_toolkit/flutter_news_example/lib/notification_preferences/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/view/view.dart", "repo_id": "news_toolkit", "token_count": 15 }
907
import 'package:app_ui/app_ui.dart' hide Assets; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/search/search.dart'; import 'package:news_repository/news_repository.dart'; class SearchPage extends StatelessWidget { const SearchPage({super.key}); @override Widget build(BuildContext context) { return BlocProvider<SearchBloc>( create: (context) => SearchBloc( newsRepository: context.read<NewsRepository>(), )..add(const SearchTermChanged()), child: const SearchView(), ); } } class SearchView extends StatefulWidget { const SearchView({super.key}); @override State<SearchView> createState() => _SearchViewState(); } class _SearchViewState extends State<SearchView> { final TextEditingController _controller = TextEditingController(); @override void initState() { super.initState(); _controller.addListener( () => context .read<SearchBloc>() .add(SearchTermChanged(searchTerm: _controller.text)), ); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final l10n = context.l10n; return BlocConsumer<SearchBloc, SearchState>( listener: (context, state) { if (state.status == SearchStatus.failure) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar(content: Text(context.l10n.searchErrorMessage)), ); } }, builder: (context, state) { return CustomScrollView( slivers: [ SliverList( delegate: SliverChildListDelegate( [ SearchTextField( key: const Key('searchPage_searchTextField'), controller: _controller, ), SearchHeadlineText( headerText: state.searchType == SearchType.popular ? l10n.searchPopularSearches : l10n.searchRelevantTopics, ), Padding( padding: const EdgeInsets.fromLTRB( AppSpacing.lg, 0, AppSpacing.lg, AppSpacing.lg, ), child: Wrap( spacing: AppSpacing.sm, children: state.topics .map<Widget>( (topic) => SearchFilterChip( key: Key('searchFilterChip_$topic'), chipText: topic, onSelected: (text) => _controller.text = text, ), ) .toList(), ), ), SearchHeadlineText( headerText: state.searchType == SearchType.popular ? l10n.searchPopularArticles : l10n.searchRelevantArticles, ), ], ), ), ...state.articles.map<Widget>( (newsBlock) => CategoryFeedItem(block: newsBlock), ) ], ); }, ); } }
news_toolkit/flutter_news_example/lib/search/view/search_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/view/search_page.dart", "repo_id": "news_toolkit", "token_count": 1859 }
908
export 'dialog/dialog.dart'; export 'view/view.dart'; export 'widgets/widgets.dart';
news_toolkit/flutter_news_example/lib/subscriptions/subscriptions.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/subscriptions.dart", "repo_id": "news_toolkit", "token_count": 34 }
909
export 'bloc/theme_mode_bloc.dart'; export 'view/theme_selector.dart';
news_toolkit/flutter_news_example/lib/theme_selector/theme_selector.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/theme_selector/theme_selector.dart", "repo_id": "news_toolkit", "token_count": 29 }
910
name: ads_consent_client description: A client that handles requesting ads consent on a device. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: flutter: sdk: flutter google_mobile_ads: ^4.0.0 dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/ads_consent_client/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/ads_consent_client/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 145 }
911
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.75 5.25L11.6925 6.3075L13.6275 8.25H6V9.75H13.6275L11.6925 11.685L12.75 12.75L16.5 9L12.75 5.25ZM3 3.75H9V2.25H3C2.175 2.25 1.5 2.925 1.5 3.75V14.25C1.5 15.075 2.175 15.75 3 15.75H9V14.25H3V3.75Z" fill="white"/> </svg>
news_toolkit/flutter_news_example/packages/app_ui/assets/icons/log_out_icon.svg/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/assets/icons/log_out_icon.svg", "repo_id": "news_toolkit", "token_count": 185 }
912
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
news_toolkit/flutter_news_example/packages/app_ui/gallery/android/gradle.properties/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/android/gradle.properties", "repo_id": "news_toolkit", "token_count": 31 }
913
export 'typography_page.dart';
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/typography/typography.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/typography/typography.dart", "repo_id": "news_toolkit", "token_count": 11 }
914
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template app_button} /// Button with text displayed in the application. /// {@endtemplate} class AppButton extends StatelessWidget { /// {@macro app_button} const AppButton._({ required this.child, this.onPressed, Color? buttonColor, Color? disabledButtonColor, Color? foregroundColor, Color? disabledForegroundColor, BorderSide? borderSide, double? elevation, TextStyle? textStyle, Size? maximumSize, Size? minimumSize, EdgeInsets? padding, super.key, }) : _buttonColor = buttonColor ?? Colors.white, _disabledButtonColor = disabledButtonColor ?? AppColors.disabledButton, _borderSide = borderSide, _foregroundColor = foregroundColor ?? AppColors.black, _disabledForegroundColor = disabledForegroundColor ?? AppColors.disabledForeground, _elevation = elevation ?? 0, _textStyle = textStyle, _maximumSize = maximumSize ?? _defaultMaximumSize, _minimumSize = minimumSize ?? _defaultMinimumSize, _padding = padding ?? _defaultPadding; /// Filled black button. const AppButton.black({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.black, child: child, foregroundColor: AppColors.white, elevation: elevation, textStyle: textStyle, ); /// Filled blue dress button. const AppButton.blueDress({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.blueDress, child: child, foregroundColor: AppColors.white, elevation: elevation, textStyle: textStyle, ); /// Filled crystal blue button. const AppButton.crystalBlue({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.crystalBlue, child: child, foregroundColor: AppColors.white, elevation: elevation, textStyle: textStyle, ); /// Filled red wine button. const AppButton.redWine({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.redWine, child: child, foregroundColor: AppColors.white, elevation: elevation, textStyle: textStyle, ); /// Filled secondary button. const AppButton.secondary({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, Color? disabledButtonColor, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.secondary, child: child, foregroundColor: AppColors.white, disabledButtonColor: disabledButtonColor ?? AppColors.disabledSurface, elevation: elevation, textStyle: textStyle, padding: _smallPadding, maximumSize: _smallMaximumSize, minimumSize: _smallMinimumSize, ); /// Filled dark aqua button. const AppButton.darkAqua({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.darkAqua, child: child, foregroundColor: AppColors.white, elevation: elevation, textStyle: textStyle, ); /// Outlined white button. const AppButton.outlinedWhite({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, child: child, buttonColor: AppColors.white, borderSide: const BorderSide( color: AppColors.pastelGrey, ), elevation: elevation, foregroundColor: AppColors.lightBlack, textStyle: textStyle, ); /// Outlined transparent dark aqua button. const AppButton.outlinedTransparentDarkAqua({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, child: child, buttonColor: AppColors.transparent, borderSide: const BorderSide( color: AppColors.paleSky, ), elevation: elevation, foregroundColor: AppColors.darkAqua, textStyle: textStyle, ); /// Outlined transparent white button. const AppButton.outlinedTransparentWhite({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, child: child, buttonColor: AppColors.transparent, borderSide: const BorderSide( color: AppColors.white, ), elevation: elevation, foregroundColor: AppColors.white, textStyle: textStyle, ); /// Filled transparent dark aqua button. const AppButton.transparentDarkAqua({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, child: child, buttonColor: AppColors.transparent, elevation: elevation, foregroundColor: AppColors.darkAqua, textStyle: textStyle, ); /// Filled transparent white button. const AppButton.transparentWhite({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, TextStyle? textStyle, }) : this._( key: key, onPressed: onPressed, child: child, disabledButtonColor: AppColors.transparent, buttonColor: AppColors.transparent, elevation: elevation, foregroundColor: AppColors.white, disabledForegroundColor: AppColors.white, textStyle: textStyle, ); /// Filled small red wine blue button. const AppButton.smallRedWine({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.redWine, child: child, foregroundColor: AppColors.white, elevation: elevation, maximumSize: _smallMaximumSize, minimumSize: _smallMinimumSize, padding: _smallPadding, ); /// Filled small transparent button. const AppButton.smallDarkAqua({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.darkAqua, child: child, foregroundColor: AppColors.white, elevation: elevation, maximumSize: _smallMaximumSize, minimumSize: _smallMinimumSize, padding: _smallPadding, ); /// Filled small transparent button. const AppButton.smallTransparent({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.transparent, child: child, foregroundColor: AppColors.darkAqua, elevation: elevation, maximumSize: _smallMaximumSize, minimumSize: _smallMinimumSize, padding: _smallPadding, ); /// Filled small transparent button. const AppButton.smallOutlineTransparent({ required Widget child, Key? key, VoidCallback? onPressed, double? elevation, }) : this._( key: key, onPressed: onPressed, buttonColor: AppColors.transparent, child: child, borderSide: const BorderSide( color: AppColors.paleSky, ), foregroundColor: AppColors.darkAqua, elevation: elevation, maximumSize: _smallMaximumSize, minimumSize: _smallMinimumSize, padding: _smallPadding, ); /// The maximum size of the small variant of the button. static const _smallMaximumSize = Size(double.infinity, 40); /// The minimum size of the small variant of the button. static const _smallMinimumSize = Size(0, 40); /// The maximum size of the button. static const _defaultMaximumSize = Size(double.infinity, 56); /// The minimum size of the button. static const _defaultMinimumSize = Size(double.infinity, 56); /// The padding of the small variant of the button. static const _smallPadding = EdgeInsets.symmetric(horizontal: AppSpacing.xlg); /// The padding of the the button. static const _defaultPadding = EdgeInsets.symmetric(vertical: AppSpacing.lg); /// [VoidCallback] called when button is pressed. /// Button is disabled when null. final VoidCallback? onPressed; /// A background color of the button. /// /// Defaults to [Colors.white]. final Color _buttonColor; /// A disabled background color of the button. /// /// Defaults to [AppColors.disabledButton]. final Color? _disabledButtonColor; /// Color of the text, icons etc. /// /// Defaults to [AppColors.black]. final Color _foregroundColor; /// Color of the disabled text, icons etc. /// /// Defaults to [AppColors.disabledForeground]. final Color _disabledForegroundColor; /// A border of the button. final BorderSide? _borderSide; /// Elevation of the button. final double _elevation; /// [TextStyle] of the button text. /// /// Defaults to [TextTheme.labelLarge]. final TextStyle? _textStyle; /// The maximum size of the button. /// /// Defaults to [_defaultMaximumSize]. final Size _maximumSize; /// The minimum size of the button. /// /// Defaults to [_defaultMinimumSize]. final Size _minimumSize; /// The padding of the button. /// /// Defaults to [EdgeInsets.zero]. final EdgeInsets _padding; /// [Widget] displayed on the button. final Widget child; @override Widget build(BuildContext context) { final textStyle = _textStyle ?? Theme.of(context).textTheme.labelLarge; return ElevatedButton( onPressed: onPressed, style: ButtonStyle( maximumSize: MaterialStateProperty.all(_maximumSize), padding: MaterialStateProperty.all(_padding), minimumSize: MaterialStateProperty.all(_minimumSize), textStyle: MaterialStateProperty.all(textStyle), backgroundColor: onPressed == null ? MaterialStateProperty.all(_disabledButtonColor) : MaterialStateProperty.all(_buttonColor), elevation: MaterialStateProperty.all(_elevation), foregroundColor: onPressed == null ? MaterialStateProperty.all(_disabledForegroundColor) : MaterialStateProperty.all(_foregroundColor), side: MaterialStateProperty.all(_borderSide), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(100), ), ), ), child: child, ); } }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_button.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_button.dart", "repo_id": "news_toolkit", "token_count": 4799 }
915
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('AppLogo', () { testWidgets('renders Image for AppLogo.dark', (tester) async { await tester.pumpApp(AppLogo.dark()); expect( find.byWidgetPredicate( (widget) => widget is Image && widget.width == 172, ), findsOneWidget, ); }); testWidgets('renders Image for AppLogo.light', (tester) async { await tester.pumpApp(AppLogo.light()); expect( find.byWidgetPredicate( (widget) => widget is Image && widget.width == 172, ), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_logo_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_logo_test.dart", "repo_id": "news_toolkit", "token_count": 332 }
916
# Authentication Client [![style: very good analysis](https://img.shields.io/badge/style-very_good_analysis-B22C89.svg)](https://pub.dev/packages/very_good_analysis) A Generic Authentication Client Interface.
news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/README.md", "repo_id": "news_toolkit", "token_count": 66 }
917
import 'package:android_intent_plus/android_intent.dart'; import 'package:flutter/foundation.dart'; import 'package:url_launcher/url_launcher.dart'; /// {@template email_launcher_exception} /// Exceptions from the email launcher. /// {@endtemplate} abstract class EmailLauncherException implements Exception { /// {@macro email_launcher_exception} const EmailLauncherException(this.error); /// The error which was caught. final Object error; } /// {@template launch_email_app_failure} /// Thrown during the launching email app process if a failure occurs. /// {@endtemplate} class LaunchEmailAppFailure extends EmailLauncherException { /// {@macro launch_email_app_failure} const LaunchEmailAppFailure(super.error); } /// Provider to inject `launchUrl`. typedef LaunchUrlProvider = Future<bool> Function(Uri url); /// Provider to inject `canLaunchUrl`. typedef CanLaunchUrlProvider = Future<bool> Function(Uri url); /// {@template email_launcher} /// Class which manages the email launcher logic. /// {@endtemplate} class EmailLauncher { /// {@macro email_launcher} EmailLauncher({ LaunchUrlProvider? launchUrlProvider, CanLaunchUrlProvider? canLaunchProvider, }) : _launchUrlProvider = launchUrlProvider ?? launchUrl, _canLaunchUrlProvider = canLaunchProvider ?? canLaunchUrl; final LaunchUrlProvider _launchUrlProvider; final CanLaunchUrlProvider _canLaunchUrlProvider; /// Launches a default email app on `Android` and `iOS`. Future<void> launchEmailApp() async { try { if (defaultTargetPlatform == TargetPlatform.android) { const intent = AndroidIntent( action: 'android.intent.action.MAIN', category: 'android.intent.category.APP_EMAIL', ); await intent.launch(); } else if (defaultTargetPlatform == TargetPlatform.iOS) { final url = Uri(scheme: 'message'); if (await _canLaunchUrlProvider(url)) { await _launchUrlProvider(url); } } } catch (error, stackTrace) { Error.throwWithStackTrace(LaunchEmailAppFailure(error), stackTrace); } } }
news_toolkit/flutter_news_example/packages/email_launcher/lib/src/email_launcher.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/email_launcher/lib/src/email_launcher.dart", "repo_id": "news_toolkit", "token_count": 690 }
918
import 'dart:async'; import 'package:authentication_client/authentication_client.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_news_example_api/client.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; /// {@template in_app_purchase_failure} /// A base failure class for the in-app purchase repository failures. /// {@endtemplate} abstract class InAppPurchaseFailure with EquatableMixin implements Exception { /// {@macro in_app_purchase_failure} const InAppPurchaseFailure(this.error); /// The error which was caught. final Object error; @override List<Object> get props => [error]; } /// {@template deliver_in_app_purchase_failure} /// An exception thrown when delivering a purchase from the purchaseStream /// fails. /// {@endtemplate} class DeliverInAppPurchaseFailure extends InAppPurchaseFailure { /// {@macro deliver_in_app_purchase_failure} const DeliverInAppPurchaseFailure(super.error); } /// {@template complete_in_app_purchase_failure} /// An exception thrown when completing a purchase from the purchaseStream /// fails. /// {@endtemplate} class CompleteInAppPurchaseFailure extends InAppPurchaseFailure { /// {@macro complete_in_app_purchase_failure} const CompleteInAppPurchaseFailure(super.error); } /// {@template internal_in_app_purchase_failure} /// An exception thrown when emitted purchase from the purchaseStream /// has status [PurchaseStatus.error]. /// {@endtemplate} class InternalInAppPurchaseFailure extends InAppPurchaseFailure { /// {@macro internal_in_app_purchase_failure} const InternalInAppPurchaseFailure(super.error); } /// {@template fetch_subscriptions_failure} /// An exception thrown when fetching subscriptions fails. /// {@endtemplate} class FetchSubscriptionsFailure extends InAppPurchaseFailure { /// {@macro fetch_subscriptions_failure} const FetchSubscriptionsFailure(super.error); } /// {@template query_in_app_product_details_failure} /// An exception thrown when querying in app product details fails. /// {@endtemplate} class QueryInAppProductDetailsFailure extends InAppPurchaseFailure { /// {@macro query_in_app_product_details_failure} const QueryInAppProductDetailsFailure(super.error); } /// {@template in_app_purchase_buy_non_consumable_failure} /// An exception thrown when buyNonConsumable returns false. /// {@endtemplate} class InAppPurchaseBuyNonConsumableFailure extends InAppPurchaseFailure { /// {@macro in_app_purchase_buy_non_consumable_failure} const InAppPurchaseBuyNonConsumableFailure(super.error); } /// {@template in_app_purchase_repository} /// The `InAppPurchaseRepository` uses [in_app_purchase](https://pub.dev/packages/in_app_purchase) /// package to conduct native in-app purchase. /// /// Here is a quick explanation of how the purchase flow looks like: /// 1. The app displays a list of available (subscriptions) that are fetched /// using the [fetchSubscriptions] method. /// /// 2. Once the user selects one of the products, the [purchase] method is /// called. This method does not update us about the entire purchase /// process. However, the purchase updates are available through the /// [purchaseStream](https://pub.dev/documentation/in_app_purchase/latest/in_app_purchase/InAppPurchase/purchaseStream.html). /// /// 3. Once a user successfully finishes the transaction, a [PurchaseDetails](https://pub.dev/documentation/in_app_purchase_platform_interface/latest/in_app_purchase_platform_interface/PurchaseDetails-class.html) /// object is pushed to the `purchaseStream`. It will have a [pendingCompletePurchase](https://pub.dev/documentation/in_app_purchase_platform_interface/latest/in_app_purchase_platform_interface/PurchaseDetails/pendingCompletePurchase.html) /// flag set to true, which means that we need to deliver the content of the /// product to the user and mark the purchase as completed using [completePurchase](https://pub.dev/documentation/in_app_purchase_platform_interface/latest/in_app_purchase_platform_interface/InAppPurchasePlatform/completePurchase.html) /// method. class InAppPurchaseRepository { /// {@macro in_app_purchase_repository} InAppPurchaseRepository({ required AuthenticationClient authenticationClient, required FlutterNewsExampleApiClient apiClient, required InAppPurchase inAppPurchase, }) : _apiClient = apiClient, _authenticationClient = authenticationClient, _inAppPurchase = inAppPurchase { _inAppPurchase.purchaseStream .expand((value) => value) .listen(_onPurchaseUpdated); } final InAppPurchase _inAppPurchase; final FlutterNewsExampleApiClient _apiClient; final AuthenticationClient _authenticationClient; final _purchaseUpdateStreamController = StreamController<PurchaseUpdate>.broadcast(); /// A stream of purchase updates. /// /// List of possible updates: /// * [PurchaseCanceled] /// * [PurchaseDelivered] /// * [PurchaseCompleted] /// * [PurchaseFailed] Stream<PurchaseUpdate> get purchaseUpdate => _purchaseUpdateStreamController.stream.asBroadcastStream(); List<Subscription>? _cachedSubscriptions; /// Fetches and caches list of subscriptions from the server. Future<List<Subscription>> fetchSubscriptions() async { try { if (_cachedSubscriptions != null) { return _cachedSubscriptions!; } final response = await _apiClient.getSubscriptions(); _cachedSubscriptions = response.subscriptions; return _cachedSubscriptions ?? []; } catch (error, stackTrace) { Error.throwWithStackTrace( FetchSubscriptionsFailure(error), stackTrace, ); } } /// Allows the user to purchase given [subscription]. /// /// When the payment is successfully completed, the app informs /// the server about the purchased subscription. The server then verifies /// if the purchase was correct and updates user's subscription. Future<void> purchase({ required Subscription subscription, }) async { final productDetailsResponse = await _inAppPurchase.queryProductDetails({subscription.id}); if (productDetailsResponse.error != null) { Error.throwWithStackTrace( QueryInAppProductDetailsFailure( productDetailsResponse.error.toString(), ), StackTrace.current, ); } if (productDetailsResponse.productDetails.isEmpty) { Error.throwWithStackTrace( QueryInAppProductDetailsFailure( 'No subscription found with id ${subscription.id}.', ), StackTrace.current, ); } if (productDetailsResponse.productDetails.length > 1) { Error.throwWithStackTrace( QueryInAppProductDetailsFailure( 'Found ${productDetailsResponse.productDetails.length} products ' 'with id ${subscription.id}. Only one should be found.', ), StackTrace.current, ); } final productDetails = productDetailsResponse.productDetails.first; final user = await _authenticationClient.user.first; final purchaseParam = PurchaseParam( productDetails: productDetails, applicationUserName: user.id, ); final isPurchaseRequestSuccessful = await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam); if (!isPurchaseRequestSuccessful) { Error.throwWithStackTrace( InAppPurchaseBuyNonConsumableFailure( 'Failed to buy ${productDetails.id} for user ${user.id}', ), StackTrace.current, ); } } /// If user is authenticated, then the `restorePurchases` can be called /// in order to restore all the previous purchases. /// /// Restored purchases are delivered through the purchaseStream /// with a status of [PurchaseStatus.restored]. Future<void> restorePurchases() async { final user = await _authenticationClient.user.first; if (!user.isAnonymous) { await _inAppPurchase.restorePurchases(applicationUserName: user.id); } } Future<void> _onPurchaseUpdated(PurchaseDetails purchase) async { /// On iOS, the canceled status is never reported. /// When the native payment dialog is closed, the error status is reported. if (purchase.status == PurchaseStatus.canceled) { _purchaseUpdateStreamController.add(const PurchaseCanceled()); } if (purchase.status == PurchaseStatus.error) { _purchaseUpdateStreamController.add( PurchaseFailed( failure: InternalInAppPurchaseFailure( purchase.error.toString(), ), ), ); } try { if (purchase.status == PurchaseStatus.purchased || purchase.status == PurchaseStatus.restored) { final purchasedProduct = (await fetchSubscriptions()) .firstWhere((product) => product.id == purchase.productID); _purchaseUpdateStreamController.add( PurchasePurchased(subscription: purchasedProduct), ); await _apiClient.createSubscription( subscriptionId: purchasedProduct.id, ); _purchaseUpdateStreamController.add( PurchaseDelivered(subscription: purchasedProduct), ); } } catch (error, stackTrace) { _purchaseUpdateStreamController.addError( PurchaseFailed( failure: DeliverInAppPurchaseFailure( error, ), ), stackTrace, ); } try { if (purchase.pendingCompletePurchase) { final purchasedSubscription = (await fetchSubscriptions()).firstWhere( (subscription) => subscription.id == purchase.productID, ); await _inAppPurchase.completePurchase(purchase); _purchaseUpdateStreamController.add( PurchaseCompleted( subscription: purchasedSubscription, ), ); } } catch (error, stackTrace) { _purchaseUpdateStreamController.addError( PurchaseFailed( failure: CompleteInAppPurchaseFailure( error, ), ), stackTrace, ); } } } /// {@template purchase_update} /// A base class that represents a purchase update. /// {@endtemplate} abstract class PurchaseUpdate extends Equatable { /// {@macro purchase_update} const PurchaseUpdate(); } /// {@template purchase_delivered} /// An update representing a delivered purchase. /// {@endtemplate} class PurchaseDelivered extends PurchaseUpdate { /// {@macro purchase_delivered} const PurchaseDelivered({ required this.subscription, }) : super(); /// A subscription associated with a purchase that was delivered. final Subscription subscription; @override List<Object> get props => [subscription]; } /// {@template purchase_completed} /// An update representing a completed purchase. /// {@endtemplate} class PurchaseCompleted extends PurchaseUpdate { /// {@macro purchase_completed} const PurchaseCompleted({ required this.subscription, }) : super(); /// A subscription that was successfully purchased. final Subscription subscription; @override List<Object> get props => [subscription]; } /// {@template purchase_purchased} /// An update representing a purchased purchase that has not been delivered yet. /// {@endtemplate} class PurchasePurchased extends PurchaseUpdate { /// {@macro purchase_purchased} const PurchasePurchased({ required this.subscription, }) : super(); /// A subscription that was successfully purchased. final Subscription subscription; @override List<Object> get props => [subscription]; } /// {@template purchase_canceled} /// An update representing canceled purchase. /// {@endtemplate} class PurchaseCanceled extends PurchaseUpdate { /// {@macro purchase_canceled} const PurchaseCanceled() : super(); @override List<Object> get props => []; } /// {@template purchase_failed} /// An update representing failed purchase. /// {@endtemplate} class PurchaseFailed extends PurchaseUpdate { /// {@macro purchase_failed} const PurchaseFailed({ required this.failure, }) : super(); /// A failure which occurred when purchasing a subscription. final InAppPurchaseFailure failure; @override List<Object> get props => []; }
news_toolkit/flutter_news_example/packages/in_app_purchase_repository/lib/src/in_app_purchase_repository.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/in_app_purchase_repository/lib/src/in_app_purchase_repository.dart", "repo_id": "news_toolkit", "token_count": 3969 }
919
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // coverage:ignore-file // ignore_for_file: type=lint // ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use import 'package:flutter/widgets.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter/services.dart'; class $AssetsIconsGen { const $AssetsIconsGen(); /// File path: assets/icons/arrow_left_disable.svg SvgGenImage get arrowLeftDisable => const SvgGenImage('assets/icons/arrow_left_disable.svg'); /// File path: assets/icons/arrow_left_enable.svg SvgGenImage get arrowLeftEnable => const SvgGenImage('assets/icons/arrow_left_enable.svg'); /// File path: assets/icons/arrow_right_disable.svg SvgGenImage get arrowRightDisable => const SvgGenImage('assets/icons/arrow_right_disable.svg'); /// File path: assets/icons/arrow_right_enable.svg SvgGenImage get arrowRightEnable => const SvgGenImage('assets/icons/arrow_right_enable.svg'); /// File path: assets/icons/play_icon.svg SvgGenImage get playIcon => const SvgGenImage('assets/icons/play_icon.svg'); /// List of all assets List<SvgGenImage> get values => [ arrowLeftDisable, arrowLeftEnable, arrowRightDisable, arrowRightEnable, playIcon ]; } class Assets { Assets._(); static const $AssetsIconsGen icons = $AssetsIconsGen(); } class AssetGenImage { const AssetGenImage(this._assetName); final String _assetName; Image image({ Key? key, AssetBundle? bundle, ImageFrameBuilder? frameBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? scale, double? width, double? height, Color? color, Animation<double>? opacity, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, String? package = 'news_blocks_ui', FilterQuality filterQuality = FilterQuality.low, int? cacheWidth, int? cacheHeight, }) { return Image.asset( _assetName, key: key, bundle: bundle, frameBuilder: frameBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, scale: scale, width: width, height: height, color: color, opacity: opacity, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, package: package, filterQuality: filterQuality, cacheWidth: cacheWidth, cacheHeight: cacheHeight, ); } ImageProvider provider({ AssetBundle? bundle, String? package = 'news_blocks_ui', }) { return AssetImage( _assetName, bundle: bundle, package: package, ); } String get path => _assetName; String get keyName => 'packages/news_blocks_ui/$_assetName'; } class SvgGenImage { const SvgGenImage(this._assetName); final String _assetName; SvgPicture svg({ Key? key, bool matchTextDirection = false, AssetBundle? bundle, String? package = 'news_blocks_ui', double? width, double? height, BoxFit fit = BoxFit.contain, AlignmentGeometry alignment = Alignment.center, bool allowDrawingOutsideViewBox = false, WidgetBuilder? placeholderBuilder, String? semanticsLabel, bool excludeFromSemantics = false, SvgTheme theme = const SvgTheme(), ColorFilter? colorFilter, Clip clipBehavior = Clip.hardEdge, @deprecated Color? color, @deprecated BlendMode colorBlendMode = BlendMode.srcIn, @deprecated bool cacheColorFilter = false, }) { return SvgPicture.asset( _assetName, key: key, matchTextDirection: matchTextDirection, bundle: bundle, package: package, width: width, height: height, fit: fit, alignment: alignment, allowDrawingOutsideViewBox: allowDrawingOutsideViewBox, placeholderBuilder: placeholderBuilder, semanticsLabel: semanticsLabel, excludeFromSemantics: excludeFromSemantics, theme: theme, colorFilter: colorFilter, color: color, colorBlendMode: colorBlendMode, clipBehavior: clipBehavior, cacheColorFilter: cacheColorFilter, ); } String get path => _assetName; String get keyName => 'packages/news_blocks_ui/$_assetName'; }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/generated/assets.gen.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/generated/assets.gen.dart", "repo_id": "news_toolkit", "token_count": 1783 }
920
import 'package:app_ui/app_ui.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template post_small} /// A reusable post small news block widget. /// {@endtemplate} class PostSmall extends StatelessWidget { /// {@macro post_small} const PostSmall({required this.block, this.onPressed, super.key}); /// The size of this post image. static const _imageSize = 80.0; /// The associated [PostSmallBlock] instance. final PostSmallBlock block; /// An optional callback which is invoked when the action is triggered. /// A [Uri] from the associated [BlockAction] is provided to the callback. final BlockActionCallback? onPressed; @override Widget build(BuildContext context) { final imageUrl = block.imageUrl; return GestureDetector( onTap: () { if (block.hasNavigationAction) onPressed?.call(block.action!); }, child: Padding( padding: const EdgeInsets.all(AppSpacing.lg), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (imageUrl != null) Padding( padding: const EdgeInsets.only(right: AppSpacing.lg), child: CachedNetworkImage( imageUrl: imageUrl, width: _imageSize, height: _imageSize, fit: BoxFit.cover, ), ), Flexible( child: PostSmallContent( title: block.title, publishedAt: block.publishedAt, ), ), ], ), ), ); } } /// {@template post_small_content} /// The content of [PostSmall]. /// {@endtemplate} @visibleForTesting class PostSmallContent extends StatelessWidget { /// {@macro post_small_content} const PostSmallContent({ required this.title, required this.publishedAt, super.key, }); /// The title of this post. final String title; /// The date when this post was published. final DateTime publishedAt; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Column( children: [ Text( title, style: textTheme.titleLarge?.copyWith( color: AppColors.highEmphasisSurface, ), ), const SizedBox(height: AppSpacing.xs), PostFooter( publishedAt: publishedAt, ), ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_small.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_small.dart", "repo_id": "news_toolkit", "token_count": 1143 }
921
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/widgets.dart'; /// {@template inline_image} /// A reusable image widget displayed inline with the content. /// {@endtemplate} class InlineImage extends StatelessWidget { /// {@macro inline_image} const InlineImage({ required this.imageUrl, this.progressIndicatorBuilder, super.key, }); /// The aspect ratio of this image. static const _aspectRatio = 3 / 2; /// The url of this image. final String imageUrl; /// Widget displayed while the target [imageUrl] is loading. final ProgressIndicatorBuilder? progressIndicatorBuilder; @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: _aspectRatio, child: CachedNetworkImage( imageUrl: imageUrl, progressIndicatorBuilder: progressIndicatorBuilder, height: double.infinity, width: double.infinity, fit: BoxFit.cover, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/inline_image.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/inline_image.dart", "repo_id": "news_toolkit", "token_count": 343 }
922
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; extension AppTester on WidgetTester { Future<void> pumpApp( Widget widgetUnderTest, { ThemeData? theme, }) async { await pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: widgetUnderTest, ), ), ); await pump(); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/pump_app.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/pump_app.dart", "repo_id": "news_toolkit", "token_count": 170 }
923
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart' show ColoredBox, Colors; 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('Spacer', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly for extraSmall spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.extraSmall), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_extra_small.png'), ); }); testWidgets('renders correctly for small spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.small), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_small.png'), ); }); testWidgets('renders correctly for medium spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.medium), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_medium.png'), ); }); testWidgets('renders correctly for large spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.large), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_large.png'), ); }); testWidgets('renders correctly for veryLarge spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.veryLarge), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_very_large.png'), ); }); testWidgets('renders correctly for extraLarge spacing', (tester) async { final widget = ColoredBox( color: Colors.black, child: Spacer( block: SpacerBlock(spacing: Spacing.extraLarge), ), ); await tester.pumpApp(widget); await expectLater( find.byType(Spacer), matchesGoldenFile('spacing_extra_large.png'), ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/spacer_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/spacer_test.dart", "repo_id": "news_toolkit", "token_count": 1201 }
924
// 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('TextHeadline', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly', (tester) async { final widget = Center( child: TextHeadline( block: TextHeadlineBlock(text: 'Title text'), ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextHeadline), matchesGoldenFile('text_headline.png'), ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_headline_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_headline_test.dart", "repo_id": "news_toolkit", "token_count": 294 }
925
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('PostContentCategory', () { testWidgets('renders category name in uppercase', (tester) async { final testPostContentCategory = PostContentCategory( categoryName: 'Test', isContentOverlaid: false, isVideoContent: false, ); await tester.pumpContentThemedApp(testPostContentCategory); expect( find.text(testPostContentCategory.categoryName.toUpperCase()), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_category_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_category_test.dart", "repo_id": "news_toolkit", "token_count": 266 }
926
import 'package:equatable/equatable.dart'; import 'package:flutter_news_example_api/client.dart'; /// {@template news_failure} /// Base failure class for the news repository failures. /// {@endtemplate} abstract class NewsFailure with EquatableMixin implements Exception { /// {@macro news_failure} const NewsFailure(this.error); /// The error which was caught. final Object error; @override List<Object?> get props => [error]; } /// {@template get_feed_failure} /// Thrown when fetching feed fails. /// {@endtemplate} class GetFeedFailure extends NewsFailure { /// {@macro get_feed_failure} const GetFeedFailure(super.error); } /// {@template get_categories_failure} /// Thrown when fetching categories fails. /// {@endtemplate} class GetCategoriesFailure extends NewsFailure { /// {@macro get_categories_failure} const GetCategoriesFailure(super.error); } /// {@template popular_search_failure} /// Thrown when fetching popular searches fails. /// {@endtemplate} class PopularSearchFailure extends NewsFailure { /// {@macro popular_search_failure} const PopularSearchFailure(super.error); } /// {@template relevant_search_failure} /// Thrown when fetching relevant searches fails. /// {@endtemplate} class RelevantSearchFailure extends NewsFailure { /// {@macro relevant_search_failure} const RelevantSearchFailure(super.error); } /// {@template news_repository} /// A repository that manages news data. /// {@endtemplate} class NewsRepository { /// {@macro news_repository} const NewsRepository({ required FlutterNewsExampleApiClient apiClient, }) : _apiClient = apiClient; final FlutterNewsExampleApiClient _apiClient; /// Requests news feed metadata. /// /// Supported parameters: /// * [category] - the desired news [Category]. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. Future<FeedResponse> getFeed({ Category? category, int? limit, int? offset, }) async { try { return await _apiClient.getFeed( category: category, limit: limit, offset: offset, ); } catch (error, stackTrace) { Error.throwWithStackTrace(GetFeedFailure(error), stackTrace); } } /// Requests the available news categories. Future<CategoriesResponse> getCategories() async { try { return await _apiClient.getCategories(); } catch (error, stackTrace) { Error.throwWithStackTrace(GetCategoriesFailure(error), stackTrace); } } /// Subscribes the provided [email] to the newsletter. Future<void> subscribeToNewsletter({required String email}) async { try { await _apiClient.subscribeToNewsletter(email: email); } catch (error, stackTrace) { Error.throwWithStackTrace(GetFeedFailure(error), stackTrace); } } /// Requests the popular searches. Future<PopularSearchResponse> popularSearch() async { try { return await _apiClient.popularSearch(); } catch (error, stackTrace) { Error.throwWithStackTrace(PopularSearchFailure(error), stackTrace); } } /// Requests the searches relevant to [term]. Future<RelevantSearchResponse> relevantSearch({required String term}) async { try { return await _apiClient.relevantSearch(term: term); } catch (error, stackTrace) { Error.throwWithStackTrace(RelevantSearchFailure(error), stackTrace); } } }
news_toolkit/flutter_news_example/packages/news_repository/lib/src/news_repository.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_repository/lib/src/news_repository.dart", "repo_id": "news_toolkit", "token_count": 1114 }
927
// ignore_for_file: prefer_const_constructors import 'package:notifications_client/notifications_client.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; class FakeNotificationsClient extends Fake implements NotificationsClient {} void main() { test('NotificationsClient can be implemented', () { expect(FakeNotificationsClient.new, returnsNormally); }); test('exports SubscribeToCategoryFailure', () { expect( () => SubscribeToCategoryFailure('oops'), returnsNormally, ); }); test('exports UnsubscribeFromCategoryFailure', () { expect( () => UnsubscribeFromCategoryFailure('oops'), returnsNormally, ); }); }
news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/test/src/notifications_client_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/test/src/notifications_client_test.dart", "repo_id": "news_toolkit", "token_count": 217 }
928
import 'dart:convert'; import 'package:flutter_news_example_api/client.dart'; import 'package:mocktail/mocktail.dart'; import 'package:notifications_repository/notifications_repository.dart'; import 'package:storage/storage.dart'; import 'package:test/test.dart'; class MockStorage extends Mock implements Storage {} void main() { group('NotificationsStorage', () { late Storage storage; setUp(() { storage = MockStorage(); when( () => storage.write( key: any(named: 'key'), value: any(named: 'value'), ), ).thenAnswer((_) async {}); }); group('setNotificationsEnabled', () { test('saves the value in Storage', () async { const enabled = true; await NotificationsStorage(storage: storage) .setNotificationsEnabled(enabled: enabled); verify( () => storage.write( key: NotificationsStorageKeys.notificationsEnabled, value: enabled.toString(), ), ).called(1); }); }); group('fetchNotificationsEnabled', () { test('returns the value from Storage', () async { when( () => storage.read(key: NotificationsStorageKeys.notificationsEnabled), ).thenAnswer((_) async => 'true'); final result = await NotificationsStorage(storage: storage) .fetchNotificationsEnabled(); verify( () => storage.read( key: NotificationsStorageKeys.notificationsEnabled, ), ).called(1); expect(result, isTrue); }); test('returns false when no value exists in Storage', () async { when( () => storage.read(key: NotificationsStorageKeys.notificationsEnabled), ).thenAnswer((_) async => null); final result = await NotificationsStorage(storage: storage) .fetchNotificationsEnabled(); verify( () => storage.read( key: NotificationsStorageKeys.notificationsEnabled, ), ).called(1); expect(result, isFalse); }); }); group('setCategoriesPreferences', () { test('saves the value in Storage', () async { const preferences = { Category.top, Category.health, }; await NotificationsStorage(storage: storage).setCategoriesPreferences( categories: preferences, ); verify( () => storage.write( key: NotificationsStorageKeys.categoriesPreferences, value: json.encode( preferences.map((category) => category.name).toList(), ), ), ).called(1); }); }); group('fetchCategoriesPreferences', () { test('returns the value from Storage', () async { const preferences = { Category.health, Category.entertainment, }; when( () => storage.read(key: NotificationsStorageKeys.categoriesPreferences), ).thenAnswer( (_) async => json.encode( preferences.map((preference) => preference.name).toList(), ), ); final result = await NotificationsStorage(storage: storage) .fetchCategoriesPreferences(); verify( () => storage.read( key: NotificationsStorageKeys.categoriesPreferences, ), ).called(1); expect(result, equals(preferences)); }); test('returns null when no value exists in Storage', () async { when( () => storage.read(key: NotificationsStorageKeys.categoriesPreferences), ).thenAnswer((_) async => null); final result = await NotificationsStorage(storage: storage) .fetchCategoriesPreferences(); verify( () => storage.read( key: NotificationsStorageKeys.categoriesPreferences, ), ).called(1); expect(result, isNull); }); }); }); }
news_toolkit/flutter_news_example/packages/notifications_repository/test/src/notifications_storage_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/test/src/notifications_storage_test.dart", "repo_id": "news_toolkit", "token_count": 1749 }
929
# purchase_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A PurchaseClient stubbing InAppPurchase implementation. [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
news_toolkit/flutter_news_example/packages/purchase_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/purchase_client/README.md", "repo_id": "news_toolkit", "token_count": 170 }
930
export 'src/persistent_storage.dart';
news_toolkit/flutter_news_example/packages/storage/persistent_storage/lib/persistent_storage.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/lib/persistent_storage.dart", "repo_id": "news_toolkit", "token_count": 13 }
931
// This package is just an abstraction. // See secure_storage for a concrete implementation // ignore_for_file: prefer_const_constructors import 'package:storage/storage.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; // Storage is exported and can be implemented class FakeStorage extends Fake implements Storage {} void main() { test('Storage can be implemented', () { expect(FakeStorage.new, returnsNormally); }); test('exports StorageException', () { expect(() => StorageException('oops'), returnsNormally); }); }
news_toolkit/flutter_news_example/packages/storage/storage/test/storage_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/storage/test/storage_test.dart", "repo_id": "news_toolkit", "token_count": 156 }
932
// ignore_for_file: prefer_const_constructors 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; class FakeInterstitialAd extends Fake implements ads.InterstitialAd {} class FakeRewardedAd extends Fake implements ads.RewardedAd {} class FakeRewardItem extends Fake implements ads.RewardItem {} void main() { group('FullScreenAdsState', () { test('supports value comparisons', () { final interstitialAd = FakeInterstitialAd(); final rewardedAd = FakeRewardedAd(); final earnedReward = FakeRewardItem(); expect( FullScreenAdsState( interstitialAd: interstitialAd, rewardedAd: rewardedAd, earnedReward: earnedReward, status: FullScreenAdsStatus.initial, ), equals( FullScreenAdsState( interstitialAd: interstitialAd, rewardedAd: rewardedAd, earnedReward: earnedReward, status: FullScreenAdsStatus.initial, ), ), ); }); group('copyWith', () { test( 'returns same object ' 'when no properties are passed', () { expect( FullScreenAdsState.initial().copyWith(), equals(FullScreenAdsState.initial()), ); }); test( 'returns object with updated interstitialAd ' 'when interstitialAd is passed', () { final interstitialAd = FakeInterstitialAd(); expect( FullScreenAdsState.initial().copyWith(interstitialAd: interstitialAd), equals( FullScreenAdsState( status: FullScreenAdsStatus.initial, interstitialAd: interstitialAd, ), ), ); }); test( 'returns object with updated rewardedAd ' 'when rewardedAd is passed', () { final rewardedAd = FakeRewardedAd(); expect( FullScreenAdsState.initial().copyWith(rewardedAd: rewardedAd), equals( FullScreenAdsState( status: FullScreenAdsStatus.initial, rewardedAd: rewardedAd, ), ), ); }); test( 'returns object with updated earnedReward ' 'when earnedReward is passed', () { final earnedReward = FakeRewardItem(); expect( FullScreenAdsState.initial().copyWith(earnedReward: earnedReward), equals( FullScreenAdsState( status: FullScreenAdsStatus.initial, earnedReward: earnedReward, ), ), ); }); test( 'returns object with updated status ' 'when status is passed', () { const status = FullScreenAdsStatus.showingInterstitialAd; expect( FullScreenAdsState.initial().copyWith(status: status), equals( FullScreenAdsState(status: status), ), ); }); }); }); }
news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_state_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_state_test.dart", "repo_id": "news_toolkit", "token_count": 1373 }
933
// ignore_for_file: prefer_const_constructors // ignore_for_file: prefer_const_literals_to_create_immutables import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState> implements ArticleBloc {} void main() { group('ArticleComments', () { testWidgets('renders title and text field', (tester) async { await tester.pumpApp(ArticleComments()); expect( find.byKey(Key('articleComments_discussionTitle')), findsOneWidget, ); expect( find.byType(AppTextField), findsOneWidget, ); }); testWidgets( 'adds ArticleCommented with article title to ArticleBloc ' 'when comment is submitted', (tester) async { final ArticleBloc articleBloc = MockArticleBloc(); final articleState = ArticleState.initial().copyWith(title: 'title'); when(() => articleBloc.state).thenReturn(articleState); await tester.pumpApp( BlocProvider.value( value: articleBloc, child: ArticleComments(), ), ); final textField = tester.widget<AppTextField>(find.byType(AppTextField)); textField.onSubmitted!(''); verify( () => articleBloc.add( ArticleCommented(articleTitle: articleState.title!), ), ).called(1); }); }); }
news_toolkit/flutter_news_example/test/article/widgets/article_comments_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_comments_test.dart", "repo_id": "news_toolkit", "token_count": 662 }
934
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('CategoryFeedLoaderItem', () { testWidgets('renders CircularProgressIndicator', (tester) async { await tester.pumpApp(CategoryFeedLoaderItem()); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets('executes onPresented callback', (tester) async { final completer = Completer<void>(); await tester.pumpApp( CategoryFeedLoaderItem(onPresented: completer.complete), ); expect(completer.isCompleted, isTrue); }); }); }
news_toolkit/flutter_news_example/test/feed/widgets/category_feed_loader_item_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/feed/widgets/category_feed_loader_item_test.dart", "repo_id": "news_toolkit", "token_count": 287 }
935
import 'package:flutter/material.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('LoginModal', () { test('has a route', () { expect(LoginModal.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('renders a LoginForm', (tester) async { await tester.pumpApp(const LoginModal()); expect(find.byType(LoginForm), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/test/login/view/login_modal_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/login/view/login_modal_test.dart", "repo_id": "news_toolkit", "token_count": 192 }
936
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/newsletter/newsletter.dart' hide NewsletterEvent; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:visibility_detector/visibility_detector.dart'; import '../../helpers/helpers.dart'; class MockNewsletterBloc extends Mock implements NewsletterBloc {} class MockAnalyticsBloc extends MockBloc<AnalyticsEvent, AnalyticsState> implements AnalyticsBloc {} void main() { late NewsletterBloc newsletterBloc; const initialState = NewsletterState(); setUp(() { newsletterBloc = MockNewsletterBloc(); VisibilityDetectorController.instance.updateInterval = Duration.zero; }); group('Newsletter', () { testWidgets('renders NewsletterView', (tester) async { await tester.pumpApp( Newsletter(), ); await tester.pump(); expect(find.byType(NewsletterView), findsOneWidget); }); }); group('NewsletterView', () { testWidgets('renders NewsletterSignUp', (tester) async { whenListen( newsletterBloc, Stream.fromIterable([initialState]), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); expect(find.byType(NewsletterSignUp), findsOneWidget); }); testWidgets('renders disabled button when status is not valid', (tester) async { whenListen( newsletterBloc, Stream.fromIterable([initialState]), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); expect( tester.widget<AppButton>(find.byType(AppButton)).onPressed, isNull, ); }); testWidgets('renders enabled button when status is valid', (tester) async { whenListen( newsletterBloc, Stream.fromIterable([initialState.copyWith(isValid: true)]), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); final signUpButton = find.byType(AppButton); expect(tester.widget<AppButton>(signUpButton).onPressed, isNotNull); await tester.tap(signUpButton); verify(() => newsletterBloc.add(NewsletterSubscribed())).called(1); }); testWidgets( 'adds EmailChanged to NewsletterBloc ' 'on email text field filled', (tester) async { whenListen( newsletterBloc, Stream.fromIterable([initialState.copyWith(isValid: true)]), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); const changedEmail = '[email protected]'; await tester.enterText(find.byType(AppEmailTextField), changedEmail); verify(() => newsletterBloc.add(EmailChanged(email: changedEmail))) .called(1); }); testWidgets( 'adds TrackAnalyticsEvent to AnalyticsBloc ' 'with NewsletterEvent.impression ' 'when shown', (tester) async { final AnalyticsBloc analyticsBloc = MockAnalyticsBloc(); whenListen( newsletterBloc, Stream.fromIterable([initialState]), initialState: initialState, ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: newsletterBloc), BlocProvider.value(value: analyticsBloc), ], child: NewsletterView(), ), ); verify( () => analyticsBloc.add( TrackAnalyticsEvent(NewsletterEvent.impression()), ), ).called(1); }); testWidgets( 'adds TrackAnalyticsEvent to AnalyticsBloc ' 'with NewsletterEvent.signUp ' 'when status is success', (tester) async { final AnalyticsBloc analyticsBloc = MockAnalyticsBloc(); whenListen( newsletterBloc, Stream.fromIterable( [ NewsletterState(), NewsletterState(status: NewsletterStatus.success), ], ), initialState: initialState, ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: newsletterBloc), BlocProvider.value(value: analyticsBloc), ], child: NewsletterView(), ), ); verify( () => analyticsBloc.add( TrackAnalyticsEvent(NewsletterEvent.signUp()), ), ).called(1); }); testWidgets('renders NewsletterSuccess when NewsletterStatus is success', (tester) async { whenListen( newsletterBloc, Stream.fromIterable( [NewsletterState(status: NewsletterStatus.success)], ), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); expect(find.byType(NewsletterSucceeded), findsOneWidget); }); testWidgets('shows SnackBar when NewsletterStatus is failure', (tester) async { whenListen( newsletterBloc, Stream.fromIterable( [NewsletterState(status: NewsletterStatus.failure)], ), initialState: initialState, ); await tester.pumpApp( BlocProvider<NewsletterBloc>.value( value: newsletterBloc, child: NewsletterView(), ), ); await tester.pump(); expect(find.byType(SnackBar), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/test/newsletter/view/newsletter_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/newsletter/view/newsletter_test.dart", "repo_id": "news_toolkit", "token_count": 2626 }
937
import 'package:flutter_news_example/search/search.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('SearchHeadlineText', () { testWidgets('renders headerText uppercased', (tester) async { await tester.pumpApp( const SearchHeadlineText( headerText: 'text', ), ); expect(find.text('TEXT'), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/test/search/widgets/search_headline_text_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/search/widgets/search_headline_text_test.dart", "repo_id": "news_toolkit", "token_count": 180 }
938
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/theme_selector/theme_selector.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockThemeModeBloc extends MockBloc<ThemeModeEvent, ThemeMode> implements ThemeModeBloc {} void main() { late ThemeModeBloc themeModeBloc; group('ThemeSelector', () { setUp(() { themeModeBloc = MockThemeModeBloc(); when(() => themeModeBloc.state).thenReturn(ThemeMode.system); }); testWidgets('contains all three ThemeMode options', (tester) async { await tester.pumpApp(const ThemeSelector(), themeModeBloc: themeModeBloc); final dropdown = find.byKey(const Key('themeSelector_dropdown')); expect(dropdown, findsOneWidget); await tester.tap(dropdown); await tester.pumpAndSettle(); expect( find.byKey(const Key('themeSelector_system_dropdownMenuItem')).first, findsOneWidget, ); expect( find.byKey(const Key('themeSelector_light_dropdownMenuItem')).first, findsOneWidget, ); expect( find.byKey(const Key('themeSelector_dark_dropdownMenuItem')).first, findsOneWidget, ); }); testWidgets('sets the new ThemeMode on change', (tester) async { await tester.pumpApp(const ThemeSelector(), themeModeBloc: themeModeBloc); await tester.tap(find.byKey(const Key('themeSelector_dropdown'))); await tester.pumpAndSettle(); await tester.tap( find.byKey(const Key('themeSelector_dark_dropdownMenuItem')).last, ); verify( () => themeModeBloc.add(const ThemeModeChanged(ThemeMode.dark)), ).called(1); }); }); }
news_toolkit/flutter_news_example/test/theme_selector/view/theme_selector_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/theme_selector/view/theme_selector_test.dart", "repo_id": "news_toolkit", "token_count": 721 }
939
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ {{#flavors}} { "name": "{{name}}", "request": "launch", "type": "dart", "program": "lib/main/main_{{name}}.dart", "args": [ "--flavor", "{{name}}", "--target", "lib/main/main_{{name}}.dart", "--dart-define", "FLAVOR_DEEP_LINK_DOMAIN={{deep_link_domain}}", "--dart-define", "FLAVOR_DEEP_LINK_PATH=email_login", "--dart-define", "TWITTER_API_KEY={{twitter_api_key}}", "--dart-define", "TWITTER_API_SECRET={{twitter_api_secret}}", "--dart-define", "TWITTER_REDIRECT_URI={{project_name.paramCase()}}://" ] }, {{/flavors}} { "name": "Launch UI Gallery", "request": "launch", "type": "dart", "program": "packages/app_ui/gallery/lib/main.dart" } ] }
news_toolkit/tool/generator/static/launch.json/0
{ "file_path": "news_toolkit/tool/generator/static/launch.json", "repo_id": "news_toolkit", "token_count": 737 }
940
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -e platform="$1" build_mode="$2" output_dir="$3" shift 3 cd "$output_dir"/all_packages flutter build "$platform" --"$build_mode" "$@"
packages/.ci/scripts/build_all_packages_app_legacy.sh/0
{ "file_path": "packages/.ci/scripts/build_all_packages_app_legacy.sh", "repo_id": "packages", "token_count": 105 }
941
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -e # This file runs the repo tooling (see TOOL_PATH) in a configuration that's # common to almost all of the CI usage, avoiding the need to pass the same # flags (e.g., --packages-for-branch) in every CI invocation. # # For local use, directly run `dart run <tool path>`. readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" readonly REPO_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")" readonly TOOL_PATH="$REPO_DIR/script/tool/bin/flutter_plugin_tools.dart" # Ensure that the tool dependencies have been fetched. (pushd "$REPO_DIR/script/tool" && dart pub get && popd) >/dev/null # The tool expects to be run from the repo root. cd "$REPO_DIR" # Run from the in-tree source. # PACKAGE_SHARDING is (optionally) set in CI configuration. See .ci.yaml dart run "$TOOL_PATH" "$@" --packages-for-branch --log-timing $PACKAGE_SHARDING
packages/.ci/scripts/tool_runner.sh/0
{ "file_path": "packages/.ci/scripts/tool_runner.sh", "repo_id": "packages", "token_count": 351 }
942
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: set default apps script: .ci/scripts/set_default_linux_apps.sh infra_step: true - name: download Dart deps script: .ci/scripts/tool_runner.sh args: ["fetch-deps", "--linux", "--supporting-target-platforms-only"] infra_step: true - name: build examples script: .ci/scripts/tool_runner.sh args: ["build-examples", "--linux"] - name: native test script: .ci/scripts/xvfb_tool_runner.sh args: ["native-test", "--linux"] - name: drive examples script: .ci/scripts/xvfb_tool_runner.sh args: ["drive-examples", "--linux", "--exclude=script/configs/exclude_integration_linux.yaml"]
packages/.ci/targets/linux_platform_tests.yaml/0
{ "file_path": "packages/.ci/targets/linux_platform_tests.yaml", "repo_id": "packages", "token_count": 275 }
943
# High quality pre-built Animations for Flutter This package contains pre-canned animations for commonly-desired effects. The animations can be customized with your content and dropped into your application to delight your users. To see examples of the following animations on a device or simulator: ```bash cd example/ flutter run --release ``` ## Material motion for Flutter Material motion is a set of transition patterns that help users understand and navigate an app. For more information on the patterns and how to choose between them, check out the [Material motion system spec](https://material.io/design/motion/the-motion-system.html). A codelab, [Building Beautiful Transitions with Material Motion for Flutter](https://codelabs.developers.google.com/codelabs/material-motion-flutter), is also available. Material motion defines the following transition patterns: 1. [Container transform](#container-transform) 2. [Shared axis](#shared-axis) 3. [Fade through](#fade-through) 4. [Fade](#fade) ### Container transform The **container transform** pattern is designed for transitions between UI elements that include a container. This pattern creates a visible connection between two UI elements. !["Container transform gallery - normal speed and slow motion"](example/demo_gifs/container_transform_lineup.gif) _Examples of the container transform:_ 1. _A card into a details page_ 2. _A list item into a details page_ 3. _A FAB into a details page_ 4. _A search bar into expanded search_ ### Shared axis The **shared axis** pattern is used for transitions between UI elements that have a spatial or navigational relationship. This pattern uses a shared transformation on the x, y, or z axis to reinforce the relationship between elements. !["Shared axis gallery - normal speed and slow motion"](example/demo_gifs/shared_axis_lineup.gif) _Examples of the shared axis pattern:_ 1. _An onboarding flow transitions along the x-axis_ 2. _A stepper transitions along the y-axis_ 3. _A parent-child navigation transitions along the z-axis_ ### Fade through The **fade through** pattern is used for transitions between UI elements that do not have a strong relationship to each other. !["Fade through gallery - normal speed and slow motion"](example/demo_gifs/fade_through_lineup.gif) _Examples of the fade through pattern:_ 1. _Tapping destinations in a bottom navigation bar_ 2. _Tapping a refresh icon_ 3. _Tapping an account switcher_ ### Fade The **fade** pattern is used for UI elements that enter or exit within the bounds of the screen, such as a dialog that fades in the center of the screen. !["Fade gallery - normal speed and slow motion"](example/demo_gifs/fade_lineup.gif) _Examples of the fade pattern:_ 1. _A dialog_ 2. _A menu_ 3. _A snackbar_ 4. _A FAB_
packages/packages/animations/README.md/0
{ "file_path": "packages/packages/animations/README.md", "repo_id": "packages", "token_count": 772 }
944
#include "Generated.xcconfig"
packages/packages/animations/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/animations/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
945
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; const String _loremIpsumParagraph = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' 'tempor incididunt ut labore et dolore magna aliqua. Vulputate dignissim ' 'suspendisse in est. Ut ornare lectus sit amet. Eget nunc lobortis mattis ' 'aliquam faucibus purus in. Hendrerit gravida rutrum quisque non tellus ' 'orci ac auctor. Mattis aliquam faucibus purus in massa. Tellus rutrum ' 'tellus pellentesque eu tincidunt tortor. Nunc eget lorem dolor sed. Nulla ' 'at volutpat diam ut venenatis tellus in metus. Tellus cras adipiscing enim ' 'eu turpis. Pretium fusce id velit ut tortor. Adipiscing enim eu turpis ' 'egestas pretium. Quis varius quam quisque id. Blandit aliquam etiam erat ' 'velit scelerisque. In nisl nisi scelerisque eu. Semper risus in hendrerit ' 'gravida rutrum quisque. Suspendisse in est ante in nibh mauris cursus ' 'mattis molestie. Adipiscing elit duis tristique sollicitudin nibh sit ' 'amet commodo nulla. Pretium viverra suspendisse potenti nullam ac tortor ' 'vitae.\n' '\n' 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' 'tempor incididunt ut labore et dolore magna aliqua. Vulputate dignissim ' 'suspendisse in est. Ut ornare lectus sit amet. Eget nunc lobortis mattis ' 'aliquam faucibus purus in. Hendrerit gravida rutrum quisque non tellus ' 'orci ac auctor. Mattis aliquam faucibus purus in massa. Tellus rutrum ' 'tellus pellentesque eu tincidunt tortor. Nunc eget lorem dolor sed. Nulla ' 'at volutpat diam ut venenatis tellus in metus. Tellus cras adipiscing enim ' 'eu turpis. Pretium fusce id velit ut tortor. Adipiscing enim eu turpis ' 'egestas pretium. Quis varius quam quisque id. Blandit aliquam etiam erat ' 'velit scelerisque. In nisl nisi scelerisque eu. Semper risus in hendrerit ' 'gravida rutrum quisque. Suspendisse in est ante in nibh mauris cursus ' 'mattis molestie. Adipiscing elit duis tristique sollicitudin nibh sit ' 'amet commodo nulla. Pretium viverra suspendisse potenti nullam ac tortor ' 'vitae'; const double _fabDimension = 56.0; /// The demo page for [OpenContainerTransform]. class OpenContainerTransformDemo extends StatefulWidget { /// Creates the demo page for [OpenContainerTransform]. const OpenContainerTransformDemo({super.key}); @override State<OpenContainerTransformDemo> createState() { return _OpenContainerTransformDemoState(); } } class _OpenContainerTransformDemoState extends State<OpenContainerTransformDemo> { ContainerTransitionType _transitionType = ContainerTransitionType.fade; void _showMarkedAsDoneSnackbar(bool? isMarkedAsDone) { if (isMarkedAsDone ?? false) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Marked as done!'), )); } } void _showSettingsBottomModalSheet(BuildContext context) { showModalBottomSheet<void>( context: context, builder: (BuildContext context) { return StatefulBuilder( builder: (BuildContext context, StateSetter setModalState) { return Container( height: 125, padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Fade mode', style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 12), ToggleButtons( borderRadius: BorderRadius.circular(2.0), selectedBorderColor: Theme.of(context).colorScheme.primary, onPressed: (int index) { setModalState(() { setState(() { _transitionType = index == 0 ? ContainerTransitionType.fade : ContainerTransitionType.fadeThrough; }); }); }, isSelected: <bool>[ _transitionType == ContainerTransitionType.fade, _transitionType == ContainerTransitionType.fadeThrough, ], children: const <Widget>[ Text('FADE'), Padding( padding: EdgeInsets.symmetric(horizontal: 10.0), child: Text('FADE THROUGH'), ), ], ), ], ), ); }, ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Container transform'), actions: <Widget>[ IconButton( icon: const Icon(Icons.settings), onPressed: () { _showSettingsBottomModalSheet(context); }, ), ], ), body: ListView( padding: const EdgeInsets.all(8.0), children: <Widget>[ _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _ExampleCard(openContainer: openContainer); }, onClosed: _showMarkedAsDoneSnackbar, ), const SizedBox(height: 16.0), _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _ExampleSingleTile(openContainer: openContainer); }, onClosed: _showMarkedAsDoneSnackbar, ), const SizedBox(height: 16.0), Row( children: <Widget>[ Expanded( child: _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _SmallerCard( openContainer: openContainer, subtitle: 'Secondary text', ); }, onClosed: _showMarkedAsDoneSnackbar, ), ), const SizedBox(width: 8.0), Expanded( child: _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _SmallerCard( openContainer: openContainer, subtitle: 'Secondary text', ); }, onClosed: _showMarkedAsDoneSnackbar, ), ), ], ), const SizedBox(height: 16.0), Row( children: <Widget>[ Expanded( child: _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _SmallerCard( openContainer: openContainer, subtitle: 'Secondary', ); }, onClosed: _showMarkedAsDoneSnackbar, ), ), const SizedBox(width: 8.0), Expanded( child: _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _SmallerCard( openContainer: openContainer, subtitle: 'Secondary', ); }, onClosed: _showMarkedAsDoneSnackbar, ), ), const SizedBox(width: 8.0), Expanded( child: _OpenContainerWrapper( transitionType: _transitionType, closedBuilder: (BuildContext _, VoidCallback openContainer) { return _SmallerCard( openContainer: openContainer, subtitle: 'Secondary', ); }, onClosed: _showMarkedAsDoneSnackbar, ), ), ], ), const SizedBox(height: 16.0), ...List<Widget>.generate(10, (int index) { return OpenContainer<bool>( transitionType: _transitionType, openBuilder: (BuildContext _, VoidCallback openContainer) { return const _DetailsPage(); }, onClosed: _showMarkedAsDoneSnackbar, tappable: false, closedShape: const RoundedRectangleBorder(), closedElevation: 0.0, closedBuilder: (BuildContext _, VoidCallback openContainer) { return ListTile( leading: Image.asset( 'assets/avatar_logo.png', width: 40, ), onTap: openContainer, title: Text('List item ${index + 1}'), subtitle: const Text('Secondary text'), ); }, ); }), ], ), floatingActionButton: OpenContainer( transitionType: _transitionType, openBuilder: (BuildContext context, VoidCallback _) { return const _DetailsPage( includeMarkAsDoneButton: false, ); }, closedElevation: 6.0, closedShape: const RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(_fabDimension / 2), ), ), closedColor: Theme.of(context).colorScheme.secondary, closedBuilder: (BuildContext context, VoidCallback openContainer) { return SizedBox( height: _fabDimension, width: _fabDimension, child: Center( child: Icon( Icons.add, color: Theme.of(context).colorScheme.onSecondary, ), ), ); }, ), ); } } class _OpenContainerWrapper extends StatelessWidget { const _OpenContainerWrapper({ required this.closedBuilder, required this.transitionType, required this.onClosed, }); final CloseContainerBuilder closedBuilder; final ContainerTransitionType transitionType; final ClosedCallback<bool?> onClosed; @override Widget build(BuildContext context) { return OpenContainer<bool>( transitionType: transitionType, openBuilder: (BuildContext context, VoidCallback _) { return const _DetailsPage(); }, onClosed: onClosed, tappable: false, closedBuilder: closedBuilder, ); } } class _ExampleCard extends StatelessWidget { const _ExampleCard({required this.openContainer}); final VoidCallback openContainer; @override Widget build(BuildContext context) { return _InkWellOverlay( openContainer: openContainer, height: 300, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded( child: ColoredBox( color: Colors.black38, child: Center( child: Image.asset( 'assets/placeholder_image.png', width: 100, ), ), ), ), const ListTile( title: Text('Title'), subtitle: Text('Secondary text'), ), Padding( padding: const EdgeInsets.only( left: 16.0, right: 16.0, bottom: 16.0, ), child: Text( 'Lorem ipsum dolor sit amet, consectetur ' 'adipiscing elit, sed do eiusmod tempor.', style: Theme.of(context) .textTheme .bodyMedium! .copyWith(color: Colors.black54), ), ), ], ), ); } } class _SmallerCard extends StatelessWidget { const _SmallerCard({ required this.openContainer, required this.subtitle, }); final VoidCallback openContainer; final String subtitle; @override Widget build(BuildContext context) { return _InkWellOverlay( openContainer: openContainer, height: 225, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( color: Colors.black38, height: 150, child: Center( child: Image.asset( 'assets/placeholder_image.png', width: 80, ), ), ), Expanded( child: Padding( padding: const EdgeInsets.all(10.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Title', style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 4), Text( subtitle, style: Theme.of(context).textTheme.bodySmall, ), ], ), ), ), ], ), ); } } class _ExampleSingleTile extends StatelessWidget { const _ExampleSingleTile({required this.openContainer}); final VoidCallback openContainer; @override Widget build(BuildContext context) { const double height = 100.0; return _InkWellOverlay( openContainer: openContainer, height: height, child: Row( children: <Widget>[ Container( color: Colors.black38, height: height, width: height, child: Center( child: Image.asset( 'assets/placeholder_image.png', width: 60, ), ), ), Expanded( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Title', style: Theme.of(context).textTheme.titleMedium, ), const SizedBox(height: 8), Text( 'Lorem ipsum dolor sit amet, consectetur ' 'adipiscing elit,', style: Theme.of(context).textTheme.bodySmall), ], ), ), ), ], ), ); } } class _InkWellOverlay extends StatelessWidget { const _InkWellOverlay({ this.openContainer, this.height, this.child, }); final VoidCallback? openContainer; final double? height; final Widget? child; @override Widget build(BuildContext context) { return SizedBox( height: height, child: InkWell( onTap: openContainer, child: child, ), ); } } class _DetailsPage extends StatelessWidget { const _DetailsPage({this.includeMarkAsDoneButton = true}); final bool includeMarkAsDoneButton; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Details page'), actions: <Widget>[ if (includeMarkAsDoneButton) IconButton( icon: const Icon(Icons.done), onPressed: () => Navigator.pop(context, true), tooltip: 'Mark as done', ) ], ), body: ListView( children: <Widget>[ Container( color: Colors.black38, height: 250, child: Padding( padding: const EdgeInsets.all(70.0), child: Image.asset( 'assets/placeholder_image.png', ), ), ), Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Title', style: Theme.of(context).textTheme.headlineSmall!.copyWith( color: Colors.black54, fontSize: 30.0, ), ), const SizedBox(height: 10), Text( _loremIpsumParagraph, style: Theme.of(context).textTheme.bodyMedium!.copyWith( color: Colors.black54, height: 1.5, fontSize: 16.0, ), ), ], ), ), ], ), ); } }
packages/packages/animations/example/lib/container_transition.dart/0
{ "file_path": "packages/packages/animations/example/lib/container_transition.dart", "repo_id": "packages", "token_count": 9116 }
946
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// An internal representation of a child widget subtree that, now or in the past, /// was set on the [PageTransitionSwitcher.child] field and is now in the process of /// transitioning. /// /// The internal representation includes fields that we don't want to expose to /// the public API (like the controllers). class _ChildEntry { /// Creates a [_ChildEntry]. /// /// The [primaryController], [secondaryController], [transition] and /// [widgetChild] parameters must not be null. _ChildEntry({ required this.primaryController, required this.secondaryController, required this.transition, required this.widgetChild, }); /// The animation controller for the child's transition. final AnimationController primaryController; /// The (curved) animation being used to drive the transition. final AnimationController secondaryController; /// The currently built transition for this child. Widget transition; /// The widget's child at the time this entry was created or updated. /// Used to rebuild the transition if necessary. Widget widgetChild; /// Release the resources used by this object. /// /// The object is no longer usable after this method is called. void dispose() { primaryController.dispose(); secondaryController.dispose(); } @override String toString() { return 'PageTransitionSwitcherEntry#${shortHash(this)}($widgetChild)'; } } /// Signature for builders used to generate custom layouts for /// [PageTransitionSwitcher]. /// /// The builder should return a widget which contains the given children, laid /// out as desired. It must not return null. The builder should be able to /// handle an empty list of `entries`. typedef PageTransitionSwitcherLayoutBuilder = Widget Function( List<Widget> entries, ); /// Signature for builders used to generate custom transitions for /// [PageTransitionSwitcher]. /// /// The function should return a widget which wraps the given `child`. /// /// When a [PageTransitionSwitcher]'s `child` is replaced, the new child's /// `primaryAnimation` runs forward and the value of its `secondaryAnimation` is /// usually fixed at 0.0. At the same time, the old child's `secondaryAnimation` /// runs forward, and the value of its primaryAnimation is usually fixed at 1.0. /// /// The widget returned by the [PageTransitionSwitcherTransitionBuilder] can /// incorporate both animations. It will use the primary animation to define how /// its child appears, and the secondary animation to define how its child /// disappears. typedef PageTransitionSwitcherTransitionBuilder = Widget Function( Widget child, Animation<double> primaryAnimation, Animation<double> secondaryAnimation, ); /// A widget that transitions from an old child to a new child whenever [child] /// changes using an animation specified by [transitionBuilder]. /// /// This is a variation of an [AnimatedSwitcher], but instead of using the /// same transition for enter and exit, two separate transitions can be /// specified, similar to how the enter and exit transitions of a [PageRoute] /// are defined. /// /// When a new [child] is specified, the [transitionBuilder] is effectively /// applied twice, once to the old child and once to the new one. When /// [reverse] is false, the old child's `secondaryAnimation` runs forward, and /// the value of its `primaryAnimation` is usually fixed at 1.0. The new child's /// `primaryAnimation` runs forward and the value of its `secondaryAnimation` is /// usually fixed at 0.0. The widget returned by the [transitionBuilder] can /// incorporate both animations. It will use the primary animation to define how /// its child appears, and the secondary animation to define how its child /// disappears. This is similar to the transition associated with pushing a new /// [PageRoute] on top of another. /// /// When [reverse] is true, the old child's `primaryAnimation` runs in reverse /// and the value of its `secondaryAnimation` is usually fixed at 0.0. The new /// child's `secondaryAnimation` runs in reverse and the value of its /// `primaryAnimation` is usually fixed at 1.0. This is similar to popping a /// [PageRoute] to reveal another [PageRoute] underneath it. /// /// This process is the same as the one used by [PageRoute.buildTransitions]. /// /// The following example shows a [transitionBuilder] that slides out the /// old child to the right (driven by the `secondaryAnimation`) while the new /// child fades in (driven by the `primaryAnimation`): /// /// ```dart /// transitionBuilder: ( /// Widget child, /// Animation<double> primaryAnimation, /// Animation<double> secondaryAnimation, /// ) { /// return SlideTransition( /// position: Tween<Offset>( /// begin: Offset.zero, /// end: const Offset(1.5, 0.0), /// ).animate(secondaryAnimation), /// child: FadeTransition( /// opacity: Tween<double>( /// begin: 0.0, /// end: 1.0, /// ).animate(primaryAnimation), /// child: child, /// ), /// ); /// }, /// ``` /// /// If the children are swapped fast enough (i.e. before [duration] elapses), /// more than one old child can exist and be transitioning out while the /// newest one is transitioning in. /// /// If the *new* child is the same widget type and key as the *old* child, /// but with different parameters, then [PageTransitionSwitcher] will *not* do a /// transition between them, since as far as the framework is concerned, they /// are the same widget and the existing widget can be updated with the new /// parameters. To force the transition to occur, set a [Key] on each child /// widget that you wish to be considered unique (typically a [ValueKey] on the /// widget data that distinguishes this child from the others). For example, /// changing the child from `SizedBox(width: 10)` to `SizedBox(width: 100)` /// would not trigger a transition but changing the child from /// `SizedBox(width: 10)` to `SizedBox(key: Key('foo'), width: 100)` would. /// Similarly, changing the child to `Container(width: 10)` would trigger a /// transition. /// /// The same key can be used for a new child as was used for an already-outgoing /// child; the two will not be considered related. For example, if a progress /// indicator with key A is first shown, then an image with key B, then another /// progress indicator with key A again, all in rapid succession, then the old /// progress indicator and the image will be fading out while a new progress /// indicator is fading in. /// /// PageTransitionSwitcher uses the [layoutBuilder] property to lay out the /// old and new child widgets. By default, [defaultLayoutBuilder] is used. /// See the documentation for [layoutBuilder] for suggestions on how to /// configure the layout of the incoming and outgoing child widgets if /// [defaultLayoutBuilder] is not your desired layout. class PageTransitionSwitcher extends StatefulWidget { /// Creates a [PageTransitionSwitcher]. /// /// The [duration], [reverse], and [transitionBuilder] parameters /// must not be null. const PageTransitionSwitcher({ super.key, this.duration = const Duration(milliseconds: 300), this.reverse = false, required this.transitionBuilder, this.layoutBuilder = defaultLayoutBuilder, this.child, }); /// The current child widget to display. /// /// If there was an old child, it will be transitioned out using the /// secondary animation of the [transitionBuilder], while the new child /// transitions in using the primary animation of the [transitionBuilder]. /// /// If there was no old child, then this child will transition in using /// the primary animation of the [transitionBuilder]. /// /// The child is considered to be "new" if it has a different type or [Key] /// (see [Widget.canUpdate]). final Widget? child; /// The duration of the transition from the old [child] value to the new one. /// /// This duration is applied to the given [child] when that property is set to /// a new child. Changing [duration] will not affect the durations of /// transitions already in progress. final Duration duration; /// Indicates whether the new [child] will visually appear on top of or /// underneath the old child. /// /// When this is false, the new child will transition in on top of the /// old child while its primary animation and the secondary /// animation of the old child are running forward. This is similar to /// the transition associated with pushing a new [PageRoute] on top of /// another. /// /// When this is true, the new child will transition in below the /// old child while its secondary animation and the primary /// animation of the old child are running in reverse. This is similar to /// the transition associated with popping a [PageRoute] to reveal a new /// [PageRoute] below it. final bool reverse; /// A function that wraps a new [child] with a primary and secondary animation /// set define how the child appears and disappears. /// /// This is only called when a new [child] is set (not for each build), or /// when a new [transitionBuilder] is set. If a new [transitionBuilder] is /// set, then the transition is rebuilt for the current child and all old /// children using the new [transitionBuilder]. The function must not return /// null. /// /// The child provided to the transitionBuilder may be null. final PageTransitionSwitcherTransitionBuilder transitionBuilder; /// A function that wraps all of the children that are transitioning out, and /// the [child] that's transitioning in, with a widget that lays all of them /// out. This is called every time this widget is built. The function must not /// return null. /// /// The default [PageTransitionSwitcherLayoutBuilder] used is /// [defaultLayoutBuilder]. /// /// The following example shows a [layoutBuilder] that places all entries in a /// [Stack] that sizes itself to match the largest of the active entries. /// All children are aligned on the top left corner of the [Stack]. /// /// ```dart /// PageTransitionSwitcher( /// duration: const Duration(milliseconds: 100), /// child: Container(color: Colors.red), /// layoutBuilder: ( /// List<Widget> entries, /// ) { /// return Stack( /// children: entries, /// alignment: Alignment.topLeft, /// ); /// }, /// ), /// ``` /// See [PageTransitionSwitcherLayoutBuilder] for more information about /// how a layout builder should function. final PageTransitionSwitcherLayoutBuilder layoutBuilder; /// The default layout builder for [PageTransitionSwitcher]. /// /// This function is the default way for how the new and old child widgets are placed /// during the transition between the two widgets. All children are placed in a /// [Stack] that sizes itself to match the largest of the child or a previous child. /// The children are centered on each other. /// /// See [PageTransitionSwitcherTransitionBuilder] for more information on the function /// signature. static Widget defaultLayoutBuilder(List<Widget> entries) { return Stack( alignment: Alignment.center, children: entries, ); } @override State<PageTransitionSwitcher> createState() => _PageTransitionSwitcherState(); } class _PageTransitionSwitcherState extends State<PageTransitionSwitcher> with TickerProviderStateMixin { final List<_ChildEntry> _activeEntries = <_ChildEntry>[]; _ChildEntry? _currentEntry; int _childNumber = 0; @override void initState() { super.initState(); _addEntryForNewChild(shouldAnimate: false); } @override void didUpdateWidget(PageTransitionSwitcher oldWidget) { super.didUpdateWidget(oldWidget); // If the transition builder changed, then update all of the old // transitions. if (widget.transitionBuilder != oldWidget.transitionBuilder) { _activeEntries.forEach(_updateTransitionForEntry); } final bool hasNewChild = widget.child != null; final bool hasOldChild = _currentEntry != null; if (hasNewChild != hasOldChild || hasNewChild && !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) { // Child has changed, fade current entry out and add new entry. _childNumber += 1; _addEntryForNewChild(shouldAnimate: true); } else if (_currentEntry != null) { assert(hasOldChild && hasNewChild); assert(Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)); // Child has been updated. Make sure we update the child widget and // transition in _currentEntry even though we're not going to start a new // animation, but keep the key from the old transition so that we // update the transition instead of replacing it. _currentEntry!.widgetChild = widget.child!; _updateTransitionForEntry(_currentEntry!); // uses entry.widgetChild } } void _addEntryForNewChild({required bool shouldAnimate}) { assert(shouldAnimate || _currentEntry == null); if (_currentEntry != null) { assert(shouldAnimate); if (widget.reverse) { _currentEntry!.primaryController.reverse(); } else { _currentEntry!.secondaryController.forward(); } _currentEntry = null; } if (widget.child == null) { return; } final AnimationController primaryController = AnimationController( duration: widget.duration, vsync: this, ); final AnimationController secondaryController = AnimationController( duration: widget.duration, vsync: this, ); if (shouldAnimate) { if (widget.reverse) { primaryController.value = 1.0; secondaryController.value = 1.0; secondaryController.reverse(); } else { primaryController.forward(); } } else { assert(_activeEntries.isEmpty); primaryController.value = 1.0; } _currentEntry = _newEntry( child: widget.child!, primaryController: primaryController, secondaryController: secondaryController, builder: widget.transitionBuilder, ); if (widget.reverse && _activeEntries.isNotEmpty) { // Add below old child. _activeEntries.insert(_activeEntries.length - 1, _currentEntry!); } else { // Add on top of old child. _activeEntries.add(_currentEntry!); } } _ChildEntry _newEntry({ required Widget child, required PageTransitionSwitcherTransitionBuilder builder, required AnimationController primaryController, required AnimationController secondaryController, }) { final Widget transition = builder( child, primaryController, secondaryController, ); final _ChildEntry entry = _ChildEntry( widgetChild: child, transition: KeyedSubtree.wrap( transition, _childNumber, ), primaryController: primaryController, secondaryController: secondaryController, ); secondaryController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { assert(mounted); assert(_activeEntries.contains(entry)); setState(() { _activeEntries.remove(entry); entry.dispose(); }); } }); primaryController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.dismissed) { assert(mounted); assert(_activeEntries.contains(entry)); setState(() { _activeEntries.remove(entry); entry.dispose(); }); } }); return entry; } void _updateTransitionForEntry(_ChildEntry entry) { final Widget transition = widget.transitionBuilder( entry.widgetChild, entry.primaryController, entry.secondaryController, ); entry.transition = KeyedSubtree( key: entry.transition.key, child: transition, ); } @override void dispose() { for (final _ChildEntry entry in _activeEntries) { entry.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { return widget.layoutBuilder(_activeEntries .map<Widget>((_ChildEntry entry) => entry.transition) .toList()); } }
packages/packages/animations/lib/src/page_transition_switcher.dart/0
{ "file_path": "packages/packages/animations/lib/src/page_transition_switcher.dart", "repo_id": "packages", "token_count": 4856 }
947
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera; import android.annotation.TargetApi; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.SessionConfiguration; import android.os.Build; import android.os.Handler; import android.view.Surface; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.List; /** A mockable wrapper for CameraDevice calls. */ interface CameraDeviceWrapper { @NonNull CaptureRequest.Builder createCaptureRequest(int templateType) throws CameraAccessException; @TargetApi(Build.VERSION_CODES.P) void createCaptureSession(SessionConfiguration config) throws CameraAccessException; void createCaptureSession( @NonNull List<Surface> outputs, @NonNull CameraCaptureSession.StateCallback callback, @Nullable Handler handler) throws CameraAccessException; void close(); }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraDeviceWrapper.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraDeviceWrapper.java", "repo_id": "packages", "token_count": 323 }
948
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features; import android.app.Activity; import androidx.annotation.NonNull; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DartMessenger; import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature; import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature; import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature; import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature; import io.flutter.plugins.camera.features.flash.FlashFeature; import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature; import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature; import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionPreset; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature; /** * Implementation of the {@link CameraFeatureFactory} interface creating the supported feature * implementation controlling different aspects of the {@link * android.hardware.camera2.CaptureRequest}. */ public class CameraFeatureFactoryImpl implements CameraFeatureFactory { @NonNull @Override public AutoFocusFeature createAutoFocusFeature( @NonNull CameraProperties cameraProperties, boolean recordingVideo) { return new AutoFocusFeature(cameraProperties, recordingVideo); } @NonNull @Override public ExposureLockFeature createExposureLockFeature(@NonNull CameraProperties cameraProperties) { return new ExposureLockFeature(cameraProperties); } @NonNull @Override public ExposureOffsetFeature createExposureOffsetFeature( @NonNull CameraProperties cameraProperties) { return new ExposureOffsetFeature(cameraProperties); } @NonNull @Override public FlashFeature createFlashFeature(@NonNull CameraProperties cameraProperties) { return new FlashFeature(cameraProperties); } @NonNull @Override public ResolutionFeature createResolutionFeature( @NonNull CameraProperties cameraProperties, @NonNull ResolutionPreset initialSetting, @NonNull String cameraName) { return new ResolutionFeature(cameraProperties, initialSetting, cameraName); } @NonNull @Override public FocusPointFeature createFocusPointFeature( @NonNull CameraProperties cameraProperties, @NonNull SensorOrientationFeature sensorOrientationFeature) { return new FocusPointFeature(cameraProperties, sensorOrientationFeature); } @NonNull @Override public FpsRangeFeature createFpsRangeFeature(@NonNull CameraProperties cameraProperties) { return new FpsRangeFeature(cameraProperties); } @NonNull @Override public SensorOrientationFeature createSensorOrientationFeature( @NonNull CameraProperties cameraProperties, @NonNull Activity activity, @NonNull DartMessenger dartMessenger) { return new SensorOrientationFeature(cameraProperties, activity, dartMessenger); } @NonNull @Override public ZoomLevelFeature createZoomLevelFeature(@NonNull CameraProperties cameraProperties) { return new ZoomLevelFeature(cameraProperties); } @NonNull @Override public ExposurePointFeature createExposurePointFeature( @NonNull CameraProperties cameraProperties, @NonNull SensorOrientationFeature sensorOrientationFeature) { return new ExposurePointFeature(cameraProperties, sensorOrientationFeature); } @NonNull @Override public NoiseReductionFeature createNoiseReductionFeature( @NonNull CameraProperties cameraProperties) { return new NoiseReductionFeature(cameraProperties); } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactoryImpl.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactoryImpl.java", "repo_id": "packages", "token_count": 1130 }
949