text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
{ // See https://go.microsoft.com/fwlink/?LinkId=827846 // for the documentation about the extensions.json format "recommendations": [ "dart-code.dart-code", "dart-code.flutter", "felixangelov.bloc" ] }
io_flip/.vscode/extensions.json/0
{ "file_path": "io_flip/.vscode/extensions.json", "repo_id": "io_flip", "token_count": 90 }
825
import 'package:game_domain/game_domain.dart'; import 'package:mustache_template/mustache_template.dart'; const _template = ''' <img class="card-img" src="/public/cards/{{{card.id}}}" alt="{{card.name}}" > '''; /// Builds the HMTL page for the sare card link. String buildShareCardContent({required Card card}) { return Template(_template).renderString({ 'card': card.toJson(), }); }
io_flip/api/lib/templates/share_card_template.dart/0
{ "file_path": "io_flip/api/lib/templates/share_card_template.dart", "repo_id": "io_flip", "token_count": 168 }
826
export 'card.dart'; export 'card_description.dart'; export 'deck.dart'; export 'leaderboard_player.dart'; export 'match.dart'; export 'match_state.dart'; export 'prompt.dart'; export 'prompt_term.dart'; export 'score_card.dart'; export 'web_socket_message.dart';
io_flip/api/packages/game_domain/lib/src/models/models.dart/0
{ "file_path": "io_flip/api/packages/game_domain/lib/src/models/models.dart", "repo_id": "io_flip", "token_count": 97 }
827
// ignore_for_file: prefer_const_constructors import 'package:game_domain/game_domain.dart'; import 'package:test/test.dart'; void main() { group('MatchState', () { test('can be instantiated', () { expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNotNull, ); }); test('toJson returns the instance as json', () { expect( MatchState( id: 'id', matchId: 'matchId', guestPlayedCards: const ['1'], hostPlayedCards: const ['2'], result: MatchResult.host, ).toJson(), equals({ 'id': 'id', 'matchId': 'matchId', 'guestPlayedCards': ['1'], 'hostPlayedCards': ['2'], 'result': 'host', }), ); }); test('fromJson returns the correct instance', () { expect( MatchState.fromJson(const { 'id': 'id', 'matchId': 'matchId', 'guestPlayedCards': ['1'], 'hostPlayedCards': ['2'], 'result': 'host', }), equals( MatchState( id: 'id', matchId: 'matchId', guestPlayedCards: const ['1'], hostPlayedCards: const ['2'], result: MatchResult.host, ), ), ); }); test('supports equality', () { expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], result: MatchResult.host, ), equals( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], result: MatchResult.host, ), ), ); expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNot( equals( MatchState( id: '1', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), ), ), ); expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNot( equals( MatchState( id: '', matchId: '1', guestPlayedCards: const [], hostPlayedCards: const [], ), ), ), ); expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNot( equals( MatchState( id: '', matchId: '', guestPlayedCards: const ['1'], hostPlayedCards: const [], ), ), ), ); expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNot( equals( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const ['1'], ), ), ), ); expect( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), isNot( equals( MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], result: MatchResult.host, ), ), ), ); }); test( 'isOver return true when both players reach the correct ' 'amount of turns', () { final finishedMatchState = MatchState( id: '', matchId: '', hostPlayedCards: const ['', '', ''], guestPlayedCards: const ['', '', ''], ); final unfinishedMatchState = MatchState( id: '', matchId: '', hostPlayedCards: const ['', '', ''], guestPlayedCards: const ['', ''], ); expect(finishedMatchState.isOver(), isTrue); expect(unfinishedMatchState.isOver(), isFalse); }); test( 'addHostPlayedCard adds a new card to the host list ' 'in a new instance', () { expect( MatchState( id: '', matchId: '', hostPlayedCards: const [], guestPlayedCards: const [], ).addHostPlayedCard(''), equals( MatchState( id: '', matchId: '', hostPlayedCards: const [''], guestPlayedCards: const [], ), ), ); }); test( 'addGuestPlayedCard adds a new card to the guest list ' 'in a new instance', () { expect( MatchState( id: '', matchId: '', hostPlayedCards: const [], guestPlayedCards: const [], ).addGuestPlayedCard(''), equals( MatchState( id: '', matchId: '', hostPlayedCards: const [], guestPlayedCards: const [''], ), ), ); }); test('setResult sets the result', () { expect( MatchState( id: '', matchId: '', hostPlayedCards: const [], guestPlayedCards: const [], ).setResult(MatchResult.host), equals( MatchState( id: '', matchId: '', hostPlayedCards: const [], guestPlayedCards: const [], result: MatchResult.host, ), ), ); }); }); group('MatchResult', () { group('valueOf', () { test('can map host', () { expect(MatchResult.valueOf('host'), equals(MatchResult.host)); }); test('can map guest', () { expect(MatchResult.valueOf('guest'), equals(MatchResult.guest)); }); test('can map draw', () { expect(MatchResult.valueOf('draw'), equals(MatchResult.draw)); }); test('returns null when unknown', () { expect(MatchResult.valueOf('a'), isNull); }); test('returns null when null', () { expect(MatchResult.valueOf(null), isNull); }); }); }); }
io_flip/api/packages/game_domain/test/src/models/match_state_test.dart/0
{ "file_path": "io_flip/api/packages/game_domain/test/src/models/match_state_test.dart", "repo_id": "io_flip", "token_count": 3677 }
828
name: jwt_middleware description: A dart_frog middleware for checking JWT authorization. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: clock: ^1.1.1 dart_frog: ^0.3.0 equatable: ^2.0.5 http: ^0.13.5 jose: ^0.3.3 x509: ^0.2.3 dev_dependencies: mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^4.0.0
io_flip/api/packages/jwt_middleware/pubspec.yaml/0
{ "file_path": "io_flip/api/packages/jwt_middleware/pubspec.yaml", "repo_id": "io_flip", "token_count": 176 }
829
import 'package:db_client/db_client.dart'; import 'package:game_domain/game_domain.dart'; /// {@template leaderboard_repository} /// Access to Leaderboard datasource. /// {@endtemplate} class LeaderboardRepository { /// {@macro leaderboard_repository} const LeaderboardRepository({ required DbClient dbClient, required String blacklistDocumentId, }) : _dbClient = dbClient, _blacklistDocumentId = blacklistDocumentId; final DbClient _dbClient; final String _blacklistDocumentId; /// Retrieves the leaderboard players. /// /// The players are ordered by longest streak and returns the top 10. Future<List<LeaderboardPlayer>> getLeaderboard() async { final results = await _dbClient.orderBy('leaderboard', 'longestStreak'); return results .map( (e) => LeaderboardPlayer.fromJson({ 'id': e.id, ...e.data, }), ) .toList(); } /// Retrieves the blacklist for player initials. Future<List<String>> getInitialsBlacklist() async { final blacklistData = await _dbClient.getById( 'initials_blacklist', _blacklistDocumentId, ); if (blacklistData == null) { return []; } return (blacklistData.data['blacklist'] as List).cast<String>(); } /// Retrieves the score card where the longest streak deck matches /// the given [deckId]. Future<ScoreCard?> findScoreCardByLongestStreakDeck(String deckId) async { final results = await _dbClient.findBy( 'score_cards', 'longestStreakDeck', deckId, ); if (results.isEmpty) { return null; } return ScoreCard.fromJson({ 'id': results.first.id, ...results.first.data, }); } /// Retrieves the top score cards with the highest total wins. Future<List<ScoreCard>> getScoreCardsWithMostWins() async { final results = await _dbClient.orderBy('score_cards', 'wins'); return results .map( (e) => ScoreCard.fromJson({ 'id': e.id, ...e.data, }), ) .toList(); } /// Retrieves the top score cards with the longest streak. Future<List<ScoreCard>> getScoreCardsWithLongestStreak() async { final results = await _dbClient.orderBy('score_cards', 'longestStreak'); return results .map( (e) => ScoreCard.fromJson({ 'id': e.id, ...e.data, }), ) .toList(); } /// Adds the initials to the score card with the given [scoreCardId]. Future<void> addInitialsToScoreCard({ required String scoreCardId, required String initials, }) async { await _dbClient.update( 'score_cards', DbEntityRecord( id: scoreCardId, data: { 'initials': initials, }, ), ); } }
io_flip/api/packages/leaderboard_repository/lib/src/leaderboard_repository.dart/0
{ "file_path": "io_flip/api/packages/leaderboard_repository/lib/src/leaderboard_repository.dart", "repo_id": "io_flip", "token_count": 1139 }
830
name: prompt_repository description: Access to Prompt datasource. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: db_client: path: ../db_client game_domain: path: ../game_domain dev_dependencies: mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^3.1.0
io_flip/api/packages/prompt_repository/pubspec.yaml/0
{ "file_path": "io_flip/api/packages/prompt_repository/pubspec.yaml", "repo_id": "io_flip", "token_count": 139 }
831
import 'dart:async'; import 'dart:io'; import 'package:cards_repository/cards_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:prompt_repository/prompt_repository.dart'; FutureOr<Response> onRequest(RequestContext context) async { if (context.request.method == HttpMethod.post) { final cardsRepository = context.read<CardsRepository>(); final promptRepository = context.read<PromptRepository>(); final body = await context.request.json() as Map<String, dynamic>; final prompt = Prompt.fromJson(body); if (!await promptRepository.isValidPrompt(prompt)) { return Response(statusCode: HttpStatus.badRequest); } final characterClass = prompt.characterClass; if (characterClass == null) { return Response(statusCode: HttpStatus.badRequest); } final characterPower = prompt.power; if (characterPower == null) { return Response(statusCode: HttpStatus.badRequest); } final cards = await cardsRepository.generateCards( characterClass: characterClass, characterPower: characterPower, ); return Response.json( body: {'cards': cards.map((e) => e.toJson()).toList()}, ); } return Response(statusCode: HttpStatus.methodNotAllowed); }
io_flip/api/routes/game/cards/index.dart/0
{ "file_path": "io_flip/api/routes/game/cards/index.dart", "repo_id": "io_flip", "token_count": 456 }
832
import 'dart:async'; import 'dart:convert'; import 'package:dart_frog/dart_frog.dart'; import 'package:dart_frog_web_socket/dart_frog_web_socket.dart' as ws; import 'package:game_domain/game_domain.dart'; import 'package:match_repository/match_repository.dart'; import '../../main.dart'; typedef WebSocketHandlerFactory = Handler Function( void Function(ws.WebSocketChannel channel, String? protocol) onConnection, ); Future<Response> onRequest(RequestContext context) async { final matchRepository = context.read<MatchRepository>(); final webSocketHandlerFactory = context.read<WebSocketHandlerFactory>(); final handler = webSocketHandlerFactory((channel, protocol) { String? userId; String? matchId; var isHost = true; Future<void> setConnectivity({required bool connected}) async { if (userId != null) { await matchRepository.setPlayerConnectivity( userId: userId!, connected: connected, ); } } Future<void> setGameConnectivity({required bool connected}) async { if (matchId != null) { if (isHost) { await matchRepository.setHostConnectivity( match: matchId!, active: connected, ); } else { await matchRepository.setGuestConnectivity( match: matchId!, active: connected, ); } } } Future<void> handleMessage(WebSocketMessage message) async { if (message.messageType == MessageType.token) { final tokenPayload = message.payload! as WebSocketTokenPayload; final newUserId = await jwtMiddleware.verifyToken(tokenPayload.token); if (newUserId != userId) { if (userId != null) { // Disconnect the old user. await matchRepository.setPlayerConnectivity( userId: userId!, connected: false, ); } userId = newUserId; if (userId != null) { final isConnected = await matchRepository.getPlayerConnectivity( userId: userId!, ); if (isConnected && !tokenPayload.reconnect) { final message = WebSocketMessage.error( WebSocketErrorCode.playerAlreadyConnected, ); channel.sink.add(jsonEncode(message)); userId = null; } else if (!isConnected) { try { await setConnectivity(connected: true); channel.sink .add(jsonEncode(const WebSocketMessage.connected())); } catch (e) { channel.sink.add( jsonEncode( WebSocketMessage.error( WebSocketErrorCode.firebaseException, ), ), ); } } else if (isConnected) { channel.sink.add(jsonEncode(const WebSocketMessage.connected())); } } } } else { // All other message types require a user to already be authenticated. if (userId != null) { if (message.messageType == MessageType.matchJoined) { final matchJoinedPayload = message.payload! as WebSocketMatchJoinedPayload; await setGameConnectivity(connected: false); matchId = matchJoinedPayload.matchId; isHost = matchJoinedPayload.isHost; await setGameConnectivity(connected: true); channel.sink.add( jsonEncode( WebSocketMessage.matchJoined( isHost: isHost, matchId: matchId!, ), ), ); } else if (message.messageType == MessageType.matchLeft) { await setGameConnectivity(connected: false); matchId = null; } } } } channel.stream.listen( (data) async { if (data is String) { final decoded = jsonDecode(data); if (decoded is Map) { try { final message = WebSocketMessage.fromJson( Map<String, dynamic>.from(decoded), ); await handleMessage(message); } catch (e) { // ignore this message. } } } }, onDone: () { setConnectivity(connected: false); setGameConnectivity(connected: false); }, ); }); return handler(context); }
io_flip/api/routes/public/connect.dart/0
{ "file_path": "io_flip/api/routes/public/connect.dart", "repo_id": "io_flip", "token_count": 2186 }
833
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:logging/logging.dart'; import 'package:mocktail/mocktail.dart'; import 'package:scripts_repository/scripts_repository.dart'; import 'package:test/test.dart'; import '../../../../main.dart'; import '../../../../routes/game/scripts/[scriptId].dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockScriptsRepository extends Mock implements ScriptsRepository {} class _MockGameScriptMachine extends Mock implements GameScriptMachine {} class _MockRequest extends Mock implements Request {} class _MockLogger extends Mock implements Logger {} void main() { group('GET /game/scripts/[scriptId]', () { late ScriptsRepository scriptsRepository; late Request request; late RequestContext context; late Logger logger; setUp(() { scriptsRepository = _MockScriptsRepository(); when(scriptsRepository.getCurrentScript) .thenAnswer((_) async => 'script'); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.get); logger = _MockLogger(); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<ScriptsRepository>()) .thenReturn(scriptsRepository); when(() => context.read<Logger>()).thenReturn(logger); when(() => context.read<ScriptsState>()).thenReturn(ScriptsState.enabled); }); test('responds with a 200', () async { final response = await route.onRequest(context, 'current'); expect(response.statusCode, equals(HttpStatus.ok)); }); test('responds with a 404 if using the wrong id', () async { final response = await route.onRequest(context, ''); expect(response.statusCode, equals(HttpStatus.notFound)); }); test('responds with a not allowed when the wrong method', () async { when(() => request.method).thenReturn(HttpMethod.head); final response = await route.onRequest(context, ''); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('responds with the script', () async { final response = await route.onRequest(context, 'current'); final body = await response.body(); expect( body, equals('script'), ); }); }); group('PUT /scripts/[scriptId]', () { late ScriptsRepository scriptsRepository; late GameScriptMachine gameScriptMachine; late Request request; late RequestContext context; late Logger logger; setUp(() { scriptsRepository = _MockScriptsRepository(); gameScriptMachine = _MockGameScriptMachine(); when(() => scriptsRepository.updateCurrentScript(any())) .thenAnswer((_) async {}); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.put); when(request.body).thenAnswer((_) async => 'the script'); logger = _MockLogger(); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<ScriptsRepository>()) .thenReturn(scriptsRepository); when(() => context.read<Logger>()).thenReturn(logger); when(() => context.read<GameScriptMachine>()) .thenReturn(gameScriptMachine); when(() => context.read<ScriptsState>()).thenReturn(ScriptsState.enabled); }); test('responds with a 200', () async { final response = await route.onRequest(context, 'current'); expect(response.statusCode, equals(HttpStatus.noContent)); }); test('responds with a 404 if using the wrong id', () async { final response = await route.onRequest(context, ''); expect(response.statusCode, equals(HttpStatus.notFound)); }); test('responds with a not allowed when the wrong method', () async { when(() => request.method).thenReturn(HttpMethod.head); final response = await route.onRequest(context, ''); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('update the script on the db', () async { await route.onRequest(context, 'current'); verify(() => scriptsRepository.updateCurrentScript('the script')) .called(1); }); test('update the script in the current machine', () async { await route.onRequest(context, 'current'); verify(() => gameScriptMachine.currentScript = 'the script').called(1); }); test('responds with a 405 if scripts are not enabled', () async { when(() => context.read<ScriptsState>()) .thenReturn(ScriptsState.disabled); final response = await route.onRequest(context, 'current'); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); }
io_flip/api/test/routes/game/scripts/[scriptId]_test.dart/0
{ "file_path": "io_flip/api/test/routes/game/scripts/[scriptId]_test.dart", "repo_id": "io_flip", "token_count": 1689 }
834
// ignore_for_file: avoid_print import 'dart:io'; import 'package:csv/csv.dart'; import 'package:db_client/db_client.dart'; import 'package:game_domain/game_domain.dart'; /// {@template data_loader} /// Dart tool that feed descriptions into the Descriptions base /// {@endtemplate} class DescriptionsLoader { /// {@macro data_loader} const DescriptionsLoader({ required DbClient dbClient, required File csv, }) : _dbClient = dbClient, _csv = csv; final File _csv; final DbClient _dbClient; String _normalizeTerm(String term) { return term.trim().toLowerCase().replaceAll(' ', '_'); } /// Loads the descriptions from the CSV file into the database /// [onProgress] is called everytime there is progress, /// it takes in the current inserted and the total to insert. Future<void> loadDescriptions(void Function(int, int) onProgress) async { final descriptions = <CardDescription>[]; final content = await _csv.readAsString(); final lines = const CsvToListConverter().convert(content); for (final parts in lines.skip(1)) { final character = _normalizeTerm( parts[0] as String, ); final characterClass = _normalizeTerm( parts[1] as String, ); final power = _normalizeTerm( parts[2] as String, ); final location = _normalizeTerm( parts[3] as String, ); for (var i = 4; i < parts.length; i++) { final value = parts[i] as String; if (value.trim().isEmpty) { continue; } descriptions.add( CardDescription( character: character, characterClass: characterClass, power: power, location: location, description: value, ), ); } } var progress = 0; onProgress(progress, descriptions.length); for (final description in descriptions) { progress++; try { await _dbClient.add( 'card_descriptions', description.toJson(), ); } catch (e) { print('Failed'); print(e); } // So we don't get rate limited await Future<void>.delayed(const Duration(milliseconds: 5)); onProgress(progress, descriptions.length); } } }
io_flip/api/tools/data_loader/lib/src/descriptions_loader.dart/0
{ "file_path": "io_flip/api/tools/data_loader/lib/src/descriptions_loader.dart", "repo_id": "io_flip", "token_count": 925 }
835
import 'package:flop/flop/flop.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FlopPage extends StatelessWidget { const FlopPage({ super.key, required this.setAppCheckDebugToken, required this.reload, }); final void Function(String) setAppCheckDebugToken; final void Function() reload; @override Widget build(BuildContext context) { return BlocProvider<FlopBloc>( create: (_) => FlopBloc( setAppCheckDebugToken: setAppCheckDebugToken, reload: reload, )..add(const NextStepRequested()), child: const FlopView(), ); } }
io_flip/flop/lib/flop/view/flop_page.dart/0
{ "file_path": "io_flip/flop/lib/flop/view/flop_page.dart", "repo_id": "io_flip", "token_count": 242 }
836
{ "name": "functions", "scripts": { "lint": "eslint --ext .js,.ts .", "build": "tsc", "build:watch": "tsc --watch", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log", "test": "ts-mocha --reporter spec test/**/*.ts" }, "engines": { "node": "18" }, "main": "lib/index.js", "dependencies": { "firebase-admin": "^11.5.0", "firebase-functions": "^4.2.0" }, "devDependencies": { "@types/chai": "^4.3.5", "@types/mocha": "^10.0.1", "@types/sinon": "^10.0.14", "@typescript-eslint/eslint-plugin": "^5.12.0", "@typescript-eslint/parser": "^5.12.0", "chai": "^4.3.7", "eslint": "^8.9.0", "eslint-config-google": "^0.14.0", "eslint-plugin-import": "^2.25.4", "firebase-functions-test": "^3.1.0", "mocha": "^10.2.0", "sinon": "^15.0.4", "ts-mocha": "^10.0.0", "typescript": "^4.9.0" }, "private": true }
io_flip/functions/package.json/0
{ "file_path": "io_flip/functions/package.json", "repo_id": "io_flip", "token_count": 545 }
837
export 'audio_button.dart';
io_flip/lib/audio/widgets/widgets.dart/0
{ "file_path": "io_flip/lib/audio/widgets/widgets.dart", "repo_id": "io_flip", "token_count": 10 }
838
import 'dart:math' as math; import 'package:flame/cache.dart'; import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class DeckPack extends StatefulWidget { const DeckPack({ required this.child, required this.onComplete, required this.size, this.deviceInfoAware = deviceInfoAwareAsset, super.key, }); final Widget child; final Size size; final VoidCallback onComplete; final DeviceInfoAwareAsset<Widget> deviceInfoAware; @override State<DeckPack> createState() => DeckPackState(); } @visibleForTesting class DeckPackState extends State<DeckPack> { Widget? _deckPackAnimation; bool _underlayVisible = false; bool _isAnimationComplete = false; @override void initState() { super.initState(); widget .deviceInfoAware( predicate: isAndroid, asset: () => AnimatedDeckPack( onComplete: onComplete, onUnderlayVisible: onUnderlayVisible, ), orElse: () => SpriteAnimationDeckPack( onComplete: onComplete, onUnderlayVisible: onUnderlayVisible, ), ) .then((widget) { setState(() { _deckPackAnimation = widget; }); }); } void onComplete() { widget.onComplete(); setState(() { _isAnimationComplete = true; }); } void onUnderlayVisible() { setState(() { _underlayVisible = true; }); context.read<AudioController>().playSfx(Assets.sfx.deckOpen); } @override Widget build(BuildContext context) { return SizedBox.fromSize( size: widget.size, child: Center( child: Stack( alignment: Alignment.bottomCenter, children: [ if (_isAnimationComplete) widget.child else AspectRatio( // Aspect ratio of card aspectRatio: widget.size.aspectRatio, child: Offstage( offstage: !_underlayVisible, child: StretchAnimation( animating: _underlayVisible, child: Center(child: widget.child), ), ), ), if (!_isAnimationComplete && _deckPackAnimation != null) _deckPackAnimation!, ], ), ), ); } } @visibleForTesting class AnimatedDeckPack extends StatefulWidget { const AnimatedDeckPack({ required this.onComplete, required this.onUnderlayVisible, super.key, }); final VoidCallback onComplete; final VoidCallback onUnderlayVisible; @override State<AnimatedDeckPack> createState() => AnimatedDeckPackState(); } @visibleForTesting class AnimatedDeckPackState extends State<AnimatedDeckPack> with SingleTickerProviderStateMixin { late AnimationController _controller; var _underlayVisibleCalled = false; final animatable = TweenSequence<Matrix4>([ TweenSequenceItem( tween: TransformTween( beginScale: 0.5, beginTranslateZ: 300, beginRotateY: -math.pi, ), weight: 0.25, ), for (var i = 0; i < 5; i++) ...[ TweenSequenceItem( tween: TransformTween( endRotateZ: -math.pi / 60 - (i * math.pi / 60), ), weight: 0.15 - i * 0.01, ), TweenSequenceItem( tween: TransformTween( endRotateZ: math.pi / 60 + (i * math.pi / 60), ), weight: 0.15 - i * 0.01, ), ], TweenSequenceItem( tween: TransformTween( endTranslateZ: -300, endRotateX: math.pi / 4, ), weight: 0.3, ), ]); @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(seconds: 1), ) ..addListener(() { if (!_underlayVisibleCalled && _controller.value > 0.95) { widget.onUnderlayVisible(); setState(() { _underlayVisibleCalled = true; }); } }) ..addStatusListener((status) { if (status == AnimationStatus.completed) { widget.onComplete(); } }) ..forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, child) { return Transform( transform: animatable.evaluate(_controller), alignment: Alignment.center, child: child, ); }, child: AnimatedOpacity( duration: const Duration(milliseconds: 100), opacity: _underlayVisibleCalled ? 0 : 1, child: Assets.images.mobile.deckPackStill.image(), ), ); } } @visibleForTesting class SpriteAnimationDeckPack extends StatefulWidget { const SpriteAnimationDeckPack({ required this.onComplete, required this.onUnderlayVisible, super.key, }); final VoidCallback onComplete; final VoidCallback onUnderlayVisible; @override State<SpriteAnimationDeckPack> createState() => SpriteAnimationDeckPackState(); } @visibleForTesting class SpriteAnimationDeckPackState extends State<SpriteAnimationDeckPack> { late final Images images; final asset = platformAwareAsset( desktop: Assets.images.desktop.frontPack.keyName, mobile: Assets.images.mobile.frontPack.keyName, ); Widget? anim; @override void initState() { super.initState(); images = context.read<Images>(); setupAnimation(); } @override void dispose() { images.clear(asset); super.dispose(); } Future<void> setupAnimation() async { final data = SpriteAnimationData.sequenced( amount: 56, amountPerRow: platformAwareAsset(desktop: 7, mobile: 8), textureSize: platformAwareAsset( desktop: Vector2(1050, 1219), mobile: Vector2(750, 871), ), stepTime: 0.04, loop: false, ); await SpriteAnimation.load( asset, data, images: images, ).then((animation) { if (!mounted) return; final ticker = animation.ticker() ..onFrame = onFrame ..completed.then((_) => widget.onComplete()); setState(() { anim = SpriteAnimationWidget( animation: animation, animationTicker: ticker, ); }); }); } void onFrame(int currentFrame) { if (currentFrame == 29) { widget.onUnderlayVisible(); } } @override Widget build(BuildContext context) { if (anim == null) return const SizedBox.shrink(); return LayoutBuilder( builder: (context, constraints) { // The shrink is here to "hide" the size of the deck pack // animation as we want the DeckPack to size to the card and // not the animation size. return SizedBox.shrink( child: OverflowBox( maxWidth: constraints.maxWidth / 0.272, maxHeight: constraints.maxHeight / 0.344, child: Transform.translate( offset: Offset(0, constraints.maxHeight * 0.16), child: Center( child: AspectRatio( // Aspect ratio of texture aspectRatio: 1050 / 1219, child: SizedBox.expand(child: anim), ), ), ), ), ); }, ); } }
io_flip/lib/draft/widgets/deck_pack.dart/0
{ "file_path": "io_flip/lib/draft/widgets/deck_pack.dart", "repo_id": "io_flip", "token_count": 3339 }
839
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** import 'package:flutter/services.dart'; // 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'; class $AssetsIconsGen { const $AssetsIconsGen(); /// File path: assets/icons/cancel.svg SvgGenImage get cancel => const SvgGenImage('assets/icons/cancel.svg'); /// File path: assets/icons/info.svg SvgGenImage get info => const SvgGenImage('assets/icons/info.svg'); /// List of all assets List<SvgGenImage> get values => [cancel, info]; } class $AssetsImagesGen { const $AssetsImagesGen(); $AssetsImagesDesktopGen get desktop => const $AssetsImagesDesktopGen(); /// File path: assets/images/download.png AssetGenImage get download => const AssetGenImage('assets/images/download.png'); /// File path: assets/images/facebook.png AssetGenImage get facebook => const AssetGenImage('assets/images/facebook.png'); /// File path: assets/images/google.png AssetGenImage get google => const AssetGenImage('assets/images/google.png'); $AssetsImagesLeaderboardGen get leaderboard => const $AssetsImagesLeaderboardGen(); $AssetsImagesMobileGen get mobile => const $AssetsImagesMobileGen(); /// File path: assets/images/temp_preferences_custom.png AssetGenImage get tempPreferencesCustom => const AssetGenImage('assets/images/temp_preferences_custom.png'); /// File path: assets/images/twitter.png AssetGenImage get twitter => const AssetGenImage('assets/images/twitter.png'); /// List of all assets List<AssetGenImage> get values => [download, facebook, tempPreferencesCustom, twitter]; } class $AssetsMusicGen { const $AssetsMusicGen(); /// File path: assets/music/GoogleIO-GameMusic-JN-TimeToRumble-JN-Rev1-Ext-LOOPEDonce.mp3 String get googleIOGameMusicJNTimeToRumbleJNRev1ExtLOOPEDonce => 'assets/music/GoogleIO-GameMusic-JN-TimeToRumble-JN-Rev1-Ext-LOOPEDonce.mp3'; /// File path: assets/music/README.md String get readme => 'assets/music/README.md'; /// List of all assets List<String> get values => [googleIOGameMusicJNTimeToRumbleJNRev1ExtLOOPEDonce, readme]; } class $AssetsSfxGen { const $AssetsSfxGen(); /// File path: assets/sfx/add_to_hand.mp3 String get addToHand => 'assets/sfx/add_to_hand.mp3'; /// File path: assets/sfx/air.mp3 String get air => 'assets/sfx/air.mp3'; /// File path: assets/sfx/arena_ambiance.mp3 String get arenaAmbiance => 'assets/sfx/arena_ambiance.mp3'; /// File path: assets/sfx/card_movement.mp3 String get cardMovement => 'assets/sfx/card_movement.mp3'; /// File path: assets/sfx/click.mp3 String get click => 'assets/sfx/click.mp3'; /// File path: assets/sfx/clock_running.mp3 String get clockRunning => 'assets/sfx/clock_running.mp3'; /// File path: assets/sfx/deck_open.mp3 String get deckOpen => 'assets/sfx/deck_open.mp3'; /// File path: assets/sfx/draw_match.mp3 String get drawMatch => 'assets/sfx/draw_match.mp3'; /// File path: assets/sfx/earth.mp3 String get earth => 'assets/sfx/earth.mp3'; /// File path: assets/sfx/fire.mp3 String get fire => 'assets/sfx/fire.mp3'; /// File path: assets/sfx/flip.mp3 String get flip => 'assets/sfx/flip.mp3'; /// File path: assets/sfx/holo_reveal.mp3 String get holoReveal => 'assets/sfx/holo_reveal.mp3'; /// File path: assets/sfx/lost_match.mp3 String get lostMatch => 'assets/sfx/lost_match.mp3'; /// File path: assets/sfx/match_seaching.mp3 String get matchSeaching => 'assets/sfx/match_seaching.mp3'; /// File path: assets/sfx/metal.mp3 String get metal => 'assets/sfx/metal.mp3'; /// File path: assets/sfx/play_card.mp3 String get playCard => 'assets/sfx/play_card.mp3'; /// File path: assets/sfx/start_game.mp3 String get startGame => 'assets/sfx/start_game.mp3'; /// File path: assets/sfx/water.mp3 String get water => 'assets/sfx/water.mp3'; /// File path: assets/sfx/win_match.mp3 String get winMatch => 'assets/sfx/win_match.mp3'; /// List of all assets List<String> get values => [ addToHand, air, arenaAmbiance, cardMovement, click, clockRunning, deckOpen, drawMatch, earth, fire, flip, holoReveal, lostMatch, matchSeaching, metal, playCard, startGame, water, winMatch ]; } class $AssetsImagesDesktopGen { const $AssetsImagesDesktopGen(); /// File path: assets/images/desktop/card_master.png AssetGenImage get cardMaster => const AssetGenImage('assets/images/desktop/card_master.png'); /// File path: assets/images/desktop/draw_splash.png AssetGenImage get drawSplash => const AssetGenImage('assets/images/desktop/draw_splash.png'); /// File path: assets/images/desktop/front_pack.png AssetGenImage get frontPack => const AssetGenImage('assets/images/desktop/front_pack.png'); /// File path: assets/images/desktop/loss_splash.png AssetGenImage get lossSplash => const AssetGenImage('assets/images/desktop/loss_splash.png'); /// File path: assets/images/desktop/main.jpg AssetGenImage get main => const AssetGenImage('assets/images/desktop/main.jpg'); /// File path: assets/images/desktop/stadium_background.png AssetGenImage get stadiumBackground => const AssetGenImage('assets/images/desktop/stadium_background.png'); /// File path: assets/images/desktop/stadium_background_close_up.png AssetGenImage get stadiumBackgroundCloseUp => const AssetGenImage( 'assets/images/desktop/stadium_background_close_up.png'); /// File path: assets/images/desktop/win_splash.png AssetGenImage get winSplash => const AssetGenImage('assets/images/desktop/win_splash.png'); /// List of all assets List<AssetGenImage> get values => [ cardMaster, drawSplash, frontPack, lossSplash, main, stadiumBackground, stadiumBackgroundCloseUp, winSplash ]; } class $AssetsImagesLeaderboardGen { const $AssetsImagesLeaderboardGen(); /// File path: assets/images/leaderboard/num1.png AssetGenImage get num1 => const AssetGenImage('assets/images/leaderboard/num1.png'); /// File path: assets/images/leaderboard/num2.png AssetGenImage get num2 => const AssetGenImage('assets/images/leaderboard/num2.png'); /// File path: assets/images/leaderboard/num3.png AssetGenImage get num3 => const AssetGenImage('assets/images/leaderboard/num3.png'); /// List of all assets List<AssetGenImage> get values => [num1, num2, num3]; } class $AssetsImagesMobileGen { const $AssetsImagesMobileGen(); /// File path: assets/images/mobile/card_master.png AssetGenImage get cardMaster => const AssetGenImage('assets/images/mobile/card_master.png'); /// File path: assets/images/mobile/card_master_still.png AssetGenImage get cardMasterStill => const AssetGenImage('assets/images/mobile/card_master_still.png'); /// File path: assets/images/mobile/deck_pack_still.png AssetGenImage get deckPackStill => const AssetGenImage('assets/images/mobile/deck_pack_still.png'); /// File path: assets/images/mobile/draw.svg SvgGenImage get draw => const SvgGenImage('assets/images/mobile/draw.svg'); /// File path: assets/images/mobile/front_pack.png AssetGenImage get frontPack => const AssetGenImage('assets/images/mobile/front_pack.png'); /// File path: assets/images/mobile/loss.svg SvgGenImage get loss => const SvgGenImage('assets/images/mobile/loss.svg'); /// File path: assets/images/mobile/main.jpg AssetGenImage get main => const AssetGenImage('assets/images/mobile/main.jpg'); /// File path: assets/images/mobile/stadium_background.png AssetGenImage get stadiumBackground => const AssetGenImage('assets/images/mobile/stadium_background.png'); /// File path: assets/images/mobile/stadium_background_close_up.png AssetGenImage get stadiumBackgroundCloseUp => const AssetGenImage( 'assets/images/mobile/stadium_background_close_up.png'); /// File path: assets/images/mobile/win.svg SvgGenImage get win => const SvgGenImage('assets/images/mobile/win.svg'); /// List of all assets List<dynamic> get values => [ cardMaster, cardMasterStill, deckPackStill, draw, frontPack, loss, main, stadiumBackground, stadiumBackgroundCloseUp, win ]; } class Assets { Assets._(); static const $AssetsIconsGen icons = $AssetsIconsGen(); static const $AssetsImagesGen images = $AssetsImagesGen(); static const $AssetsMusicGen music = $AssetsMusicGen(); static const $AssetsSfxGen sfx = $AssetsSfxGen(); } 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, 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, }) { return AssetImage( _assetName, bundle: bundle, package: package, ); } String get path => _assetName; String get keyName => _assetName; } class SvgGenImage { const SvgGenImage(this._assetName); final String _assetName; SvgPicture svg({ Key? key, bool matchTextDirection = false, AssetBundle? bundle, String? package, 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 => _assetName; }
io_flip/lib/gen/assets.gen.dart/0
{ "file_path": "io_flip/lib/gen/assets.gen.dart", "repo_id": "io_flip", "token_count": 4426 }
840
export 'info_button.dart';
io_flip/lib/info/widgets/widgets.dart/0
{ "file_path": "io_flip/lib/info/widgets/widgets.dart", "repo_id": "io_flip", "token_count": 10 }
841
import 'package:flutter/material.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class LeaderboardPlayers extends StatelessWidget { const LeaderboardPlayers({ required this.players, super.key, }); final List<LeaderboardPlayer> players; @override Widget build(BuildContext context) { final topPlayers = players.length >= 3 ? players.sublist(0, 3) : players; final restPlayers = players.length >= 3 ? players.sublist(3) : <LeaderboardPlayer>[]; return Column( children: [ for (final player in topPlayers) ...[ const SizedBox(height: IoFlipSpacing.md), player, ], if (restPlayers.isNotEmpty) ...[ const Divider( thickness: 2, color: IoFlipColors.seedGrey30, ), ], for (final player in restPlayers) ...[ player, const SizedBox(height: IoFlipSpacing.md), ], ], ); } } class LeaderboardPlayer extends StatelessWidget { const LeaderboardPlayer({ required this.index, required this.initials, required this.value, super.key, }); final int index; final String initials; final int value; @override Widget build(BuildContext context) { var color = Colors.transparent; Widget number = Text( (index + 1).toString(), style: IoFlipTextStyles.cardNumberXS, ); switch (index) { case 0: color = IoFlipColors.seedGold; number = Assets.images.leaderboard.num1.image(); break; case 1: color = IoFlipColors.seedSilver; number = Assets.images.leaderboard.num2.image(); break; case 2: color = IoFlipColors.seedBronze; number = Assets.images.leaderboard.num3.image(); break; } return Padding( padding: const EdgeInsets.symmetric(horizontal: IoFlipSpacing.sm), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( width: 24, height: 24, alignment: Alignment.center, decoration: BoxDecoration( color: color, shape: BoxShape.circle, ), child: number, ), const SizedBox(width: IoFlipSpacing.xlg), Text(initials, style: IoFlipTextStyles.headlineH6), ], ), Text( value.toString(), style: IoFlipTextStyles.buttonLG, ), ], ), ); } }
io_flip/lib/leaderboard/widgets/leaderboard_players.dart/0
{ "file_path": "io_flip/lib/leaderboard/widgets/leaderboard_players.dart", "repo_id": "io_flip", "token_count": 1267 }
842
part of 'prompt_form_bloc.dart'; enum PromptTermsStatus { initial, loading, loaded, failed } class PromptFormState extends Equatable { const PromptFormState({ required this.status, required this.prompts, this.characterClasses = const [], this.powers = const [], }); const PromptFormState.initial() : this( status: PromptTermsStatus.initial, prompts: const Prompt(), characterClasses: const [], powers: const [], ); final PromptTermsStatus status; final Prompt prompts; final List<String> characterClasses; final List<String> powers; PromptFormState copyWith({ PromptTermsStatus? status, Prompt? prompts, List<String>? characterClasses, List<String>? powers, }) { return PromptFormState( status: status ?? this.status, prompts: prompts ?? this.prompts, characterClasses: characterClasses ?? this.characterClasses, powers: powers ?? this.powers, ); } @override List<Object> get props => [status, prompts, characterClasses, powers]; }
io_flip/lib/prompt/bloc/prompt_form_state.dart/0
{ "file_path": "io_flip/lib/prompt/bloc/prompt_form_state.dart", "repo_id": "io_flip", "token_count": 386 }
843
import 'package:code_text_field/code_text_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_highlight/themes/monokai-sublime.dart'; import 'package:highlight/languages/javascript.dart'; import 'package:io_flip/scripts/cubit/scripts_cubit.dart'; import 'package:io_flip/style/snack_bar.dart'; class ScriptsView extends StatefulWidget { const ScriptsView({super.key}); @override State<ScriptsView> createState() => _ScriptsViewState(); } class _ScriptsViewState extends State<ScriptsView> { late CodeController _codeController; @override void initState() { super.initState(); _codeController = CodeController( language: javascript, text: context.read<ScriptsCubit>().state.current, ); } @override void dispose() { _codeController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return BlocConsumer<ScriptsCubit, ScriptsState>( listener: (context, state) { if (state.status == ScriptsStateStatus.failed) { showSnackBar('Failed to update script'); } }, builder: (context, state) { final isLoading = state.status == ScriptsStateStatus.loading; return CodeTheme( data: const CodeThemeData(styles: monokaiSublimeTheme), child: Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 80, child: isLoading ? const CircularProgressIndicator() : IconButton( icon: const Icon(Icons.save), onPressed: () { context .read<ScriptsCubit>() .updateScript(_codeController.text); }, ), ), Expanded( child: SingleChildScrollView( child: CodeField(controller: _codeController), ), ), ], ), ), ); }, ); } }
io_flip/lib/scripts/views/scripts_view.dart/0
{ "file_path": "io_flip/lib/scripts/views/scripts_view.dart", "repo_id": "io_flip", "token_count": 1119 }
844
export 'card_inspector_dialog.dart'; export 'share_card_dialog.dart'; export 'share_hand_dialog.dart'; export 'share_hand_page.dart';
io_flip/lib/share/views/views.dart/0
{ "file_path": "io_flip/lib/share/views/views.dart", "repo_id": "io_flip", "token_count": 53 }
845
import 'dart:convert'; import 'dart:io'; import 'package:api_client/api_client.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'; class _MockApiClient extends Mock implements ApiClient {} class _MockResponse extends Mock implements http.Response {} void main() { group('LeaderboardResource', () { late ApiClient apiClient; late http.Response response; late LeaderboardResource resource; setUp(() { apiClient = _MockApiClient(); response = _MockResponse(); resource = LeaderboardResource(apiClient: apiClient); }); group('getLeaderboardResults', () { setUp(() { when(() => apiClient.get(any())).thenAnswer((_) async => response); }); test('makes the correct call ', () async { const leaderboardPlayer = LeaderboardPlayer( id: 'id', longestStreak: 1, initials: 'TST', ); when(() => response.statusCode).thenReturn(HttpStatus.ok); when(() => response.body).thenReturn( jsonEncode( { 'leaderboardPlayers': [leaderboardPlayer.toJson()], }, ), ); final results = await resource.getLeaderboardResults(); expect(results, equals([leaderboardPlayer])); }); test('throws ApiClientError when request fails', () async { when(() => response.statusCode) .thenReturn(HttpStatus.internalServerError); when(() => response.body).thenReturn('Oops'); await expectLater( resource.getLeaderboardResults, throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET /leaderboard/results returned status 500 with the following response: "Oops"', ), ), ), ); }); test('throws ApiClientError when request response is invalid', () async { when(() => response.statusCode).thenReturn(HttpStatus.ok); when(() => response.body).thenReturn('Oops'); await expectLater( resource.getLeaderboardResults, throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET /leaderboard/results returned invalid response "Oops"', ), ), ), ); }); }); group('getInitialsBlacklist', () { setUp(() { when(() => apiClient.get(any())).thenAnswer((_) async => response); }); test('gets initials blacklist', () async { const blacklist = ['WTF']; when(() => response.statusCode).thenReturn(HttpStatus.ok); when(() => response.body).thenReturn(jsonEncode({'list': blacklist})); final result = await resource.getInitialsBlacklist(); expect(result, equals(blacklist)); }); test('gets empty blacklist if endpoint not found', () async { const emptyList = <String>[]; when(() => response.statusCode).thenReturn(HttpStatus.notFound); final result = await resource.getInitialsBlacklist(); expect(result, equals(emptyList)); }); test('throws ApiClientError when request fails', () async { when(() => response.statusCode) .thenReturn(HttpStatus.internalServerError); when(() => response.body).thenReturn('Oops'); await expectLater( resource.getInitialsBlacklist, throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET /leaderboard/initials_blacklist returned status 500 with the following response: "Oops"', ), ), ), ); }); test('throws ApiClientError when request response is invalid', () async { when(() => response.statusCode).thenReturn(HttpStatus.ok); when(() => response.body).thenReturn('Oops'); await expectLater( resource.getInitialsBlacklist, throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET /leaderboard/initials_blacklist returned invalid response "Oops"', ), ), ), ); }); }); group('addInitialsToScoreCard', () { const scoreCardId = 'scoreCardId'; const initials = 'initials'; setUp(() { when(() => apiClient.post(any(), body: any(named: 'body'))) .thenAnswer((_) async => response); }); test('makes the correct call', () async { when(() => response.statusCode).thenReturn(HttpStatus.noContent); await resource.addInitialsToScoreCard( scoreCardId: scoreCardId, initials: initials, ); verify( () => apiClient.post( '/game/leaderboard/initials', body: jsonEncode({ 'scoreCardId': scoreCardId, 'initials': initials, }), ), ).called(1); }); test('throws ApiClientError when request fails', () async { when(() => response.statusCode) .thenReturn(HttpStatus.internalServerError); when(() => response.body).thenReturn('Oops'); await expectLater( () => resource.addInitialsToScoreCard( scoreCardId: scoreCardId, initials: initials, ), throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'POST /leaderboard/initials returned status 500 with the following response: "Oops"', ), ), ), ); }); }); }); }
io_flip/packages/api_client/test/src/resources/leaderboard_resource_test.dart/0
{ "file_path": "io_flip/packages/api_client/test/src/resources/leaderboard_resource_test.dart", "repo_id": "io_flip", "token_count": 2737 }
846
import 'package:flame/cache.dart'; import 'package:flutter/material.dart' hide Element; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:provider/provider.dart'; class AllElementsStory extends StatefulWidget { const AllElementsStory({super.key}); @override State<AllElementsStory> createState() => _AllElementsStoryState(); } class _AllElementsStoryState extends State<AllElementsStory> { @override Widget build(BuildContext context) { return Provider( create: (_) => Images(prefix: ''), child: StoryScaffold( title: 'All Elements', body: Padding( padding: const EdgeInsets.all(IoFlipSpacing.xxxlg), child: Wrap( spacing: IoFlipSpacing.xxxlg, runSpacing: IoFlipSpacing.xxxlg, children: [ for (final element in Element.values) _ElementalDamageGroup( key: ValueKey( DamageDirection.bottomToTop.name + element.name, ), direction: DamageDirection.bottomToTop, element: element, ), for (final element in Element.values) _ElementalDamageGroup( key: ValueKey( DamageDirection.topToBottom.name + element.name, ), direction: DamageDirection.topToBottom, element: element, ), ], ), ), ), ); } } class _ElementalDamageGroup extends StatelessWidget { const _ElementalDamageGroup({ super.key, required this.element, required this.direction, }); final Element element; final DamageDirection direction; @override Widget build(BuildContext context) { final card1 = GameCard( image: 'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media', name: 'Dash the Great', description: 'The best Dash in all the Dashland', suitName: element.name, power: 57, size: const GameCardSize.xs(), isRare: false, ); const card2 = GameCard( image: 'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media', name: 'Dash the Great', description: 'The best Dash in all the Dashland', suitName: 'earth', power: 57, size: GameCardSize.xs(), isRare: false, ); return SizedBox( width: 175, height: 300, child: Stack( children: [ Positioned( top: 0, left: 0, child: direction == DamageDirection.topToBottom ? card1 : card2, ), Positioned( bottom: 0, right: 0, child: direction == DamageDirection.topToBottom ? card2 : card1, ), Positioned( top: 0, left: 0, bottom: 0, right: 0, child: ElementalDamageAnimation( element, direction: direction, initialState: DamageAnimationState.charging, size: const GameCardSize.xs(), assetSize: AssetSize.small, onComplete: () {}, ), ), ], ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/widgets/all_elements_story.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/lib/widgets/all_elements_story.dart", "repo_id": "io_flip", "token_count": 1664 }
847
name: gallery description: Gallery project to showcase app_ui version: 0.0.1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: dashbook: ^0.1.11 flame: git: url: https://github.com/willhlas/flame path: packages/flame ref: main flutter: sdk: flutter intl: ^0.17.0 io_flip_ui: path: ../ provider: ^6.0.5 dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^3.1.0 flutter: uses-material-design: true
io_flip/packages/io_flip_ui/gallery/pubspec.yaml/0
{ "file_path": "io_flip/packages/io_flip_ui/gallery/pubspec.yaml", "repo_id": "io_flip", "token_count": 235 }
848
import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; /// {@template earth_damage} // ignore: comment_references /// A widget that renders several [SpriteAnimation]s for the damages /// of a card on another. /// {@endtemplate} class EarthDamage extends ElementalDamage { /// {@macro earth_damage} EarthDamage({required super.size}) : super( chargeBackPath: Assets.images.elements.desktop.earth.chargeBack.keyName, chargeFrontPath: Assets.images.elements.desktop.earth.chargeFront.keyName, damageReceivePath: Assets.images.elements.desktop.earth.damageReceive.keyName, damageSendPath: Assets.images.elements.desktop.earth.damageSend.keyName, victoryChargeBackPath: Assets.images.elements.desktop.earth.victoryChargeBack.keyName, victoryChargeFrontPath: Assets.images.elements.desktop.earth.victoryChargeFront.keyName, badgePath: Assets.images.suits.card.earth.keyName, animationColor: IoFlipColors.seedRed, ); }
io_flip/packages/io_flip_ui/lib/src/animations/damages/earth_damage.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/animations/damages/earth_damage.dart", "repo_id": "io_flip", "token_count": 467 }
849
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; /// {@template io_flip_theme} /// IO FLIP theme. /// {@endtemplate} class IoFlipTheme { /// [ThemeData] for IO FLIP. static ThemeData get themeData { return ThemeData( useMaterial3: true, colorScheme: _colorScheme, textTheme: _textTheme.apply( bodyColor: IoFlipColors.seedWhite, displayColor: IoFlipColors.seedWhite, decorationColor: IoFlipColors.seedWhite, ), tabBarTheme: _tabBarTheme, dialogTheme: _dialogTheme, bottomNavigationBarTheme: _bottomNavigationBarTheme, ); } static ColorScheme get _colorScheme { return ColorScheme.fromSeed( seedColor: IoFlipColors.seedBlue, background: IoFlipColors.seedBlack, ); } static TextTheme get _textTheme { final isMobile = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; return isMobile ? IoFlipTextStyles.mobile.textTheme : IoFlipTextStyles.desktop.textTheme; } static TabBarTheme get _tabBarTheme { const yellow = IoFlipColors.seedYellow; const grey = IoFlipColors.seedGrey50; return const TabBarTheme( labelColor: yellow, indicatorColor: yellow, unselectedLabelColor: grey, dividerColor: grey, indicator: UnderlineTabIndicator( borderSide: BorderSide(color: yellow), ), ); } static DialogTheme get _dialogTheme { const black = IoFlipColors.seedBlack; return const DialogTheme( backgroundColor: black, surfaceTintColor: Colors.transparent, ); } static BottomNavigationBarThemeData get _bottomNavigationBarTheme { return const BottomNavigationBarThemeData( backgroundColor: Colors.transparent, ); } }
io_flip/packages/io_flip_ui/lib/src/theme/io_flip_theme.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/theme/io_flip_theme.dart", "repo_id": "io_flip", "token_count": 715 }
850
import 'package:flutter/material.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; /// {@template fading_dot_indicator} /// A loading indicator with 3 fading dots. /// {@endtemplate} class FadingDotLoader extends StatefulWidget { /// {@macro fading_dot_indicator} const FadingDotLoader({super.key, this.numberOfDots = 3}); /// The number of dots in the loader. final int numberOfDots; @override State<FadingDotLoader> createState() => _FadingDotLoaderState(); } class _FadingDotLoaderState extends State<FadingDotLoader> with TickerProviderStateMixin { late final AnimationController animationController; @override void initState() { super.initState(); final length = Duration(milliseconds: 460 * widget.numberOfDots); animationController = AnimationController(vsync: this, duration: length) ..repeat(); } @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (var i = 0; i < widget.numberOfDots; i++) ...[ _AnimatedDot(index: i, animation: animationController), if (i < widget.numberOfDots - 1) const SizedBox(width: IoFlipSpacing.xs) ], ], ); } @override void dispose() { animationController.dispose(); super.dispose(); } } class _AnimatedDot extends StatelessWidget { const _AnimatedDot({ required this.animation, required this.index, }); final Animation<double> animation; final int index; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { // Calculates the animation controller value with an offset based on the // dot's index and limits the new value between the range (0, 1) final offset = (animation.value - (index * .2)) % 1; // Takes the new value that goes 0 -> 1, and converts it to move 0->1->0 final progress = 1 - (2 * (offset - .5).abs()); // Calculates opacity with a floor and ceiling of 40% and 100% final opacity = (progress * .6) + .4; return Opacity( opacity: opacity, child: child, ); }, child: Container( width: IoFlipSpacing.lg, height: IoFlipSpacing.lg, decoration: const BoxDecoration( color: IoFlipColors.seedPaletteBlue50, shape: BoxShape.circle, ), ), ); } }
io_flip/packages/io_flip_ui/lib/src/widgets/fading_dot_loader.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/fading_dot_loader.dart", "repo_id": "io_flip", "token_count": 957 }
851
name: io_flip_ui description: UI Toolkit for IO FLIP. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: device_info_plus: ^8.2.2 equatable: ^2.0.5 flame: git: url: https://github.com/willhlas/flame path: packages/flame ref: main flutter: sdk: flutter flutter_shaders: ^0.1.1 flutter_svg: ^2.0.5 provider: ^6.0.5 dev_dependencies: build_runner: ^2.3.3 flutter_gen_runner: ^5.3.0 flutter_test: sdk: flutter mocktail: ^0.3.0 mocktail_image_network: ^0.3.1 very_good_analysis: ^4.0.0 flutter: shaders: - shaders/foil.frag assets: - assets/images/ - assets/images/elements/desktop/air/ - assets/images/elements/desktop/earth/ - assets/images/elements/desktop/fire/ - assets/images/elements/desktop/metal/ - assets/images/elements/desktop/water/ - assets/images/elements/mobile/air/ - assets/images/elements/mobile/earth/ - assets/images/elements/mobile/fire/ - assets/images/elements/mobile/metal/ - assets/images/elements/mobile/water/ - assets/images/result_badges/ - assets/images/suits/onboarding/ - assets/images/suits/card/ - assets/images/card_frames/ - assets/images/card_frames/holos/ - assets/images/flip_countdown/mobile/ - assets/images/flip_countdown/desktop/ fonts: - family: Google Sans fonts: - asset: assets/fonts/GoogleSansText-Regular.ttf - asset: assets/fonts/GoogleSansText-Italic.ttf style: italic - family: Roboto Serif fonts: - asset: assets/fonts/RobotoSerif-Regular.ttf - asset: assets/fonts/RobotoSerif-Italic.ttf style: italic - family: Saira fonts: - asset: assets/fonts/Saira-Regular.ttf - asset: assets/fonts/Saira-Italic.ttf style: italic flutter_gen: line_length: 80 assets: outputs: package_parameter_enabled: true integrations: flutter_svg: true
io_flip/packages/io_flip_ui/pubspec.yaml/0
{ "file_path": "io_flip/packages/io_flip_ui/pubspec.yaml", "repo_id": "io_flip", "token_count": 904 }
852
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/src/widgets/damages/dual_animation.dart'; void main() { group('ReverseRRectClipper', () { group('shouldReclip', () { test('returns true for a different RRect', () { final oldClipper = ReverseRRectClipper( RRect.fromRectAndRadius( Offset.zero & Size(50, 200), Radius.circular(50), ), ); final newClipper = ReverseRRectClipper( RRect.fromRectAndRadius( Offset.zero & Size(50, 150), Radius.circular(50), ), ); expect(newClipper.shouldReclip(oldClipper), isTrue); }); test('returns false for the same RRect', () { final oldClipper = ReverseRRectClipper( RRect.fromRectAndRadius( Offset.zero & Size(50, 200), Radius.circular(50), ), ); final newClipper = ReverseRRectClipper( RRect.fromRectAndRadius( Offset.zero & Size(50, 200), Radius.circular(50), ), ); expect(newClipper.shouldReclip(oldClipper), isFalse); }); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/damages/dual_animation_test.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/test/src/widgets/damages/dual_animation_test.dart", "repo_id": "io_flip", "token_count": 619 }
853
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; void main() { group('StretchAnimation', () { late bool complete; setUp(() { complete = false; }); Widget buildSubject({ required bool animating, }) => MaterialApp( home: Scaffold( body: Center( child: StretchAnimation( animating: animating, onComplete: () { complete = true; }, child: Container(), ), ), ), ); testWidgets('can play animation', (tester) async { await tester.pumpWidget(buildSubject(animating: true)); await tester.pump(); expect(tester.binding.hasScheduledFrame, isTrue); }); testWidgets('can stop animation', (tester) async { await tester.pumpWidget(buildSubject(animating: true)); await tester.pumpWidget(buildSubject(animating: false)); await tester.pump(); expect(tester.binding.hasScheduledFrame, isFalse); }); testWidgets('can start animation', (tester) async { await tester.pumpWidget(buildSubject(animating: false)); await tester.pumpWidget(buildSubject(animating: true)); await tester.pump(); expect(tester.binding.hasScheduledFrame, isTrue); }); testWidgets('calls onComplete after it finishes', (tester) async { await tester.pumpWidget(buildSubject(animating: true)); await tester.pumpAndSettle(); expect(complete, isTrue); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/stretch_animation_test.dart/0
{ "file_path": "io_flip/packages/io_flip_ui/test/src/widgets/stretch_animation_test.dart", "repo_id": "io_flip", "token_count": 709 }
854
echo ' ################################# ' echo ' ## Starting flop in local mode ## ' echo ' ################################# ' ENCRYPTION_KEY=$1 ENCRYPTION_IV=$2 RECAPTCHA_KEY=$3 APPCHECK_DEBUG_TOKEN=$4 cd flop && flutter build web \ --dart-define ENCRYPTION_KEY=$ENCRYPTION_KEY \ --dart-define ENCRYPTION_IV=$ENCRYPTION_IV \ --dart-define RECAPTCHA_KEY=$RECAPTCHA_KEY \ --dart-define APPCHECK_DEBUG_TOKEN=$APPCHECK_DEBUG_TOKEN
io_flip/scripts/build_flop.sh/0
{ "file_path": "io_flip/scripts/build_flop.sh", "repo_id": "io_flip", "token_count": 165 }
855
// ignore_for_file: prefer_const_constructors import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/draft/draft.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:mocktail/mocktail.dart'; class _MockGameResource extends Mock implements GameResource {} class _MockAudioController extends Mock implements AudioController {} void main() { group('DraftBloc', () { final rareCard = Card( id: '0', name: '', description: '', image: '', rarity: true, power: 20, suit: Suit.fire, ); final commonCard = Card( id: '0', name: '', description: '', image: '', rarity: false, power: 20, suit: Suit.fire, ); final cards = List.generate( 10, (i) => Card( id: i.toString(), name: '', description: '', image: '', rarity: false, power: 20, suit: Suit.values[i % Suit.values.length], ), ); final deck = Deck( id: 'deckId', userId: 'userId', cards: cards.sublist(0, 3), ); late GameResource gameResource; late AudioController audioController; setUp(() { gameResource = _MockGameResource(); when(() => gameResource.generateCards(Prompt())) .thenAnswer((_) async => cards); audioController = _MockAudioController(); when(() => audioController.playSfx(any())).thenAnswer((_) {}); }); test('has the correct initial state', () { expect( DraftBloc( gameResource: _MockGameResource(), audioController: _MockAudioController(), ).state, equals(DraftState.initial()), ); }); blocTest<DraftBloc, DraftState>( 'can request a deck', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), act: (bloc) => bloc.add(DeckRequested(Prompt())), expect: () => [ DraftState( cards: const [], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoading, firstCardOpacity: 1, ), DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'plays the holo reveal sfx when the deck is loaded and the first ' 'card is rare', setUp: () { final cards = List.generate( 10, (i) => Card( id: i.toString(), name: '', description: '', image: '', rarity: i == 0, power: 20, suit: Suit.values[i % Suit.values.length], ), ); when(() => gameResource.generateCards(Prompt())) .thenAnswer((_) async => cards); }, build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), act: (bloc) => bloc.add(DeckRequested(Prompt())), verify: (_) { verify(() => audioController.playSfx(Assets.sfx.holoReveal)).called(1); }, ); blocTest<DraftBloc, DraftState>( 'change the cards order on PreviousCard', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(PreviousCard()); }, expect: () => [ DraftState( cards: [ cards.last, ...cards.getRange(0, cards.length - 1), ], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'plays the holo reveal when the previous card is rare', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: [commonCard, rareCard], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(PreviousCard()); }, verify: (_) { verify(() => audioController.playSfx(Assets.sfx.holoReveal)).called(1); }, ); blocTest<DraftBloc, DraftState>( 'change the cards order on NextCard', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(NextCard()); }, expect: () => [ DraftState( cards: [ ...cards.getRange(1, cards.length), cards.first, ], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'plays the holo reveal when the next card is rare', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: [commonCard, rareCard], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(NextCard()); }, verify: (_) { verify(() => audioController.playSfx(Assets.sfx.holoReveal)).called(1); }, ); blocTest<DraftBloc, DraftState>( 'change the cards order on CardSwiped', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: .2, ), act: (bloc) { bloc.add(CardSwiped()); }, expect: () => [ DraftState( cards: [ ...cards.getRange(1, cards.length), cards.first, ], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'plays the holo reveal after a swipe and when the next card is rare', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: [commonCard, rareCard], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(CardSwiped()); }, verify: (_) { verify(() => audioController.playSfx(Assets.sfx.holoReveal)).called(1); }, ); blocTest<DraftBloc, DraftState>( 'changes opacity order on CardSwipeStarted', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(CardSwipeStarted(.1)); }, expect: () => [ DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: .9, ), ], ); blocTest<DraftBloc, DraftState>( 'plays cardMovement on CardSwipeStarted', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(CardSwipeStarted(.1)); }, verify: (_) { verify(() => audioController.playSfx(Assets.sfx.cardMovement)) .called(1); }, ); blocTest<DraftBloc, DraftState>( 'selects a card, changes deck on SelectCard, and plays sfx', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: const [null, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(SelectCard(0)); }, expect: () => [ DraftState( cards: [ ...cards.getRange(1, cards.length), ], selectedCards: [cards.first, null, null], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), ], verify: (_) { final captured = verify(() => audioController.playSfx(captureAny())).captured; final sfx = captured.first; expect(sfx, isA<String>()); expect(sfx as String, Assets.sfx.addToHand); }, ); blocTest<DraftBloc, DraftState>( 'can still select a card when the deck is full', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: [cards[1], cards[2], cards[3]], status: DraftStateStatus.deckSelected, firstCardOpacity: 1, ), act: (bloc) { bloc.add(SelectCard(2)); }, expect: () => [ DraftState( cards: [ ...cards.getRange(1, cards.length), cards[3], ], selectedCards: [cards[1], cards[2], cards.first], status: DraftStateStatus.deckSelected, firstCardOpacity: 1, ), ], verify: (_) { final captured = verify(() => audioController.playSfx(captureAny())).captured; final sfx = captured.first; expect(sfx, isA<String>()); expect(sfx as String, Assets.sfx.addToHand); }, ); blocTest<DraftBloc, DraftState>( 'status is complete when the deck is full', build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), seed: () => DraftState( cards: cards, selectedCards: [cards[2], null, cards[3]], status: DraftStateStatus.deckLoaded, firstCardOpacity: 1, ), act: (bloc) { bloc.add(SelectCard(1)); }, expect: () => [ DraftState( cards: [ ...cards.getRange(1, cards.length), ], selectedCards: [cards[2], cards.first, cards[3]], status: DraftStateStatus.deckSelected, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'emits failure when an error occured', setUp: () { when(() => gameResource.generateCards(Prompt())) .thenThrow(Exception('Error')); }, build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), act: (bloc) => bloc.add(DeckRequested(Prompt())), expect: () => [ DraftState( cards: const [], selectedCards: const [null, null, null], status: DraftStateStatus.deckLoading, firstCardOpacity: 1, ), DraftState( cards: const [], selectedCards: const [null, null, null], status: DraftStateStatus.deckFailed, firstCardOpacity: 1, ), ], ); blocTest<DraftBloc, DraftState>( 'emits player deck created when requested', setUp: () { when(() => gameResource.createDeck(any())) .thenAnswer((_) async => 'deckId'); when(() => gameResource.getDeck(any())).thenAnswer((_) async => deck); }, seed: () => DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.deckSelected, firstCardOpacity: 1, ), build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), act: (bloc) => bloc.add( PlayerDeckRequested([cards[0].id, cards[1].id, cards[2].id]), ), expect: () => [ DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.deckLoading, firstCardOpacity: 1, ), DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.playerDeckCreated, firstCardOpacity: 1, deck: deck, ), ], ); blocTest<DraftBloc, DraftState>( 'emits player deck failed when request fails', setUp: () { when(() => gameResource.createDeck(any())).thenThrow(Exception()); }, seed: () => DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.deckSelected, firstCardOpacity: 1, ), build: () => DraftBloc( gameResource: gameResource, audioController: audioController, ), act: (bloc) => bloc.add( PlayerDeckRequested([cards[0].id, cards[1].id, cards[2].id]), ), expect: () => [ DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.deckLoading, firstCardOpacity: 1, ), DraftState( cards: cards, selectedCards: [cards[0], cards[1], cards[2]], status: DraftStateStatus.playerDeckFailed, firstCardOpacity: 1, ), ], ); }); }
io_flip/test/draft/bloc/draft_bloc_test.dart/0
{ "file_path": "io_flip/test/draft/bloc/draft_bloc_test.dart", "repo_id": "io_flip", "token_count": 6826 }
856
export 'go_router.dart'; export 'pump_app.dart'; export 'set_display_size.dart'; export 'tap_text_span.dart'; export 'tester_l10n.dart';
io_flip/test/helpers/helpers.dart/0
{ "file_path": "io_flip/test/helpers/helpers.dart", "repo_id": "io_flip", "token_count": 59 }
857
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/leaderboard/initials_form/initials_form.dart'; void main() { group('InitialsChanged', () { test('can be instantiated', () { expect(InitialsChanged(index: 0, initial: 'A'), isNotNull); }); test('supports equality', () { expect( InitialsChanged(index: 0, initial: 'A'), equals(InitialsChanged(index: 0, initial: 'A')), ); }); }); group('InitialsSubmitted', () { test('can be instantiated', () { expect(InitialsSubmitted(), isNotNull); }); test('supports equality', () { expect( InitialsSubmitted(), equals(InitialsSubmitted()), ); }); }); }
io_flip/test/leaderboard/initials_form/bloc/initials_form_event_test.dart/0
{ "file_path": "io_flip/test/leaderboard/initials_form/bloc/initials_form_event_test.dart", "repo_id": "io_flip", "token_count": 310 }
858
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:io_flip/settings/settings.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class _MockSettingsController extends Mock implements SettingsController {} const _itemsList = ['Archer', 'Magician', 'Climber']; void main() { group('PromptFormView', () { testWidgets('flow updates correctly', (tester) async { late Prompt data; await tester.pumpSubject(onStep: (step) => data = step); await tester.tap(find.text(tester.l10n.select.toUpperCase())); await tester.pumpAndSettle(); expect(data, equals(Prompt(characterClass: _itemsList[0]))); }); testWidgets( 'flow updates correctly when changing selection', (tester) async { late Prompt data; await tester.pumpSubject(onStep: (step) => data = step); await tester.drag( find.byType(ListWheelScrollView), Offset(0, -PromptFormView.itemExtent), ); await tester.tap(find.text(tester.l10n.select.toUpperCase())); await tester.pumpAndSettle(); expect(data, equals(Prompt(characterClass: _itemsList[1]))); }, ); testWidgets( 'list snaps and selects correct item', (tester) async { late Prompt data; await tester.pumpSubject(onStep: (step) => data = step); await tester.drag( find.byType(ListWheelScrollView), Offset(0, -PromptFormView.itemExtent * 2.2), ); await tester.pumpAndSettle(); await tester.tap(find.text(tester.l10n.select.toUpperCase())); await tester.pumpAndSettle(); expect(data, equals(Prompt(characterClass: _itemsList[2]))); }, ); testWidgets( 'taps item in list and is selected correctly', (tester) async { late Prompt data; await tester.pumpSubject(onStep: (step) => data = step); await tester.tap(find.text(_itemsList[2])); await tester.pumpAndSettle(); await tester.tap(find.text(tester.l10n.select.toUpperCase())); await tester.pumpAndSettle(); expect(data, equals(Prompt(characterClass: _itemsList[2]))); }, ); testWidgets('flow completes correctly', (tester) async { late Prompt data; await tester.pumpSubject(onComplete: (step) => data = step, isLast: true); await tester.tap(find.text(tester.l10n.select.toUpperCase())); await tester.pumpAndSettle(); expect(data, equals(Prompt(characterClass: _itemsList[0]))); }); }); } extension PromptFormViewTest on WidgetTester { Future<void> pumpSubject({ bool isLast = false, ValueChanged<Prompt>? onComplete, ValueChanged<Prompt>? onStep, }) { final SettingsController settingsController = _MockSettingsController(); when(() => settingsController.muted).thenReturn(ValueNotifier(true)); return pumpApp( Scaffold( body: SimpleFlow( initialData: Prompt.new, onComplete: onComplete ?? (_) {}, stepBuilder: (context, data, _) { onStep?.call(data); return PromptFormView( title: '', initialItem: 0, itemsList: _itemsList, isLastOfFlow: isLast, ); }, ), ), settingsController: settingsController, ); } }
io_flip/test/prompt/view/prompt_form_view_test.dart/0
{ "file_path": "io_flip/test/prompt/view/prompt_form_view_test.dart", "repo_id": "io_flip", "token_count": 1549 }
859
import 'package:api_client/api_client.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/share/views/views.dart'; import 'package:io_flip/share/widgets/widgets.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import '../../helpers/helpers.dart'; class _MockShareResource extends Mock implements ShareResource {} String? launchedUrl; const shareUrl = 'https://example.com'; const card = Card( id: '', name: 'name', description: 'description', image: '', rarity: false, power: 1, suit: Suit.air, ); void main() { late ShareResource shareResource; setUp(() { shareResource = _MockShareResource(); when(() => shareResource.facebookShareHandUrl(any())).thenReturn(''); when(() => shareResource.twitterShareHandUrl(any())).thenReturn(''); }); group('ShareHandDialog', () { testWidgets('renders', (tester) async { await tester.pumpSubject(shareResource); expect(find.byType(ShareDialog), findsOneWidget); }); testWidgets('renders a CardShareDialog widget', (tester) async { await tester.pumpSubject(shareResource); expect(find.byType(ShareDialog), findsOneWidget); }); testWidgets('renders a CardFan widget', (tester) async { await tester.pumpSubject(shareResource); expect(find.byType(CardFan), findsOneWidget); }); testWidgets('renders the users wins and initials', (tester) async { await tester.pumpSubject(shareResource); expect(find.text('5 ${tester.l10n.winStreakLabel}'), findsOneWidget); expect(find.text('AAA'), findsOneWidget); }); testWidgets('renders the description', (tester) async { await tester.pumpSubject(shareResource); expect(find.text(tester.l10n.shareTeamDialogDescription), findsOneWidget); }); testWidgets('gets the twitter and facebook share links', (tester) async { await tester.pumpSubject(shareResource); verify(() => shareResource.twitterShareHandUrl('test')).called(1); verify(() => shareResource.facebookShareHandUrl('test')).called(1); }); }); } extension ShareCardDialogTest on WidgetTester { Future<void> pumpSubject(ShareResource shareResource) async { await mockNetworkImages(() { return pumpApp( const IoFlipDialog( child: ShareHandDialog( deck: Deck(id: 'test', userId: '', cards: [card, card, card]), wins: 5, initials: 'AAA', ), ), shareResource: shareResource, ); }); } }
io_flip/test/share/views/share_hand_dialog_test.dart/0
{ "file_path": "io_flip/test/share/views/share_hand_dialog_test.dart", "repo_id": "io_flip", "token_count": 1002 }
860
--- sidebar_position: 8 description: Learn how to configure ads in your Flutter news application. --- # Ads ## Ads placement ### Banner ads In the generated Flutter News example, banner ads are introduced as [blocks](/server_development/blocks) served from static news data. The static news data contains instances of `BannerAdBlock` that the app renders as ads inside the feed and in articles. To introduce banner ads into your app, you can do one of the following: 1. Insert them locally at the client level. 2. Insert them into the data served by your [data source](/server_development/connecting_your_data_source). For additional tips, best practices, discouraged implementations with banners, review our articles on the Help Center [here](https://support.google.com/admob/answer/6128877). _Inserting Banner Ads Locally_ To insert banner ads locally, add `BannerAdBlocks` with your desired size into any block feed by adjusting the state emitted by the `ArticleBloc` and `FeedBloc`, respectively. For example, to insert banner ads into the `category` feed view, edit the `FeedBloc._onFeedRequested()` method to insert a `BannerAdBlock` every 15 blocks, and subsequently emit the updated feed. If you want banner ads to appear outside of a feed view, call the `BannerAd` widget constructor with a `BannerAdBlock` at the desired location in the widget tree. _Inserting Banner Ads at the Data Source_ Inserting banner ads into content served by your backend API is the same as local insertion, except that, out of the box, you can only insert a `BannerAdBlock` into block feeds (such as the `article` or `category` feed). To insert a banner ad on the server, change the behavior of your [custom data source](/server_development/connecting_your_data_source#creating-a-new-data-source). Methods such as `getFeed()` and `getArticle()` should insert a `BannerAdBlock` into the blocks returned from the server at your desired positions. Be sure to update the `totalBlocks` metadata returned by the server to reflect the total number of blocks served to the client. This ensures that the client renders all content properly. ### Interstitial ads Interstitial ads are full-screen ads that appear between content. As an example, interstitial ads are displayed upon opening each article. Please follow Google Ads recommendations and adjust the frequency of interstitial ads for a better user experience. This logic is handled by `_ArticleViewState`'s `initState` method (`lib/article/view/article_page.dart`). To remove interstitial ads entirely, you can delete the following line: ```dart context.read<FullScreenAdsBloc>().add(const ShowInterstitialAdRequested()); ``` Alternatively, you can move that line to a location to execute after your desired event (for example, upon article close). For additional tips, you can review our articles on the Help Center for [recommended implementations](https://support.google.com/admob/answer/6201350) and [ad guidance](https://support.google.com/admob/answer/6066980?hl=en) with interstitials. ### Sticky Ads Sticky ads are small dismissible ads that are anchored to the bottom of the screen. Sticky ads are built by the `StickyAd` widget. In the template, there is a sticky ad placed in `ArticleContent` (`lib/article/widgets/article_content.dart`). Move the `StickyAd()` constructor to change which screen shows the sticky ad. ### Rewarded ads Rewarded ads allow the user to view an advertisement to enable a desired action. In the template, unsubscribed users have the opportunity to watch a rewarded ad after viewing four articles, which unlocks the ability to view an additional article. Rewarded ads are built inside the `SubscribeWithArticleLimitModal` widget (`lib/subscriptions/widgets/subscribe_with_article_limit_modal.dart`). The following line runs when tapping the **Watch a video to view this article** button on the modal bottom sheet: ```dart context.read<FullScreenAdsBloc>().add(const ShowRewardedAdRequested()) ``` Move the line to trigger a rewarded ad at your desired position inside the app. Make sure to create a `HasWatchedRewardedAdListener` callback (similar to the one found in `lib/article/view/article_page.dart`), to display the desired content after the user has watched the rewarded ad.
news_toolkit/docs/docs/flutter_development/ads.md/0
{ "file_path": "news_toolkit/docs/docs/flutter_development/ads.md", "repo_id": "news_toolkit", "token_count": 1069 }
861
--- sidebar_position: 6 description: Learn how to setup your application for publishing to the app store. --- # App Store setup This project supports Android and iOS. Use this page to deploy your app to both the Google Play and Apple App Store. ## Google Play store ### Create apps To create your Android apps, you'll first need to create or log into an existing developer account in the [Google Play Console](https://play.google.com/console/developers). Under the **Users and permissions** tab, invite new users and grant appropriate permissions for your team. By default, you should generate a `developer` and `production` app for Android. If you created additional flavors when generating your project from mason, create corresponding apps for each flavor. ### Configure app information Under the **Store presence** dropdown, select **Main store listing** to configure your app information. Populate the required fields under the **Store settings** menu as well. If you plan to offer a subscription package to your news app, [set up the subscription product](https://play.google.com/console/u/0/developers/6749221870414263141/app-list) under the **Products** dropdown in the **Subscriptions** menu item. ## Apple App store ### Create apps To create your iOS apps, you'll first need to create or log into an existing developer account in the [Apple Developer Program](https://developer.apple.com/programs/enroll/). Log into your [App Store Connect](https://appstoreconnect.apple.com/login) account and select **Users and Access** to grant appropriate permissions to your team. Under **Apps**, create a developer and production app for your new project. If you created additional flavors when generating your project from mason, create corresponding apps for each flavor. ### Configure app information Get started by populating the fields under the **App Information** menu for your app. Configure the Privacy Policy and Terms of Use (EULA) in the **App Privacy --> Privacy Policy** section. Create the first release of your app to enable setting up subscriptions, which is done later in the **In-App Purchases** and **Subscriptions** menus. For more information about in-app purchases and subscriptions, check out [In-app purchase](https://developer.apple.com/in-app-purchase/).
news_toolkit/docs/docs/project_configuration/appstore.md/0
{ "file_path": "news_toolkit/docs/docs/project_configuration/appstore.md", "repo_id": "news_toolkit", "token_count": 531 }
862
/** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ @font-face { font-family: 'Open Sans Regular'; src: url('/static/fonts/Open_Sans/static/OpenSans/OpenSans-Regular.ttf') format('truetype'); } :root { --ifm-font-family-base: 'Open Sans Regular'; } /* You can override the default Infima variables here. */ :root { --ifm-color-primary: #4286f4; --ifm-color-primary-dark: #2573f2; --ifm-color-primary-darker: #166af1; --ifm-color-primary-darkest: #0c56cd; --ifm-color-primary-light: #5f99f6; --ifm-color-primary-lighter: #6ea2f7; --ifm-color-primary-lightest: #9abef9; --ifm-code-font-size: 95%; --ifm-footer-background-color: #f8f9fa; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); } /* For readability concerns, you should choose a lighter palette in dark mode. */ [data-theme='dark'] { --ifm-color-primary: #40cfff; --ifm-color-primary-dark: #20c7ff; --ifm-color-primary-darker: #10c3ff; --ifm-color-primary-darkest: #00a7df; --ifm-color-primary-light: #60d7ff; --ifm-color-primary-lighter: #70dbff; --ifm-color-primary-lightest: #a0e7ff; --ifm-footer-background-color: #121a26; --ifm-navbar-background-color: #121a26 !important; --ifm-background-color: #1c2834 !important; --ifm-card-background-color: #121a26; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); } /* Footer */ html .footer { margin-top: 4rem; } html[data-theme='dark'] .footer { background-color: var(--ifm-footer-background-color); } html footer .footer__copyright { font-size: 0.75rem; } /* GitHub Navbar Icon */ .navbar-github-icon:hover { opacity: 0.6; } .navbar-github-icon:before { content: ''; width: 24px; height: 24px; display: flex; background: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12'/%3E%3C/svg%3E") no-repeat; } html[data-theme='dark'] .navbar-github-icon:before { background: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='white' d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12'/%3E%3C/svg%3E") no-repeat; }
news_toolkit/docs/src/css/custom.css/0
{ "file_path": "news_toolkit/docs/src/css/custom.css", "repo_id": "news_toolkit", "token_count": 1767 }
863
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="development" type="FlutterRunConfigurationType" factoryName="Flutter" singleton="false"> <option name="additionalArgs" value="--dart-define FLAVOR_DEEP_LINK_DOMAIN=googlenewstemplatedev.page.link --dart-define FLAVOR_DEEP_LINK_PATH=email_login --dart-define TWITTER_API_KEY=jxG8uZsNuHxn6oeUZm8wfWFcH --dart-define TWITTER_API_SECRET=eQMm0mdvraBIxh418IVGsujj6XnHwTEICLoIex7X7wMcJvEytI --dart-define TWITTER_REDIRECT_URI=google-news-template://" /> <option name="buildFlavor" value="development" /> <option name="filePath" value="$PROJECT_DIR$/lib/main/main_development.dart" /> <method v="2" /> </configuration> </component>
news_toolkit/flutter_news_example/.idea/runConfigurations/development.xml/0
{ "file_path": "news_toolkit/flutter_news_example/.idea/runConfigurations/development.xml", "repo_id": "news_toolkit", "token_count": 284 }
864
<?xml version="1.0" encoding="utf-8"?> <!-- Modify this file to customize your launch splash screen --> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/splash_background" /> <!-- You can insert your own image assets here --> <item> <bitmap android:gravity="center" android:src="@mipmap/launch_image" /> </item> </layer-list>
news_toolkit/flutter_news_example/android/app/src/main/res/drawable-v21/launch_background.xml/0
{ "file_path": "news_toolkit/flutter_news_example/android/app/src/main/res/drawable-v21/launch_background.xml", "repo_id": "news_toolkit", "token_count": 166 }
865
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'feed.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Feed _$FeedFromJson(Map<String, dynamic> json) => Feed( blocks: const NewsBlocksConverter().fromJson(json['blocks'] as List), totalBlocks: json['totalBlocks'] as int, ); Map<String, dynamic> _$FeedToJson(Feed instance) => <String, dynamic>{ 'blocks': const NewsBlocksConverter().toJson(instance.blocks), 'totalBlocks': instance.totalBlocks, };
news_toolkit/flutter_news_example/api/lib/src/data/models/feed.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/data/models/feed.g.dart", "repo_id": "news_toolkit", "token_count": 184 }
866
import 'package:equatable/equatable.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:json_annotation/json_annotation.dart'; part 'categories_response.g.dart'; /// {@template categories_response} /// A news categories response object which contains available news categories. /// {@endtemplate} @JsonSerializable() class CategoriesResponse extends Equatable { /// {@macro categories_response} const CategoriesResponse({required this.categories}); /// Converts a `Map<String, dynamic>` into a [CategoriesResponse] instance. factory CategoriesResponse.fromJson(Map<String, dynamic> json) => _$CategoriesResponseFromJson(json); /// The available categories. final List<Category> categories; /// Converts the current instance to a `Map<String, dynamic>`. Map<String, dynamic> toJson() => _$CategoriesResponseToJson(this); @override List<Object> get props => [categories]; }
news_toolkit/flutter_news_example/api/lib/src/models/categories_response/categories_response.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/models/categories_response/categories_response.dart", "repo_id": "news_toolkit", "token_count": 270 }
867
# news_blocks [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Reusable News Blocks for the Flutter News Example Application [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/api/packages/news_blocks/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/README.md", "repo_id": "news_toolkit", "token_count": 170 }
868
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'image_block.g.dart'; /// {@template image_block} /// A block which represents an image. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=35%3A4874 /// {@endtemplate} @JsonSerializable() class ImageBlock with EquatableMixin implements NewsBlock { /// {@macro image_block} const ImageBlock({ required this.imageUrl, this.type = ImageBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [ImageBlock] instance. factory ImageBlock.fromJson(Map<String, dynamic> json) => _$ImageBlockFromJson(json); /// The image block type identifier. static const identifier = '__image__'; /// The url of this image. final String imageUrl; @override final String type; @override Map<String, dynamic> toJson() => _$ImageBlockToJson(this); @override List<Object> get props => [imageUrl, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/image_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/image_block.dart", "repo_id": "news_toolkit", "token_count": 356 }
869
import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'post_small_block.g.dart'; /// {@template post_small_block} /// A block which represents a small post block. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=391%3A18585 /// {@endtemplate} @JsonSerializable() class PostSmallBlock extends PostBlock { /// {@macro post_small_block} const PostSmallBlock({ required super.id, required super.category, required super.author, required super.publishedAt, required super.title, super.imageUrl, super.description, super.action, super.type = PostSmallBlock.identifier, super.isPremium, }); /// Converts a `Map<String, dynamic>` into a [PostSmallBlock] instance. factory PostSmallBlock.fromJson(Map<String, dynamic> json) => _$PostSmallBlockFromJson(json); /// The small post block type identifier. static const identifier = '__post_small__'; @override Map<String, dynamic> toJson() => _$PostSmallBlockToJson(this); }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_small_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_small_block.dart", "repo_id": "news_toolkit", "token_count": 378 }
870
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'text_lead_paragraph_block.g.dart'; /// {@template text_lead_paragraph_block} /// A block which represents a text lead paragraph. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=35%3A5002 /// {@endtemplate} @JsonSerializable() class TextLeadParagraphBlock with EquatableMixin implements NewsBlock { /// {@macro text_lead_paragraph_block} const TextLeadParagraphBlock({ required this.text, this.type = TextLeadParagraphBlock.identifier, }); /// Converts a `Map<String, dynamic>` /// into a [TextLeadParagraphBlock] instance. factory TextLeadParagraphBlock.fromJson(Map<String, dynamic> json) => _$TextLeadParagraphBlockFromJson(json); /// The text lead paragraph block type identifier. static const identifier = '__text_lead_paragraph__'; /// The text of the text lead paragraph. final String text; @override final String type; @override Map<String, dynamic> toJson() => _$TextLeadParagraphBlockToJson(this); @override List<Object?> get props => [type, text]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_lead_paragraph_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_lead_paragraph_block.dart", "repo_id": "news_toolkit", "token_count": 400 }
871
// ignore_for_file: prefer_const_constructors_in_immutables, lines_longer_than_80_chars, prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; class CustomBlockAction extends BlockAction { CustomBlockAction() : super( type: '__custom_block__', actionType: BlockActionType.navigation, ); @override Map<String, dynamic> toJson() => <String, dynamic>{'type': type}; } void main() { group('BlockAction', () { test('can be extended', () { expect(CustomBlockAction.new, returnsNormally); }); group('fromJson', () { test('returns UnknownBlockAction when type is missing', () { expect( BlockAction.fromJson(<String, dynamic>{}), equals(UnknownBlockAction()), ); }); test('returns UnknownBlockAction when type is unrecognized', () { expect( BlockAction.fromJson(<String, dynamic>{'type': 'unrecognized'}), equals(UnknownBlockAction()), ); }); test('returns NavigateToArticleAction', () { final action = NavigateToArticleAction(articleId: 'articleId'); expect(BlockAction.fromJson(action.toJson()), equals(action)); }); test('returns NavigateToVideoArticleAction', () { final action = NavigateToVideoArticleAction(articleId: 'articleId'); expect(BlockAction.fromJson(action.toJson()), equals(action)); }); test('returns NavigateToFeedCategoryAction', () { final action = NavigateToFeedCategoryAction(category: Category.top); expect(BlockAction.fromJson(action.toJson()), equals(action)); }); test('returns NavigateToSlideshowAction', () { final action = NavigateToSlideshowAction( articleId: 'articleId', slideshow: SlideshowBlock(title: 'title', slides: []), ); expect(BlockAction.fromJson(action.toJson()), equals(action)); }); }); group('UnknownBlockAction', () { test('can be (de)serialized', () { final action = UnknownBlockAction(); expect( UnknownBlockAction.fromJson(action.toJson()), equals(action), ); }); }); group('NavigateToArticleAction', () { test('can be (de)serialized', () { final action = NavigateToArticleAction(articleId: 'articleId'); expect( NavigateToArticleAction.fromJson(action.toJson()), equals(action), ); }); }); group('NavigateToVideoArticleAction', () { test('can be (de)serialized', () { final action = NavigateToVideoArticleAction(articleId: 'articleId'); expect( NavigateToVideoArticleAction.fromJson(action.toJson()), equals(action), ); }); }); group('NavigateToFeedCategoryAction', () { test('can be (de)serialized', () { final action = NavigateToFeedCategoryAction(category: Category.top); expect( NavigateToFeedCategoryAction.fromJson(action.toJson()), equals(action), ); }); }); group('NavigateToSlideshowAction', () { test('can be (de)serialized', () { final action = NavigateToSlideshowAction( articleId: 'articleId', slideshow: SlideshowBlock(title: 'title', slides: []), ); expect( NavigateToSlideshowAction.fromJson(action.toJson()), equals(action), ); }); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/block_action_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/block_action_test.dart", "repo_id": "news_toolkit", "token_count": 1464 }
872
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('SlideshowBlock', () { test('can be (de)serialized', () { final slide = SlideBlock( imageUrl: 'imageUrl', caption: 'caption', photoCredit: 'photoCredit', description: 'description', ); final block = SlideshowBlock(title: 'title', slides: [slide, slide]); expect( SlideshowBlock.fromJson(block.toJson()), equals(block), ); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slideshow_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slideshow_block_test.dart", "repo_id": "news_toolkit", "token_count": 236 }
873
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; Future<Response> onRequest(RequestContext context) async { if (context.request.method != HttpMethod.get) { return Response(statusCode: HttpStatus.methodNotAllowed); } final categories = await context.read<NewsDataSource>().getCategories(); final response = CategoriesResponse(categories: categories); return Response.json(body: response); }
news_toolkit/flutter_news_example/api/routes/api/v1/categories/index.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/routes/api/v1/categories/index.dart", "repo_id": "news_toolkit", "token_count": 145 }
874
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:flutter_news_example_api/api.dart'; import 'package:flutter_news_example_api/src/data/in_memory_news_data_source.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../routes/api/v1/search/relevant.dart' as route; class _MockNewsDataSource extends Mock implements NewsDataSource {} class _MockRequestContext extends Mock implements RequestContext {} void main() { group('GET /api/v1/search/relevant', () { late NewsDataSource newsDataSource; setUp(() { newsDataSource = _MockNewsDataSource(); }); test('responds with a 400 when query parameter is missing.', () async { final request = Request('GET', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.badRequest)); }); test('responds with a 200 on success.', () async { const term = '__test_term__'; final expected = RelevantSearchResponse( articles: relevantArticles.map((item) => item.post).toList(), topics: relevantTopics, ); when( () => newsDataSource.getRelevantArticles(term: any(named: 'term')), ).thenAnswer((_) async => expected.articles); when( () => newsDataSource.getRelevantTopics(term: any(named: 'term')), ).thenAnswer((_) async => expected.topics); final request = Request( 'GET', Uri.parse('http://127.0.0.1/').replace( queryParameters: <String, String>{'q': term}, ), ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.json(), completion(equals(expected.toJson()))); verify(() => newsDataSource.getRelevantArticles(term: term)).called(1); verify(() => newsDataSource.getRelevantTopics(term: term)).called(1); }); }); test('responds with 405 when method is not GET.', () async { final request = Request('POST', Uri.parse('http://127.0.0.1/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }
news_toolkit/flutter_news_example/api/test/routes/search/relevant_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/search/relevant_test.dart", "repo_id": "news_toolkit", "token_count": 976 }
875
export 'sticky_ad.dart';
news_toolkit/flutter_news_example/lib/ads/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/ads/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 11 }
876
part of 'article_bloc.dart'; abstract class ArticleEvent extends Equatable { const ArticleEvent(); @override List<Object> get props => []; } class ArticleRequested extends ArticleEvent { const ArticleRequested(); } class ArticleContentSeen extends ArticleEvent { const ArticleContentSeen({ required this.contentIndex, }); final int contentIndex; @override List<Object> get props => [contentIndex]; } class ArticleRewardedAdWatched extends ArticleEvent { const ArticleRewardedAdWatched(); } class ArticleCommented extends ArticleEvent with AnalyticsEventMixin { const ArticleCommented({required this.articleTitle}); final String articleTitle; @override AnalyticsEvent get event => ArticleCommentEvent(articleTitle: articleTitle); @override List<Object> get props => [articleTitle, event]; } class ShareRequested extends ArticleEvent with AnalyticsEventMixin { const ShareRequested({required this.uri}); final Uri uri; @override AnalyticsEvent get event => SocialShareEvent(); @override List<Object> get props => [uri, event]; }
news_toolkit/flutter_news_example/lib/article/bloc/article_event.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/article/bloc/article_event.dart", "repo_id": "news_toolkit", "token_count": 299 }
877
import 'package:flutter/material.dart'; class CategoriesTabBar extends StatelessWidget implements PreferredSizeWidget { const CategoriesTabBar({ required this.controller, required this.tabs, super.key, }); final TabController controller; final List<Widget> tabs; @override Widget build(BuildContext context) { return TabBar( controller: controller, isScrollable: true, tabs: tabs, ); } @override Size get preferredSize => const Size(double.infinity, 48); } class CategoryTab extends StatelessWidget { const CategoryTab({ required this.categoryName, this.onDoubleTap, super.key, }); final String categoryName; final VoidCallback? onDoubleTap; @override Widget build(BuildContext context) { return GestureDetector( onDoubleTap: onDoubleTap, child: Text(categoryName.toUpperCase()), ); } }
news_toolkit/flutter_news_example/lib/categories/widgets/categories_tab_bar.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/categories/widgets/categories_tab_bar.dart", "repo_id": "news_toolkit", "token_count": 302 }
878
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_news_example/home/home.dart'; import 'package:news_repository/news_repository.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); static Page<void> page() => const MaterialPage<void>(child: HomePage()); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (context) => CategoriesBloc( newsRepository: context.read<NewsRepository>(), )..add(const CategoriesRequested()), ), BlocProvider( create: (context) => FeedBloc( newsRepository: context.read<NewsRepository>(), ), ), BlocProvider(create: (_) => HomeCubit()) ], child: const HomeView(), ); } }
news_toolkit/flutter_news_example/lib/home/view/home_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/home/view/home_page.dart", "repo_id": "news_toolkit", "token_count": 401 }
879
import 'package:app_ui/app_ui.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_news_example/magic_link_prompt/magic_link_prompt.dart'; import 'package:flutter_news_example/terms_of_service/terms_of_service.dart'; import 'package:form_inputs/form_inputs.dart'; class LoginWithEmailForm extends StatelessWidget { const LoginWithEmailForm({super.key}); @override Widget build(BuildContext context) { final email = context.select((LoginBloc bloc) => bloc.state.email.value); return BlocListener<LoginBloc, LoginState>( listener: (context, state) { if (state.status.isSuccess) { Navigator.of(context).push<void>( MagicLinkPromptPage.route(email: email), ); } else if (state.status.isFailure) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar(content: Text(context.l10n.loginWithEmailFailure)), ); } }, child: const CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Padding( padding: EdgeInsets.fromLTRB( AppSpacing.xlg, AppSpacing.lg, AppSpacing.xlg, AppSpacing.xxlg, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ _HeaderTitle(), SizedBox(height: AppSpacing.xxxlg), _EmailInput(), _TermsAndPrivacyPolicyLinkTexts(), Spacer(), _NextButton(), ], ), ), ), ], ), ); } } class _HeaderTitle extends StatelessWidget { const _HeaderTitle(); @override Widget build(BuildContext context) { final theme = Theme.of(context); return Text( context.l10n.loginWithEmailHeaderText, key: const Key('loginWithEmailForm_header_title'), style: theme.textTheme.displaySmall, ); } } class _EmailInput extends StatefulWidget { const _EmailInput(); @override State<_EmailInput> createState() => _EmailInputState(); } class _EmailInputState extends State<_EmailInput> { final _controller = TextEditingController(); @override Widget build(BuildContext context) { final state = context.watch<LoginBloc>().state; return AppEmailTextField( key: const Key('loginWithEmailForm_emailInput_textField'), controller: _controller, readOnly: state.status.isInProgress, hintText: context.l10n.loginWithEmailTextFieldHint, onChanged: (email) => context.read<LoginBloc>().add(LoginEmailChanged(email)), suffix: ClearIconButton( onPressed: !state.status.isInProgress ? () { _controller.clear(); context.read<LoginBloc>().add(const LoginEmailChanged('')); } : null, ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } } class _TermsAndPrivacyPolicyLinkTexts extends StatelessWidget { const _TermsAndPrivacyPolicyLinkTexts(); @override Widget build(BuildContext context) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.only(top: AppSpacing.sm), child: RichText( key: const Key('loginWithEmailForm_terms_and_privacy_policy'), text: TextSpan( children: <TextSpan>[ TextSpan( text: context.l10n.loginWithEmailSubtitleText, style: theme.textTheme.bodyLarge, ), TextSpan( text: context.l10n.loginWithEmailTermsAndPrivacyPolicyText, style: theme.textTheme.bodyLarge?.apply( color: AppColors.darkAqua, ), recognizer: TapGestureRecognizer() ..onTap = () => showAppModal<void>( context: context, builder: (context) => const TermsOfServiceModal(), ), ), TextSpan( text: '.', style: theme.textTheme.bodyLarge, ), ], ), ), ); } } class _NextButton extends StatelessWidget { const _NextButton(); @override Widget build(BuildContext context) { final l10n = context.l10n; final state = context.watch<LoginBloc>().state; return AppButton.darkAqua( key: const Key('loginWithEmailForm_nextButton'), onPressed: state.valid ? () => context.read<LoginBloc>().add(SendEmailLinkSubmitted()) : null, child: state.status.isInProgress ? const SizedBox.square( dimension: 24, child: CircularProgressIndicator(), ) : Text(l10n.nextButtonText), ); } } @visibleForTesting class ClearIconButton extends StatelessWidget { const ClearIconButton({ required this.onPressed, super.key, }); final VoidCallback? onPressed; @override Widget build(BuildContext context) { final suffixVisible = context.select((LoginBloc bloc) => bloc.state.email.value.isNotEmpty); return Padding( key: const Key('loginWithEmailForm_clearIconButton'), padding: const EdgeInsets.only(right: AppSpacing.md), child: Visibility( visible: suffixVisible, child: GestureDetector( onTap: onPressed, child: Assets.icons.closeCircle.svg(), ), ), ); } }
news_toolkit/flutter_news_example/lib/login/widgets/login_with_email_form.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/widgets/login_with_email_form.dart", "repo_id": "news_toolkit", "token_count": 2701 }
880
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/subscriptions/subscriptions.dart'; class NavDrawerSubscribe extends StatelessWidget { const NavDrawerSubscribe({super.key}); @override Widget build(BuildContext context) { return const Column( children: [ NavDrawerSubscribeTitle(), NavDrawerSubscribeSubtitle(), SizedBox(height: AppSpacing.xlg), NavDrawerSubscribeButton(), ], ); } } @visibleForTesting class NavDrawerSubscribeTitle extends StatelessWidget { const NavDrawerSubscribeTitle({super.key}); @override Widget build(BuildContext context) { return Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg, vertical: AppSpacing.lg + AppSpacing.xxs, ), child: Text( context.l10n.navigationDrawerSubscribeTitle, style: Theme.of(context).textTheme.titleMedium?.copyWith( color: AppColors.highEmphasisPrimary, ), ), ), ); } } @visibleForTesting class NavDrawerSubscribeSubtitle extends StatelessWidget { const NavDrawerSubscribeSubtitle({super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg, ), child: Text( context.l10n.navigationDrawerSubscribeSubtitle, style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: AppColors.mediumEmphasisPrimary, ), ), ); } } @visibleForTesting class NavDrawerSubscribeButton extends StatelessWidget { const NavDrawerSubscribeButton({super.key}); @override Widget build(BuildContext context) { return AppButton.redWine( onPressed: () => showPurchaseSubscriptionDialog(context: context), child: Text(context.l10n.subscribeButtonText), ); } }
news_toolkit/flutter_news_example/lib/navigation/widgets/nav_drawer_subscribe.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/navigation/widgets/nav_drawer_subscribe.dart", "repo_id": "news_toolkit", "token_count": 821 }
881
export 'notification_category_tile.dart';
news_toolkit/flutter_news_example/lib/notification_preferences/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 13 }
882
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class SearchFilterChip extends StatelessWidget { const SearchFilterChip({ required this.chipText, required this.onSelected, super.key, }); final ValueSetter<String> onSelected; final String chipText; @override Widget build(BuildContext context) { return FilterChip( padding: const EdgeInsets.symmetric( vertical: AppSpacing.xs + AppSpacing.xxs, ), label: Text( chipText, style: Theme.of(context).textTheme.labelLarge, ), onSelected: (_) => onSelected(chipText), backgroundColor: AppColors.transparent, shape: RoundedRectangleBorder( side: const BorderSide(color: AppColors.borderOutline), borderRadius: BorderRadius.circular(AppSpacing.sm), ), ); } }
news_toolkit/flutter_news_example/lib/search/widgets/search_filter_chip.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/search/widgets/search_filter_chip.dart", "repo_id": "news_toolkit", "token_count": 336 }
883
export 'manage_subscription_page.dart';
news_toolkit/flutter_news_example/lib/subscriptions/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/subscriptions/view/view.dart", "repo_id": "news_toolkit", "token_count": 14 }
884
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:notifications_repository/notifications_repository.dart'; import 'package:user_repository/user_repository.dart'; part 'user_profile_event.dart'; part 'user_profile_state.dart'; class UserProfileBloc extends Bloc<UserProfileEvent, UserProfileState> { UserProfileBloc({ required UserRepository userRepository, required NotificationsRepository notificationsRepository, }) : _notificationsRepository = notificationsRepository, super(const UserProfileState.initial()) { on<UserProfileUpdated>(_onUserProfileUpdated); on<FetchNotificationsEnabled>(_onFetchNotificationsEnabled); on<ToggleNotifications>(_onToggleNotifications); _userSubscription = userRepository.user .handleError(addError) .listen((user) => add(UserProfileUpdated(user))); } final NotificationsRepository _notificationsRepository; late StreamSubscription<User> _userSubscription; void _onUserProfileUpdated( UserProfileUpdated event, Emitter<UserProfileState> emit, ) { emit( state.copyWith( user: event.user, status: UserProfileStatus.userUpdated, ), ); } FutureOr<void> _onFetchNotificationsEnabled( FetchNotificationsEnabled event, Emitter<UserProfileState> emit, ) async { try { emit( state.copyWith( status: UserProfileStatus.fetchingNotificationsEnabled, ), ); final notificationsEnabled = await _notificationsRepository.fetchNotificationsEnabled(); emit( state.copyWith( status: UserProfileStatus.fetchingNotificationsEnabledSucceeded, notificationsEnabled: notificationsEnabled, ), ); } catch (error, stackTrace) { emit( state.copyWith( status: UserProfileStatus.fetchingNotificationsEnabledFailed, ), ); addError(error, stackTrace); } } FutureOr<void> _onToggleNotifications( ToggleNotifications event, Emitter<UserProfileState> emit, ) async { final initialNotificationsEnabled = state.notificationsEnabled; final updatedNotificationsEnabled = !initialNotificationsEnabled; try { emit( state.copyWith( status: UserProfileStatus.togglingNotifications, notificationsEnabled: updatedNotificationsEnabled, ), ); await _notificationsRepository.toggleNotifications( enable: updatedNotificationsEnabled, ); emit( state.copyWith( status: UserProfileStatus.togglingNotificationsSucceeded, ), ); } catch (error, stackTrace) { emit( state.copyWith( status: UserProfileStatus.togglingNotificationsFailed, notificationsEnabled: initialNotificationsEnabled, ), ); addError(error, stackTrace); } } @override Future<void> close() { _userSubscription.cancel(); return super.close(); } }
news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_bloc.dart", "repo_id": "news_toolkit", "token_count": 1161 }
885
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/analytics_repository/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
886
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class AppBackButtonPage extends StatefulWidget { const AppBackButtonPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const AppBackButtonPage()); } @override State<AppBackButtonPage> createState() => _AppBackButtonPageState(); } class _AppBackButtonPageState extends State<AppBackButtonPage> { bool _isLight = false; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: _isLight ? AppColors.grey : AppColors.white, appBar: AppBar( title: const Text('App back button'), leading: _isLight ? const AppBackButton.light() : const AppBackButton(), ), body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Switch( value: _isLight, onChanged: (_) => setState(() => _isLight = !_isLight), ), const Text('Default/light') ], ), ), ); } }
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_back_button_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_back_button_page.dart", "repo_id": "news_toolkit", "token_count": 451 }
887
export 'src/colors/app_colors.dart'; export 'src/extensions/extensions.dart'; export 'src/generated/generated.dart'; export 'src/spacing/app_spacing.dart'; export 'src/theme/app_theme.dart'; export 'src/typography/typography.dart'; export 'src/widgets/widgets.dart';
news_toolkit/flutter_news_example/packages/app_ui/lib/app_ui.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/app_ui.dart", "repo_id": "news_toolkit", "token_count": 100 }
888
import 'package:app_ui/src/generated/generated.dart'; import 'package:flutter/material.dart'; /// {@template app_logo} /// A default app logo. /// {@endtemplate} class AppLogo extends StatelessWidget { /// {@macro app_logo} const AppLogo._({required AssetGenImage logo, super.key}) : _logo = logo; /// The dark app logo. AppLogo.dark({Key? key}) : this._(key: key, logo: Assets.images.logoDark); /// The light app logo. AppLogo.light({Key? key}) : this._(key: key, logo: Assets.images.logoLight); /// The logo to be displayed. final AssetGenImage _logo; @override Widget build(BuildContext context) { return _logo.image( fit: BoxFit.contain, width: 172, height: 24, ); } }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_logo.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_logo.dart", "repo_id": "news_toolkit", "token_count": 269 }
889
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../helpers/helpers.dart'; void main() { group('AppTextField', () { const hintText = 'Hint'; testWidgets('renders TextFormField', (tester) async { await tester.pumpApp( AppTextField(), ); expect(find.byType(TextFormField), findsOneWidget); }); testWidgets('has autocorrect set to true', (tester) async { await tester.pumpApp( AppTextField(), ); final field = tester.widget<AppTextField>(find.byType(AppTextField)); expect(field.autocorrect, true); }); testWidgets('has hint text', (tester) async { await tester.pumpApp( AppTextField( hintText: hintText, ), ); expect(find.text(hintText), findsOneWidget); }); testWidgets('calls onSubmitted when submitted', (tester) async { var onSubmittedCalled = false; await tester.pumpApp( AppTextField( onSubmitted: (_) => onSubmittedCalled = true, ), ); await tester.showKeyboard(find.byType(TextField)); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); expect(onSubmittedCalled, isTrue); }); }); }
news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_text_field_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_text_field_test.dart", "repo_id": "news_toolkit", "token_count": 581 }
890
export 'src/authentication_client.dart'; export 'src/models/models.dart';
news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/authentication_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/authentication_client.dart", "repo_id": "news_toolkit", "token_count": 25 }
891
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/authentication_client/token_storage/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/token_storage/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
892
export 'mock_url_launcher.dart';
news_toolkit/flutter_news_example/packages/email_launcher/test/helpers/helpers.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/email_launcher/test/helpers/helpers.dart", "repo_id": "news_toolkit", "token_count": 14 }
893
// ignore_for_file: prefer_const_constructors import 'package:authentication_client/authentication_client.dart'; import 'package:flutter_news_example_api/client.dart' hide User; import 'package:flutter_news_example_api/client.dart' as api; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class MockFlutterNewsExampleApiClient extends Mock implements FlutterNewsExampleApiClient {} class MockAuthenticationClient extends Mock implements AuthenticationClient {} class MockInAppPurchase extends Mock implements InAppPurchase {} class FakePurchaseDetails extends Fake implements PurchaseDetails {} class InAppPurchaseException extends InAppPurchaseFailure { InAppPurchaseException(super.error); } void main() { test('InAppPurchaseFailure supports value comparisons', () { expect( InAppPurchaseException('error'), equals( InAppPurchaseException('error'), ), ); }); group('InAppPurchaseRepository', () { late AuthenticationClient authenticationClient; late FlutterNewsExampleApiClient apiClient; late InAppPurchase inAppPurchase; final product = ProductDetails( id: 'dd339fda-33e9-49d0-9eb5-0ccb77eb760f', title: 'premium', description: 'premium subscription', price: r'$14.99', rawPrice: 14.99, currencyCode: 'USD', ); final user = AuthenticationUser( id: '123', name: 'name', ); final subscription = Subscription( id: product.id, name: SubscriptionPlan.none, cost: SubscriptionCost(annual: 1, monthly: 2), benefits: const ['benefit', 'nextBenefit'], ); final apiUserResponse = CurrentUserResponse( user: api.User( id: user.id, subscription: subscription.name, ), ); setUpAll(() { registerFallbackValue(SubscriptionPlan.none); registerFallbackValue( PurchaseParam( productDetails: product, applicationUserName: user.name, ), ); registerFallbackValue(FakePurchaseDetails()); }); setUp(() { authenticationClient = MockAuthenticationClient(); apiClient = MockFlutterNewsExampleApiClient(); inAppPurchase = MockInAppPurchase(); when( () => apiClient.createSubscription( subscriptionId: any(named: 'subscriptionId'), ), ).thenAnswer((_) async {}); when( apiClient.getCurrentUser, ).thenAnswer((_) async => apiUserResponse); when(() => authenticationClient.user).thenAnswer( (_) => Stream.fromIterable([user]), ); when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.value([ PurchaseDetails( purchaseID: 'purchaseID', productID: 'productID', verificationData: PurchaseVerificationData( localVerificationData: 'local', serverVerificationData: 'server', source: 'source', ), transactionDate: 'transactionDate', status: PurchaseStatus.pending, ), ]), ); }); group('fetchSubscriptions', () { late InAppPurchaseRepository repository; setUp(() { repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); when(apiClient.getSubscriptions).thenAnswer( (_) async => SubscriptionsResponse( subscriptions: [subscription], ), ); }); group('calls apiClient.getSubscriptions ', () { test( 'which returns cachedProducts list ' 'and calls getSubscriptions only once ' 'when cachedProducts is not empty', () async { final result = await repository.fetchSubscriptions(); final nextResult = await repository.fetchSubscriptions(); verify(apiClient.getSubscriptions).called(1); expect( result, equals(nextResult), ); }); test( 'and returns server products list ' 'when cachedProducts is empty', () async { final result = await repository.fetchSubscriptions(); expect( result, equals([subscription]), ); }); test( 'and throws FetchSubscriptionsFailure ' 'when getSubscriptions fails', () async { when(apiClient.getSubscriptions).thenThrow(Exception()); expect( repository.fetchSubscriptions(), throwsA(isA<FetchSubscriptionsFailure>()), ); }); }); }); group('purchase', () { late InAppPurchaseRepository repository; setUp(() { repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); when( () => inAppPurchase.buyNonConsumable( purchaseParam: any(named: 'purchaseParam'), ), ).thenAnswer((_) async => true); }); group('calls InAppPurchase.buyNonConsumable ', () { setUp(() { when( () => inAppPurchase.queryProductDetails( any(that: isA<Set<String>>()), ), ).thenAnswer( (_) async => ProductDetailsResponse( productDetails: [product], notFoundIDs: [], ), ); }); test('and finishes successfully', () async { await repository.purchase(subscription: subscription); verify( () => inAppPurchase.buyNonConsumable( purchaseParam: any(named: 'purchaseParam'), ), ).called(1); }); test( 'and throws InAppPurchaseBuyNonConsumableFailure ' 'when buyNonConsumable fails', () async { when( () => inAppPurchase.buyNonConsumable( purchaseParam: any(named: 'purchaseParam'), ), ).thenAnswer((_) async => false); expect( repository.purchase(subscription: subscription), throwsA(isA<InAppPurchaseBuyNonConsumableFailure>()), ); }); }); group('throws QueryInAppProductDetailsFailure', () { test('when productDetailsResponse.error is not null', () { when( () => inAppPurchase.queryProductDetails( any(that: isA<Set<String>>()), ), ).thenAnswer( (_) async => ProductDetailsResponse( productDetails: [], error: IAPError( source: 'source', code: 'code', message: 'message', ), notFoundIDs: [], ), ); expect( repository.purchase(subscription: subscription), throwsA(isA<QueryInAppProductDetailsFailure>()), ); }); test('when productDetailsResponse.productDetails isEmpty', () { when( () => inAppPurchase.queryProductDetails( any(that: isA<Set<String>>()), ), ).thenAnswer( (_) async => ProductDetailsResponse( productDetails: [], notFoundIDs: [], ), ); expect( repository.purchase(subscription: subscription), throwsA(isA<QueryInAppProductDetailsFailure>()), ); }); test('when productDetailsResponse.productDetails length > 1', () { when( () => inAppPurchase.queryProductDetails( any(that: isA<Set<String>>()), ), ).thenAnswer( (_) async => ProductDetailsResponse( productDetails: [product, product], notFoundIDs: [], ), ); expect( repository.purchase(subscription: subscription), throwsA(isA<QueryInAppProductDetailsFailure>()), ); }); }); }); group('restorePurchases ', () { late InAppPurchaseRepository repository; setUp(() { repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); when( () => inAppPurchase.buyNonConsumable( purchaseParam: any(named: 'purchaseParam'), ), ).thenAnswer((_) async => true); }); test( 'calls InAppPurchase.restorePurchases ' 'when user is not anonymous', () async { when( () => inAppPurchase.restorePurchases( applicationUserName: any(named: 'applicationUserName'), ), ).thenAnswer((_) async {}); when(() => authenticationClient.user).thenAnswer( (_) => Stream.fromIterable([user]), ); await repository.restorePurchases(); verify( () => inAppPurchase.restorePurchases( applicationUserName: any( named: 'applicationUserName', ), ), ).called(1); }); test( 'does not call InAppPurchase.restorePurchases ' 'when user is anonymous', () async { when( () => inAppPurchase.restorePurchases( applicationUserName: any(named: 'applicationUserName'), ), ).thenAnswer((_) async {}); when(() => authenticationClient.user).thenAnswer( (_) => Stream.fromIterable([AuthenticationUser.anonymous]), ); await repository.restorePurchases(); verifyNever( () => inAppPurchase.restorePurchases( applicationUserName: any( named: 'applicationUserName', ), ), ); }); }); group('onPurchaseUpdated', () { final purchaseDetails = PurchaseDetails( status: PurchaseStatus.pending, productID: product.id, transactionDate: 'transactionDate', verificationData: PurchaseVerificationData( localVerificationData: 'localVerificationData', serverVerificationData: 'server', source: 'source', ), ); setUp(() { when(apiClient.getSubscriptions).thenAnswer( (_) async => SubscriptionsResponse( subscriptions: [subscription], ), ); }); test( 'adds PurchaseCanceled event ' 'when PurchaseDetails status is canceled', () { when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [purchaseDetails.copyWith(status: PurchaseStatus.canceled)], ]), ); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); expectLater( repository.purchaseUpdate, emits(isA<PurchaseCanceled>()), ); }); test( 'adds PurchaseFailed event ' 'when PurchaseDetails status is error', () { when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [purchaseDetails.copyWith(status: PurchaseStatus.error)], ]), ); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); expectLater( repository.purchaseUpdate, emits(isA<PurchaseFailed>()), ); }); group('when PurchaseDetails status is purchased', () { setUp(() { when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [purchaseDetails.copyWith(status: PurchaseStatus.purchased)], ]), ); }); test( 'adds PurchasePurchased event ' 'calls apiClient.createSubscription ' 'adds PurchaseDelivered event ' 'adds purchased subscription to currentSubscriptionPlanStream', () async { final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emitsInOrder( <Matcher>[ isA<PurchasePurchased>(), isA<PurchaseDelivered>(), ], ), ); verify( () => apiClient.createSubscription( subscriptionId: any(named: 'subscriptionId'), ), ).called(1); }); test( 'adds PurchasePurchased event ' 'and throws PurchaseFailed ' 'when apiClient.createSubscription throws', () async { when( () => apiClient.createSubscription( subscriptionId: any(named: 'subscriptionId'), ), ).thenThrow(Exception()); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); expect( repository.purchaseUpdate, emitsInOrder( <Matcher>[ isA<PurchasePurchased>(), emitsError(isA<PurchaseFailed>()) ], ), ); }); }); group('when PurchaseDetails status is restored', () { setUp(() { when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [purchaseDetails.copyWith(status: PurchaseStatus.restored)], ]), ); }); test( 'adds PurchasePurchased event ' 'calls apiClient.createSubscription ' 'adds PurchaseDelivered event ' 'adds purchased subscription to currentSubscriptionPlanStream', () async { final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emitsInOrder( <Matcher>[ isA<PurchasePurchased>(), isA<PurchaseDelivered>(), ], ), ); verify( () => apiClient.createSubscription( subscriptionId: any(named: 'subscriptionId'), ), ).called(1); }); test( 'adds PurchasePurchased event ' 'and throws PurchaseFailed ' 'when apiClient.createSubscription throws', () async { when( () => apiClient.createSubscription( subscriptionId: any(named: 'subscriptionId'), ), ).thenThrow(Exception()); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emitsInOrder(<Matcher>[ isA<PurchasePurchased>(), emitsError(isA<PurchaseFailed>()), ]), ); }); }); group('when pendingCompletePurchase is true', () { setUp(() { when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [ purchaseDetails.copyWith( status: PurchaseStatus.pending, pendingCompletePurchase: true, ) ], ]), ); }); test( 'emits PurchaseCompleted ' 'when inAppPurchase.completePurchase succeeds', () async { when( () => inAppPurchase.completePurchase(any()), ).thenAnswer((_) async {}); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emits(isA<PurchaseCompleted>()), ); }); test( 'throws PurchaseFailed ' 'when inAppPurchase.completePurchase fails', () async { when( () => inAppPurchase.completePurchase(any()), ).thenThrow(Exception()); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emitsError( isA<PurchaseFailed>(), ), ); }); test( 'calls apiClient.getSubscriptions once ' 'and returns cachedProducts on next ' 'apiClient.getSubscriptions call', () async { when( () => inAppPurchase.completePurchase(any()), ).thenAnswer((_) async {}); when(() => inAppPurchase.purchaseStream).thenAnswer( (_) => Stream.fromIterable([ [ purchaseDetails.copyWith( status: PurchaseStatus.pending, pendingCompletePurchase: true, ), purchaseDetails.copyWith( status: PurchaseStatus.pending, pendingCompletePurchase: true, ) ], ]), ); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); await expectLater( repository.purchaseUpdate, emitsInOrder( <Matcher>[ isA<PurchaseCompleted>(), isA<PurchaseCompleted>(), ], ), ); }); }); }); group('fetchSubscriptions', () { test('returns subscription list from apiClient.getSubscriptions', () async { when(apiClient.getSubscriptions).thenAnswer( (_) async => SubscriptionsResponse( subscriptions: [subscription], ), ); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); final result = await repository.fetchSubscriptions(); expect(result, equals([subscription])); verify( apiClient.getSubscriptions, ).called(1); }); test( 'throws FetchSubscriptionsFailure ' 'when apiClient.getSubscriptions throws', () async { when(apiClient.getSubscriptions).thenThrow(Exception()); final repository = InAppPurchaseRepository( authenticationClient: authenticationClient, apiClient: apiClient, inAppPurchase: inAppPurchase, ); expect( repository.fetchSubscriptions, throwsA(isA<FetchSubscriptionsFailure>()), ); }); }); }); group('PurchaseUpdate', () { group('PurchaseDelivered', () { test('supports value comparisons', () { final event1 = PurchaseDelivered( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); final event2 = PurchaseDelivered( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); expect(event1, equals(event2)); }); }); group('PurchaseCompleted', () { test('supports value comparisons', () { final event1 = PurchaseCompleted( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); final event2 = PurchaseCompleted( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); expect(event1, equals(event2)); }); }); group('PurchasePurchased', () { test('supports value comparisons', () { final event1 = PurchasePurchased( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); final event2 = PurchasePurchased( subscription: Subscription( benefits: const [], cost: SubscriptionCost( annual: 0, monthly: 0, ), id: '1', name: SubscriptionPlan.none, ), ); expect(event1, equals(event2)); }); }); group('PurchaseFailed', () { test('supports value comparisons', () { final event1 = PurchaseFailed( failure: DeliverInAppPurchaseFailure('error'), ); final event2 = PurchaseFailed( failure: DeliverInAppPurchaseFailure('error'), ); expect(event1, equals(event2)); }); }); group('PurchaseCanceled', () { test('supports value comparisons', () { final event1 = PurchaseCanceled(); final event2 = PurchaseCanceled(); expect(event1, equals(event2)); }); }); }); } /// Extension on [PurchaseDetails] enabling copyWith. extension _PurchaseDetailsCopyWith on PurchaseDetails { /// Returns a copy of the current PurchaseDetails with the given parameters. PurchaseDetails copyWith({ String? purchaseID, String? productID, PurchaseVerificationData? verificationData, String? transactionDate, PurchaseStatus? status, bool? pendingCompletePurchase, }) => PurchaseDetails( purchaseID: purchaseID ?? this.purchaseID, productID: productID ?? this.productID, verificationData: verificationData ?? this.verificationData, transactionDate: transactionDate ?? this.transactionDate, status: status ?? this.status, )..pendingCompletePurchase = pendingCompletePurchase ?? this.pendingCompletePurchase; }
news_toolkit/flutter_news_example/packages/in_app_purchase_repository/test/src/in_app_purchase_repository_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/in_app_purchase_repository/test/src/in_app_purchase_repository_test.dart", "repo_id": "news_toolkit", "token_count": 11077 }
894
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart' as flutter_html; import 'package:news_blocks/news_blocks.dart'; import 'package:url_launcher/url_launcher.dart'; /// {@template html} /// A reusable html news block widget. /// {@endtemplate} class Html extends StatelessWidget { /// {@macro html} const Html({required this.block, super.key}); /// The associated [HtmlBlock] instance. final HtmlBlock block; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm), child: flutter_html.Html( onLinkTap: (url, attributes, element) { if (url == null) return; final uri = Uri.tryParse(url); if (uri == null) return; launchUrl(uri).ignore(); }, data: block.content, style: { 'p': flutter_html.Style.fromTextStyle( theme.textTheme.bodyLarge!, ), 'h1': flutter_html.Style.fromTextStyle( theme.textTheme.displayLarge!, ), 'h2': flutter_html.Style.fromTextStyle( theme.textTheme.displayMedium!, ), 'h3': flutter_html.Style.fromTextStyle( theme.textTheme.displaySmall!, ), 'h4': flutter_html.Style.fromTextStyle( theme.textTheme.headlineMedium!, ), 'h5': flutter_html.Style.fromTextStyle( theme.textTheme.headlineSmall!, ), 'h6': flutter_html.Style.fromTextStyle( theme.textTheme.titleLarge!, ), }, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/html.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/html.dart", "repo_id": "news_toolkit", "token_count": 792 }
895
import 'package:app_ui/app_ui.dart' show AppColors, AppSpacing; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/src/generated/generated.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template slideshow} /// A reusable slideshow. /// {@endtemplate} class Slideshow extends StatefulWidget { /// {@macro slideshow} const Slideshow({ required this.block, required this.categoryTitle, required this.navigationLabel, super.key, }); /// The associated [SlideshowBlock] instance. final SlideshowBlock block; /// The title of the category. final String categoryTitle; /// The label displayed between navigation buttons of the [_SlideshowButtons]. final String navigationLabel; @override State<Slideshow> createState() => _SlideshowState(); } class _SlideshowState extends State<Slideshow> { final _controller = PageController(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.darkBackground, body: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ _SlideshowCategoryTitle( categoryTitle: widget.categoryTitle, ), _SlideshowHeaderTitle(title: widget.block.title), _SlideshowPageView( slides: widget.block.slides, controller: _controller, ), _SlideshowButtons( totalPages: widget.block.slides.length, controller: _controller, navigationLabel: widget.navigationLabel, ), const SizedBox(height: AppSpacing.lg) ], ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } } class _SlideshowCategoryTitle extends StatelessWidget { const _SlideshowCategoryTitle({ required this.categoryTitle, }); final String categoryTitle; @override Widget build(BuildContext context) { return Padding( key: const Key('slideshow_categoryTitle'), padding: const EdgeInsets.only(left: AppSpacing.lg), child: SlideshowCategory( isIntroduction: false, slideshowText: categoryTitle, ), ); } } class _SlideshowHeaderTitle extends StatelessWidget { const _SlideshowHeaderTitle({ required this.title, }); final String title; @override Widget build(BuildContext context) { final theme = Theme.of(context).textTheme; return Padding( key: const Key('slideshow_headerTitle'), padding: const EdgeInsets.only( left: AppSpacing.lg, bottom: AppSpacing.lg, ), child: Text( title, style: theme.headlineMedium?.apply( color: AppColors.highEmphasisPrimary, ), ), ); } } class _SlideshowPageView extends StatelessWidget { const _SlideshowPageView({ required this.slides, required this.controller, }); final List<SlideBlock> slides; final PageController controller; @override Widget build(BuildContext context) { return Expanded( child: PageView.builder( key: const Key('slideshow_pageView'), physics: const NeverScrollableScrollPhysics(), controller: controller, itemCount: slides.length, itemBuilder: (context, index) => SlideshowItem( slide: slides[index], ), ), ); } } /// {@template slideshow_item} /// A reusable slideshow_item. /// {@endtemplate} @visibleForTesting class SlideshowItem extends StatelessWidget { /// {@macro slideshow_item} const SlideshowItem({required this.slide, super.key}); /// The slide to be displayed. final SlideBlock slide; @override Widget build(BuildContext context) { final theme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox.square( key: const Key('slideshow_slideshowItemImage'), child: Image.network(slide.imageUrl), ), Padding( key: const Key('slideshow_slideshowItemCaption'), padding: const EdgeInsets.only( left: AppSpacing.lg, top: AppSpacing.lg, right: AppSpacing.lg, ), child: Text( slide.caption, style: theme.titleLarge?.apply( color: AppColors.white, ), ), ), Padding( key: const Key('slideshow_slideshowItemDescription'), padding: const EdgeInsets.only( left: AppSpacing.lg, top: AppSpacing.lg, right: AppSpacing.lg, ), child: Text( slide.description, style: theme.bodySmall?.apply( color: AppColors.mediumHighEmphasisPrimary, ), ), ), Padding( key: const Key('slideshow_slideshowItemPhotoCredit'), padding: const EdgeInsets.only( left: AppSpacing.lg, top: AppSpacing.xxxs, ), child: Text( slide.photoCredit, style: theme.bodySmall?.apply( color: AppColors.mediumEmphasisPrimary, ), ), ) ], ); } } class _SlideshowButtons extends StatefulWidget { const _SlideshowButtons({ required this.totalPages, required this.controller, required this.navigationLabel, }); final int totalPages; final PageController controller; final String navigationLabel; @override State<_SlideshowButtons> createState() => _SlideshowButtonsState(); } class _SlideshowButtonsState extends State<_SlideshowButtons> { int _currentPage = 0; static const _pageAnimationDuration = Duration(milliseconds: 300); @override void initState() { widget.controller.addListener(_onPageChanged); super.initState(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); final navigationBarLabel = '${_currentPage + 1} ${widget.navigationLabel} ${widget.totalPages}'; return Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.lg, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( key: const Key('slideshow_slideshowButtonsLeft'), onPressed: () { if (_currentPage >= 1) { widget.controller.previousPage( duration: _pageAnimationDuration, curve: Curves.easeInOut, ); } }, icon: _currentPage == 0 ? Assets.icons.arrowLeftDisable.svg() : Assets.icons.arrowLeftEnable.svg(), ), Text( navigationBarLabel, style: theme.textTheme.titleLarge?.apply(color: AppColors.white), ), IconButton( key: const Key('slideshow_slideshowButtonsRight'), onPressed: () { if (_currentPage < widget.totalPages - 1) { widget.controller.nextPage( duration: _pageAnimationDuration, curve: Curves.easeInOut, ); } }, icon: _currentPage == widget.totalPages - 1 ? Assets.icons.arrowRightDisable.svg() : Assets.icons.arrowRightEnable.svg(), ), ], ), ); } void _onPageChanged() { setState(() { _currentPage = widget.controller.page?.toInt() ?? 0; }); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/slideshow.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/slideshow.dart", "repo_id": "news_toolkit", "token_count": 3338 }
896
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template lock_icon} /// Reusable lock icon. /// {@endtemplate} class LockIcon extends StatelessWidget { /// {@macro lock_icon} const LockIcon({super.key}); @override Widget build(BuildContext context) { return Align( alignment: Alignment.topRight, child: Padding( padding: const EdgeInsets.all(AppSpacing.sm), child: Icon( Icons.lock, size: AppSpacing.xlg, color: AppColors.white, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: const Offset(0, 1), blurRadius: 2, ), Shadow( color: Colors.black.withOpacity(0.15), offset: const Offset(0, 1), blurRadius: 3, ) ], ), ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/lock_icon.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/lock_icon.dart", "repo_id": "news_toolkit", "token_count": 468 }
897
// ignore_for_file: avoid_print import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; /// A comparator for golden tests that allows for a small difference in pixels. /// /// This comparator performs a pixel-for-pixel comparison of the decoded PNGs, /// returning true only if the difference is less than [differenceTolerance]%. /// In case of failure this comparator will provide output to illustrate the /// difference. class TolerantComparator extends LocalFileComparator { TolerantComparator.from( super.testFile, { required LocalFileComparator comparator, }) : _comparator = comparator; /// The difference tolerance that this comparator allows for. /// /// If compared files produce less than [differenceTolerance]% difference, /// then the test is accepted. Otherwise, the test fails. static const differenceTolerance = .06; final LocalFileComparator _comparator; @override Uri getTestUri(Uri key, int? version) => _comparator.getTestUri(key, version); @override Future<bool> compare(Uint8List imageBytes, Uri golden) async { final result = await GoldenFileComparator.compareLists( imageBytes, await getGoldenBytes(golden), ); if (!result.passed) { final error = await generateFailureOutput(result, golden, basedir); if (result.diffPercent >= differenceTolerance) { throw FlutterError(error); } else { print( 'Warning - golden differed less than $differenceTolerance% ' '(${result.diffPercent}%). Ignoring failure but logging the error.', ); print(error); } } return true; } } /// Sets [TolerantComparator] as the default golden file comparator in tests. void setUpTolerantComparator() { final oldComparator = goldenFileComparator as LocalFileComparator; final newComparator = TolerantComparator.from( comparator: oldComparator, Uri.parse('${oldComparator.basedir}test'), ); expect(oldComparator.basedir, newComparator.basedir); goldenFileComparator = newComparator; }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/tolerant_comparator.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/tolerant_comparator.dart", "repo_id": "news_toolkit", "token_count": 665 }
898
// 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('TextLeadParagraph', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly', (tester) async { final widget = Center( child: TextLeadParagraph( block: TextLeadParagraphBlock(text: 'Text Lead Paragraph'), ), ); await tester.pumpApp(widget); await expectLater( find.byType(TextLeadParagraph), matchesGoldenFile('text_lead_paragraph.png'), ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_lead_paragraph_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/text_lead_paragraph_test.dart", "repo_id": "news_toolkit", "token_count": 301 }
899
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('PostContent', () { testWidgets('renders correctly with title', (tester) async { final testPostContent = PostContent( title: 'title', premiumText: 'premiumText', ); await tester.pumpContentThemedApp(testPostContent); expect( find.text('title'), findsOneWidget, ); }); testWidgets('renders category when isPremium is false', (tester) async { final testPostContent = PostContent( title: 'title', categoryName: 'categoryName', premiumText: 'premiumText', ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostContentCategory), findsOneWidget, ); expect( find.byType(PostContentPremiumCategory), findsNothing, ); }); testWidgets( 'renders category and premium ' 'when isPremium is true', (tester) async { final testPostContent = PostContent( title: 'title', categoryName: 'categoryName', premiumText: 'premiumText', isPremium: true, ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostContentCategory), findsOneWidget, ); expect( find.byType(PostContentPremiumCategory), findsOneWidget, ); }); testWidgets( 'renders premium without category ' 'when isPremium is true and categoryName is empty', (tester) async { final testPostContent = PostContent( title: 'title', categoryName: '', premiumText: 'premiumText', isPremium: true, ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostContentCategory), findsNothing, ); expect( find.byType(PostContentPremiumCategory), findsOneWidget, ); }); group('renders PostFooter', () { testWidgets('when author provided', (tester) async { final testPostContent = PostContent( title: 'title', author: 'author', premiumText: 'premiumText', ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostFooter), findsOneWidget, ); }); testWidgets('when publishedAt provided', (tester) async { final testPostContent = PostContent( title: 'title', publishedAt: DateTime(2000, 12, 31), premiumText: 'premiumText', ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostFooter), findsOneWidget, ); }); testWidgets('when onShare provided', (tester) async { final testPostContent = PostContent( title: 'title', publishedAt: DateTime(2000, 12, 31), onShare: () {}, premiumText: 'premiumText', ); await tester.pumpContentThemedApp(testPostContent); expect( find.byType(PostFooter), findsOneWidget, ); }); testWidgets('calls onShare when clicked on share icon', (tester) async { final completer = Completer<void>(); final postContent = PostContent( publishedAt: DateTime(2000, 12, 31), premiumText: 'premiumText', title: 'title', author: 'author', description: 'description', categoryName: 'Category', onShare: completer.complete, ); await tester.pumpContentThemedApp(postContent); await tester.tap(find.byType(IconButton)); expect(completer.isCompleted, isTrue); }); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/post_content_test.dart", "repo_id": "news_toolkit", "token_count": 1775 }
900
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example_api/client.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_repository/news_repository.dart'; import 'package:test/test.dart'; class MockFlutterNewsExampleApiClient extends Mock implements FlutterNewsExampleApiClient {} void main() { group('NewsRepository', () { late FlutterNewsExampleApiClient apiClient; late NewsRepository newsRepository; setUp(() { apiClient = MockFlutterNewsExampleApiClient(); newsRepository = NewsRepository(apiClient: apiClient); }); group('getFeed', () { test( 'returns FeedResponse ' 'from ApiClient.getFeed', () { final feed = <NewsBlock>[ SpacerBlock(spacing: Spacing.extraLarge), DividerHorizontalBlock(), ]; final feedResponse = FeedResponse( feed: feed, totalCount: feed.length, ); when( () => apiClient.getFeed( category: any(named: 'category'), offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenAnswer((_) async => feedResponse); expect( newsRepository.getFeed( category: Category.entertainment, offset: 10, limit: 20, ), completion(equals(feedResponse)), ); verify( () => apiClient.getFeed( category: Category.entertainment, offset: 10, limit: 20, ), ).called(1); }); test( 'throws GetFeedFailure ' 'if ApiClient.getFeed fails', () async { when( () => apiClient.getFeed( category: any(named: 'category'), offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenThrow(Exception); expect( newsRepository.getFeed, throwsA(isA<GetFeedFailure>()), ); }); }); group('getCategories', () { test( 'returns CategoriesResponse ' 'from ApiClient.getCategories', () { const categoriesResponse = CategoriesResponse( categories: [ Category.top, Category.health, ], ); when(apiClient.getCategories) .thenAnswer((_) async => categoriesResponse); expect( newsRepository.getCategories(), completion(equals(categoriesResponse)), ); verify(apiClient.getCategories).called(1); }); test( 'throws GetCategoriesFailure ' 'if ApiClient.getCategories fails', () async { when(apiClient.getCategories).thenThrow(Exception); expect( newsRepository.getCategories, throwsA(isA<GetCategoriesFailure>()), ); }); }); group('subscribeToNewsletter', () { test('completes from ApiClient.subscribeToNewsletter', () { when( () => apiClient.subscribeToNewsletter( email: any(named: 'email'), ), ).thenAnswer((_) async {}); final response = newsRepository.subscribeToNewsletter(email: 'email'); expect(response, completes); verify( () => apiClient.subscribeToNewsletter( email: 'email', ), ).called(1); }); test('throws GetFeedFailure if ApiClient.subscribeToNewsletter', () { when( () => apiClient.subscribeToNewsletter( email: any(named: 'email'), ), ).thenThrow(Exception); final response = newsRepository.subscribeToNewsletter(email: 'email'); expect(response, throwsA(isA<GetFeedFailure>())); }); }); group('popularSearch', () { test( 'returns PopularSearchResponse ' 'from ApiClient.popularSearch', () { const popularResponse = PopularSearchResponse( articles: [ SpacerBlock(spacing: Spacing.extraLarge), DividerHorizontalBlock(), ], topics: ['Topic'], ); when(apiClient.popularSearch).thenAnswer((_) async => popularResponse); expect( newsRepository.popularSearch(), completion(equals(popularResponse)), ); verify(apiClient.popularSearch).called(1); }); test( 'throws PopularSearchFailure ' 'if ApiClient.popularSearch fails', () async { when(apiClient.popularSearch).thenThrow(Exception); expect( newsRepository.popularSearch, throwsA(isA<PopularSearchFailure>()), ); }); }); group('relevantSearch', () { test( 'returns RelevantSearchResponse ' 'from ApiClient.relevantSearch', () { const relevantResponse = RelevantSearchResponse( articles: [ SpacerBlock(spacing: Spacing.extraLarge), DividerHorizontalBlock(), ], topics: ['Topic'], ); when(() => apiClient.relevantSearch(term: '')) .thenAnswer((_) async => relevantResponse); expect( newsRepository.relevantSearch(term: ''), completion(equals(relevantResponse)), ); verify(() => apiClient.relevantSearch(term: any(named: 'term'))) .called(1); }); test( 'throws RelevantSearchFailure ' 'if ApiClient.relevantSearch fails', () async { when(() => apiClient.relevantSearch(term: any(named: 'term'))) .thenThrow(Exception); expect( newsRepository.relevantSearch(term: 'term'), throwsA(isA<RelevantSearchFailure>()), ); }); }); group('NewsFailure', () { final error = Exception('errorMessage'); group('GetFeedFailure', () { test('has correct props', () { expect(GetFeedFailure(error).props, [error]); }); }); group('GetCategoriesFailure', () { test('has correct props', () { expect(GetCategoriesFailure(error).props, [error]); }); }); group('PopularSearchFailure', () { test('has correct props', () { expect(PopularSearchFailure(error).props, [error]); }); }); group('RelevantSearchFailure', () { test('has correct props', () { expect(RelevantSearchFailure(error).props, [error]); }); }); }); }); }
news_toolkit/flutter_news_example/packages/news_repository/test/src/news_repository_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_repository/test/src/news_repository_test.dart", "repo_id": "news_toolkit", "token_count": 2985 }
901
# one_signal_notifications_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] OneSignal notifications client. ## Configuration To use OneSignal as your messaging platform follow [OneSignal documentation](https://documentation.onesignal.com/docs/flutter-sdk-setup).
news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/README.md", "repo_id": "news_toolkit", "token_count": 109 }
902
# package_info_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A client that provides information about the app's package metadata like app name, package name or version. [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/package_info_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/package_info_client/README.md", "repo_id": "news_toolkit", "token_count": 181 }
903
export 'src/purchase_client.dart';
news_toolkit/flutter_news_example/packages/purchase_client/lib/purchase_client.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/purchase_client/lib/purchase_client.dart", "repo_id": "news_toolkit", "token_count": 13 }
904
name: persistent_storage description: Storage that saves data in the device's persistent memory. publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: flutter: sdk: flutter shared_preferences: ^2.0.15 storage: path: ../storage dev_dependencies: flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/storage/persistent_storage/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 145 }
905
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:analytics_repository/analytics_repository.dart' as analytics; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:user_repository/user_repository.dart'; class MockAnalyticsRepository extends Mock implements analytics.AnalyticsRepository {} class MockUserRepository extends Mock implements UserRepository {} class MockUser extends Mock implements User {} class MockAnalyticsEvent extends Mock implements analytics.AnalyticsEvent {} void main() { group('AnalyticsBloc', () { late analytics.AnalyticsRepository analyticsRepository; late UserRepository userRepository; setUp(() { analyticsRepository = MockAnalyticsRepository(); userRepository = MockUserRepository(); when(() => userRepository.user).thenAnswer((_) => Stream.empty()); }); group('on UserRepository.user changed', () { late User user; setUp(() { user = MockUser(); when(() => user.id).thenReturn('id'); when(() => analyticsRepository.setUserId(any())) .thenAnswer((_) async {}); }); blocTest<AnalyticsBloc, AnalyticsState>( 'calls AnalyticsRepository.setUserId ' 'with null when user is anonymous', setUp: () => when(() => userRepository.user) .thenAnswer((_) => Stream.value(User.anonymous)), build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), verify: (_) { verify(() => analyticsRepository.setUserId(null)).called(1); }, ); blocTest<AnalyticsBloc, AnalyticsState>( 'calls AnalyticsRepository.setUserId ' 'with user id when user is not anonymous', setUp: () => when(() => userRepository.user) .thenAnswer((_) => Stream.value(user)), build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), verify: (_) { verify(() => analyticsRepository.setUserId(user.id)).called(1); }, ); blocTest<AnalyticsBloc, AnalyticsState>( 'adds error ' 'when AnalyticsRepository.setUserId throws', setUp: () { when(() => userRepository.user).thenAnswer((_) => Stream.value(user)); when(() => analyticsRepository.setUserId(any())) .thenThrow(Exception()); }, build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), errors: () => [isA<Exception>()], ); }); group('on TrackAnalyticsEvent', () { final event = MockAnalyticsEvent(); setUp(() { when(() => analyticsRepository.track(any())).thenAnswer((_) async {}); }); setUpAll(() { registerFallbackValue(MockAnalyticsEvent()); }); blocTest<AnalyticsBloc, AnalyticsState>( 'calls AnalyticsRepository.track', build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(TrackAnalyticsEvent(event)), verify: (_) { verify(() => analyticsRepository.track(event)).called(1); }, ); blocTest<AnalyticsBloc, AnalyticsState>( 'adds error ' 'when AnalyticsRepository.track throws', setUp: () => when(() => analyticsRepository.track(any())).thenThrow(Exception()), build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), act: (bloc) => bloc.add(TrackAnalyticsEvent(event)), errors: () => [isA<Exception>()], ); }); group('close', () { late StreamController<User> userController; setUp(() { userController = StreamController<User>(); when(() => userRepository.user) .thenAnswer((_) => userController.stream); }); blocTest<AnalyticsBloc, AnalyticsState>( 'cancels UserRepository.user subscription', build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), tearDown: () => expect(userController.hasListener, isFalse), ); }); }); }
news_toolkit/flutter_news_example/test/analytics/bloc/analytics_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/analytics/bloc/analytics_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 1865 }
906
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('ArticleContentLoaderItem', () { testWidgets('renders CircularProgressIndicator', (tester) async { await tester.pumpApp(ArticleContentLoaderItem()); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets('executes onPresented callback', (tester) async { final completer = Completer<void>(); await tester.pumpApp( ArticleContentLoaderItem(onPresented: completer.complete), ); expect(completer.isCompleted, isTrue); }); }); }
news_toolkit/flutter_news_example/test/article/widgets/article_content_loader_item_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_content_loader_item_test.dart", "repo_id": "news_toolkit", "token_count": 287 }
907
import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; /// Extension on `WidgetTester` which exposes a method to /// find a widget by [Type]. extension FindWidgetByTypeExtension on WidgetTester { /// Returns a `Widget` of type `T`. T findWidgetByType<T extends Widget>() => widget<T>(find.byType(T)); }
news_toolkit/flutter_news_example/test/helpers/find_widget_by_type.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/helpers/find_widget_by_type.dart", "repo_id": "news_toolkit", "token_count": 112 }
908
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:form_inputs/form_inputs.dart'; import 'package:mocktail/mocktail.dart'; import 'package:user_repository/user_repository.dart'; import '../../helpers/helpers.dart'; class MockUser extends Mock implements User {} class MockLoginBloc extends MockBloc<LoginEvent, LoginState> implements LoginBloc {} class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {} void main() { const loginButtonKey = Key('loginForm_emailLogin_appButton'); const signInWithGoogleButtonKey = Key('loginForm_googleLogin_appButton'); const signInWithAppleButtonKey = Key('loginForm_appleLogin_appButton'); const signInWithFacebookButtonKey = Key('loginForm_facebookLogin_appButton'); const signInWithTwitterButtonKey = Key('loginForm_twitterLogin_appButton'); const loginFormCloseModalKey = Key('loginForm_closeModal_iconButton'); group('LoginForm', () { late LoginBloc loginBloc; late AppBloc appBloc; late User user; setUp(() { loginBloc = MockLoginBloc(); appBloc = MockAppBloc(); user = MockUser(); when(() => loginBloc.state).thenReturn(const LoginState()); }); group('adds', () { testWidgets( 'LoginGoogleSubmitted to LoginBloc ' 'when sign in with google button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); await tester.ensureVisible(find.byKey(signInWithGoogleButtonKey)); await tester.tap(find.byKey(signInWithGoogleButtonKey)); verify(() => loginBloc.add(LoginGoogleSubmitted())).called(1); }); testWidgets( 'LoginTwitterSubmitted to LoginBloc ' 'when sign in with Twitter button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); await tester.ensureVisible(find.byKey(signInWithTwitterButtonKey)); await tester.tap(find.byKey(signInWithTwitterButtonKey)); verify(() => loginBloc.add(LoginTwitterSubmitted())).called(1); }); testWidgets( 'LoginFacebookSubmitted to LoginBloc ' 'when sign in with Facebook button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); await tester.ensureVisible(find.byKey(signInWithFacebookButtonKey)); await tester.tap(find.byKey(signInWithFacebookButtonKey)); verify(() => loginBloc.add(LoginFacebookSubmitted())).called(1); }); testWidgets( 'LoginAppleSubmitted to LoginBloc ' 'when sign in with apple button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), platform: TargetPlatform.iOS, ); await tester.ensureVisible(find.byKey(signInWithAppleButtonKey)); await tester.tap(find.byKey(signInWithAppleButtonKey)); verify(() => loginBloc.add(LoginAppleSubmitted())).called(1); }); testWidgets('AuthenticationFailure SnackBar when submission fails', (tester) async { whenListen( loginBloc, Stream.fromIterable(const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.failure), ]), ); await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); await tester.pump(); expect(find.byType(SnackBar), findsOneWidget); }); testWidgets('nothing when login is canceled', (tester) async { whenListen( loginBloc, Stream.fromIterable(const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.canceled), ]), ); }); }); group('renders', () { testWidgets('Sign in with Google and Apple on iOS', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), platform: TargetPlatform.iOS, ); expect(find.byKey(signInWithAppleButtonKey), findsOneWidget); expect(find.byKey(signInWithGoogleButtonKey), findsOneWidget); }); testWidgets('only Sign in with Google on Android', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), platform: TargetPlatform.android, ); expect(find.byKey(signInWithAppleButtonKey), findsNothing); expect(find.byKey(signInWithGoogleButtonKey), findsOneWidget); }); testWidgets('Sign in with Facebook', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); expect(find.byKey(signInWithFacebookButtonKey), findsOneWidget); }); testWidgets('Sign in with Twitter', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); expect(find.byKey(signInWithTwitterButtonKey), findsOneWidget); }); }); group('navigates', () { testWidgets('to LoginWithEmailPage when Continue with email is pressed', (tester) async { await tester.pumpApp( BlocProvider.value(value: loginBloc, child: const LoginForm()), ); await tester.ensureVisible(find.byKey(loginButtonKey)); await tester.tap(find.byKey(loginButtonKey)); await tester.pumpAndSettle(); expect(find.byType(LoginWithEmailPage), findsOneWidget); }); }); group('closes modal', () { const buttonText = 'button'; testWidgets('when the close icon is pressed', (tester) async { await tester.pumpApp( BlocProvider.value( value: loginBloc, child: Builder( builder: (context) { return AppButton.black( child: Text(buttonText), onPressed: () => showAppModal<void>( context: context, builder: (context) => const LoginModal(), routeSettings: const RouteSettings(name: LoginModal.name), ), ); }, ), ), ); await tester.tap(find.text(buttonText)); await tester.pumpAndSettle(); await tester.tap(find.byKey(loginFormCloseModalKey)); await tester.pumpAndSettle(); expect(find.byType(LoginForm), findsNothing); }); testWidgets('when user is authenticated', (tester) async { final appStateController = StreamController<AppState>(); whenListen( appBloc, appStateController.stream, initialState: const AppState.unauthenticated(), ); await tester.pumpApp( Builder( builder: (context) { return AppButton.black( child: Text(buttonText), onPressed: () => showAppModal<void>( context: context, builder: (context) => BlocProvider.value( value: appBloc, child: LoginModal(), ), routeSettings: const RouteSettings(name: LoginModal.name), ), ); }, ), ); await tester.tap(find.text(buttonText)); await tester.pumpAndSettle(); await tester.ensureVisible(find.byKey(loginButtonKey)); await tester.tap(find.byKey(loginButtonKey)); await tester.pumpAndSettle(); expect(find.byType(LoginWithEmailPage), findsOneWidget); appStateController.add(AppState.authenticated(user)); await tester.pump(); await tester.pumpAndSettle(); expect(find.byType(LoginWithEmailPage), findsNothing); expect(find.byType(LoginForm), findsNothing); }); testWidgets('when user is authenticated and onboarding is required', (tester) async { final appStateController = StreamController<AppState>(); whenListen( appBloc, appStateController.stream, initialState: const AppState.unauthenticated(), ); await tester.pumpApp( Builder( builder: (context) { return AppButton.black( child: Text(buttonText), onPressed: () => showAppModal<void>( context: context, builder: (context) => BlocProvider.value( value: appBloc, child: LoginModal(), ), routeSettings: const RouteSettings(name: LoginModal.name), ), ); }, ), ); await tester.tap(find.text(buttonText)); await tester.pumpAndSettle(); await tester.ensureVisible(find.byKey(loginButtonKey)); await tester.tap(find.byKey(loginButtonKey)); await tester.pumpAndSettle(); expect(find.byType(LoginWithEmailPage), findsOneWidget); appStateController.add(AppState.onboardingRequired(user)); await tester.pump(); await tester.pumpAndSettle(); expect(find.byType(LoginWithEmailPage), findsNothing); expect(find.byType(LoginForm), findsNothing); }); }); }); }
news_toolkit/flutter_news_example/test/login/widgets/login_form_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/login/widgets/login_form_test.dart", "repo_id": "news_toolkit", "token_count": 4421 }
909
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/notification_preferences/notification_preferences.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; void main() { group('NotificationPreferencesEvent', () { group('CategoriesPreferenceToggled', () { test('supports value comparisons', () { final event1 = CategoriesPreferenceToggled(category: Category.business); final event2 = CategoriesPreferenceToggled(category: Category.business); expect(event1, equals(event2)); }); }); group('InitialCategoriesPreferencesRequested', () { test('supports value comparisons', () { final event1 = InitialCategoriesPreferencesRequested(); final event2 = InitialCategoriesPreferencesRequested(); expect(event1, equals(event2)); }); }); }); }
news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_event_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_event_test.dart", "repo_id": "news_toolkit", "token_count": 313 }
910
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/slideshow/slideshow.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:news_blocks/news_blocks.dart'; import '../../helpers/helpers.dart'; void main() { initMockHydratedStorage(); group('SlideshowPage', () { const articleId = 'articleId'; final slides = List.generate( 4, (index) => SlideBlock( caption: 'caption', description: 'description', photoCredit: 'photo credit', imageUrl: 'imageUrl', ), ); final slideshow = SlideshowBlock(title: 'title', slides: slides); test('has a route', () { expect( SlideshowPage.route( slideshow: slideshow, articleId: articleId, ), isA<MaterialPageRoute<void>>(), ); }); testWidgets('renders a SlideshowView', (tester) async { await mockNetworkImages( () => tester.pumpApp( SlideshowPage( slideshow: slideshow, articleId: articleId, ), ), ); expect(find.byType(SlideshowView), findsOneWidget); }); group('navigates', () { testWidgets('back when leading button is pressed.', (tester) async { final navigator = MockNavigator(); when(() => navigator.popUntil(any())).thenAnswer((_) async {}); await mockNetworkImages( () => tester.pumpApp( SlideshowPage( slideshow: slideshow, articleId: articleId, ), navigator: navigator, ), ); await tester.tap(find.byType(AppBackButton)); await tester.pumpAndSettle(); verify(navigator.pop); }); }); }); }
news_toolkit/flutter_news_example/test/slideshow/view/slideshow_page_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/slideshow/view/slideshow_page_test.dart", "repo_id": "news_toolkit", "token_count": 859 }
911
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/user_profile/user_profile.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:user_repository/user_repository.dart'; void main() { group('UserProfileEvent', () { group('UserProfileUpdated', () { test('supports value comparisons', () { const user = User.anonymous; final userProfileUpdated = UserProfileUpdated(user); final userProfileUpdated2 = UserProfileUpdated(user); expect(userProfileUpdated, equals(userProfileUpdated2)); }); }); group('FetchNotificationsEnabled', () { test('supports value comparisons', () { final event1 = FetchNotificationsEnabled(); final event2 = FetchNotificationsEnabled(); expect(event1, equals(event2)); }); }); group('ToggleNotifications', () { test('supports value comparisons', () { final event1 = ToggleNotifications(); final event2 = ToggleNotifications(); expect(event1, equals(event2)); }); }); }); }
news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_event_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_event_test.dart", "repo_id": "news_toolkit", "token_count": 397 }
912
# Describes the targets run in continuous integration environment. # # Flutter infra uses this file to generate a checklist of tasks to be performed # for every commit. # # More information at: # * https://github.com/flutter/cocoon/blob/main/CI_YAML.md enabled_branches: - main platform_properties: linux: properties: os: Ubuntu cores: "8" device_type: none dependencies: >- [ {"dependency": "curl", "version": "version:7.64.0"} ] # The current android emulator config names can be found here: # https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/android/avd/proto # You may use those names for the android_virtual_device version. linux_android: properties: os: Ubuntu cores: "8" device_type: none dependencies: >- [ {"dependency": "android_sdk", "version": "version:33v6"}, {"dependency": "open_jdk", "version": "version:17"}, {"dependency": "curl", "version": "version:7.64.0"}, {"dependency": "avd_cipd_version", "version": "build_id:8759428741582061553"} ] linux_android_legacy: properties: os: Ubuntu cores: "8" device_type: none dependencies: >- [ {"dependency": "android_sdk", "version": "version:33v6"}, {"dependency": "open_jdk", "version": "version:17"}, {"dependency": "curl", "version": "version:7.64.0"}, {"dependency": "android_virtual_device", "version": "generic_android22.textpb"}, {"dependency": "avd_cipd_version", "version": "build_id:8759428741582061553"} ] linux_desktop: properties: os: Ubuntu cores: "8" device_type: none dependencies: >- [ {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, {"dependency": "cmake", "version": "build_id:8787856497187628321"}, {"dependency": "ninja", "version": "version:1.9.0"}, {"dependency": "curl", "version": "version:7.64.0"} ] linux_web: properties: os: Ubuntu cores: "8" device_type: none dependencies: >- [ {"dependency": "chrome_and_driver", "version": "version:114.0"} ] windows_arm64: properties: dependencies: > [ {"dependency": "certs", "version": "version:9563bb"} ] os: Windows cpu: arm64 windows_x64: properties: dependencies: > [ {"dependency": "certs", "version": "version:9563bb"} ] device_type: none os: Windows cpu: x86 mac_arm64: properties: dependencies: >- [ {"dependency": "ruby", "version": "ruby_3.1-pod_1.13"} ] os: Mac-13 device_type: none cpu: arm64 $flutter/osx_sdk : >- { "sdk_version": "15a240d" } mac_x64: properties: dependencies: >- [ {"dependency": "ruby", "version": "ruby_3.1-pod_1.13"} ] os: Mac-13 device_type: none cpu: x86 $flutter/osx_sdk : >- { "sdk_version": "15a240d" } targets: - name: Linux repo_checks recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" target_file: repo_checks.yaml channel: master version_file: flutter_master.version # The format check requires clang-format, and the current version of ktfmt requires JDK 11+. dependencies: >- [ {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, {"dependency": "open_jdk", "version": "version:17"} ] env_variables: >- { "CHANNEL": "master" } - name: Linux dart_unit_test_shard_1 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux dart_unit_test_shard_2 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux dart_unit_test_shard_1 stable recipe: packages/packages timeout: 60 properties: target_file: dart_unit_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 0 --shardCount 2" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux dart_unit_test_shard_2 stable recipe: packages/packages timeout: 60 properties: target_file: dart_unit_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 1 --shardCount 2" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux_web web_dart_unit_test_shard_1 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: web_dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux_web web_dart_unit_test_shard_2 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: web_dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux_web web_dart_unit_test_shard_1 stable recipe: packages/packages timeout: 60 properties: target_file: web_dart_unit_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 0 --shardCount 2" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux_web web_dart_unit_test_shard_2 stable recipe: packages/packages timeout: 60 properties: target_file: web_dart_unit_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 1 --shardCount 2" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux analyze master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" target_file: analyze.yaml channel: master version_file: flutter_master.version env_variables: >- { "CHANNEL": "master" } - name: Linux analyze stable recipe: packages/packages timeout: 30 properties: target_file: analyze.yaml channel: stable version_file: flutter_stable.version env_variables: >- { "CHANNEL": "stable" } # This is only run on stable since it's extremely likely that stable will # resolve to packages that are older (or at least as old) than on master, so # running a second copy with master is very unlikely to catch anything that # this doesn't. - name: Linux analyze_downgraded stable recipe: packages/packages timeout: 30 properties: target_file: analyze_downgraded.yaml channel: stable version_file: flutter_stable.version env_variables: >- { "CHANNEL": "stable" } # Analyze with the previous stable (N-1) and the stable before that (N-2). The # versions in `channel` should be updated after a new major stable release. - name: Linux analyze_legacy N-1 recipe: packages/packages timeout: 30 properties: target_file: analyze_legacy.yaml channel: "3.16.9" env_variables: >- { "CHANNEL": "3.16.9" } - name: Linux analyze_legacy N-2 recipe: packages/packages timeout: 30 properties: target_file: analyze_legacy.yaml channel: "3.13.9" env_variables: >- { "CHANNEL": "3.13.9" } - name: Linux_android custom_package_tests master recipe: packages/packages timeout: 30 dimensions: kvm: "1" properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: linux_custom_package_tests.yaml # Pigeon tests need Andoid deps (thus the Linux_android base), emulator, # and clang-format. # web_benchmarks needs Chrome. dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"}, {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, {"dependency": "chrome_and_driver", "version": "version:114.0"} ] channel: master env_variables: >- { "CHANNEL": "master" } - name: Linux_android custom_package_tests stable recipe: packages/packages timeout: 30 dimensions: kvm: "1" properties: version_file: flutter_stable.version target_file: linux_custom_package_tests.yaml # See comments on 'master' version above. dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"}, {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"}, {"dependency": "chrome_and_driver", "version": "version:114.0"} ] channel: stable env_variables: >- { "CHANNEL": "stable" } ### Android tasks ### - name: Linux_android android_build_all_packages master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: android_build_all_packages.yaml channel: master # The legacy project build requires an older JDK. dependencies: >- [ {"dependency": "open_jdk", "version": "version:11"} ] env_variables: >- { "CHANNEL": "master" } - name: Linux_android android_build_all_packages stable recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_stable.version target_file: android_build_all_packages.yaml channel: stable # The legacy project build requires an older JDK. dependencies: >- [ {"dependency": "open_jdk", "version": "version:11"} ] env_variables: >- { "CHANNEL": "stable" } # All of the Linux_android android_platform_tests shards have the same # dependency list, despite some running on Android 33 AVDs versus 34. # See https://github.com/flutter/flutter/issues/137082 for context. - name: Linux_android android_platform_tests_shard_1 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 0 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 6" } - name: Linux_android android_platform_tests_shard_2 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 1 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 6" } - name: Linux_android android_platform_tests_shard_3 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 2 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 6" } - name: Linux_android android_platform_tests_shard_4 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 3 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 6" } - name: Linux_android android_platform_tests_shard_5 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 4 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 6" } - name: Linux_android android_platform_tests_shard_6 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests.yaml channel: master version_file: flutter_master.version # set up for 34 package_sharding: "--shardIndex 5 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 5 --shardCount 6" } - name: Linux_android android_platform_tests_api_33_shard_1 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests_api_33_avd.yaml channel: master version_file: flutter_master.version # set up for 33 package_sharding: "--shardIndex 0 --shardCount 2" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_33_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux_android android_platform_tests_api_33_shard_2 master recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests_api_33_avd.yaml channel: master version_file: flutter_master.version # set up for 33 package_sharding: "--shardIndex 1 --shardCount 2" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_33_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux_android android_platform_tests_shard_1 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 0 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 6" } - name: Linux_android android_platform_tests_shard_2 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 1 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 6" } - name: Linux_android android_platform_tests_shard_3 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 2 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 6" } - name: Linux_android android_platform_tests_shard_4 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 3 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 6" } - name: Linux_android android_platform_tests_shard_5 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 4 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 6" } - name: Linux_android android_platform_tests_shard_6 stable recipe: packages/packages presubmit: false timeout: 60 properties: target_file: android_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 5 --shardCount 6" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_34_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 5 --shardCount 6" } - name: Linux_android android_platform_tests_api_33_shard_1 stable recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests_api_33_avd.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 0 --shardCount 2" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_33_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Linux_android android_platform_tests_api_33_shard_2 stable recipe: packages/packages timeout: 60 properties: target_file: android_platform_tests_api_33_avd.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 1 --shardCount 2" dependencies: >- [ {"dependency": "android_virtual_device", "version": "android_33_google_apis_x64.textpb"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_1 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 6" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_2 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 6" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_3 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 2 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 6" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_4 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 3 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 6" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_5 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 4 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 6" } - name: Linux_android_legacy android_platform_tests_legacy_api_shard_6 master recipe: packages/packages timeout: 60 properties: target_file: android_legacy_emulator_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 5 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 5 --shardCount 6" } # Device versions of Android integration tests, run via FTL. # TODO(stuartmorgan): Revisit whether physical device tests are redundant once # we have more data about emulator tests; see # https://github.com/flutter/flutter/issues/131429. - name: Linux_android android_device_tests_shard_1 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 6" } - name: Linux_android android_device_tests_shard_2 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 6" } - name: Linux_android android_device_tests_shard_3 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 2 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 6" } - name: Linux_android android_device_tests_shard_4 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 3 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 6" } - name: Linux_android android_device_tests_shard_5 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 4 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 6" } - name: Linux_android android_device_tests_shard_6 master recipe: packages/packages timeout: 90 properties: target_file: android_device_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 5 --shardCount 6" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 5 --shardCount 6" } ### Web tasks ### - name: Linux_web web_build_all_packages master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: web_build_all_packages.yaml channel: master env_variables: >- { "CHANNEL": "master" } - name: Linux_web web_build_all_packages stable recipe: packages/packages timeout: 30 properties: version_file: flutter_stable.version target_file: web_build_all_packages.yaml channel: stable env_variables: >- { "CHANNEL": "stable" } - name: Linux_web web_platform_tests_shard_1 master recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_master.version channel: master package_sharding: "--shardIndex 0 --shardCount 3" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 3" } - name: Linux_web web_platform_tests_shard_2 master recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_master.version channel: master package_sharding: "--shardIndex 1 --shardCount 3" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 3" } - name: Linux_web web_platform_tests_shard_3 master recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_master.version channel: master package_sharding: "--shardIndex 2 --shardCount 3" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 3" } - name: Linux_web web_platform_tests_shard_1 stable recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_stable.version channel: stable package_sharding: "--shardIndex 0 --shardCount 3" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 3" } - name: Linux_web web_platform_tests_shard_2 stable recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_stable.version channel: stable package_sharding: "--shardIndex 1 --shardCount 3" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 3" } - name: Linux_web web_platform_tests_shard_3 stable recipe: packages/packages timeout: 60 properties: target_file: web_platform_tests.yaml version_file: flutter_stable.version channel: stable package_sharding: "--shardIndex 2 --shardCount 3" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 3" } ### Linux desktop tasks - name: Linux_desktop build_all_packages master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: linux_build_all_packages.yaml channel: master env_variables: >- { "CHANNEL": "master" } - name: Linux_desktop build_all_packages stable recipe: packages/packages timeout: 30 properties: version_file: flutter_stable.version target_file: linux_build_all_packages.yaml channel: stable env_variables: >- { "CHANNEL": "stable" } - name: Linux_desktop platform_tests master recipe: packages/packages timeout: 30 properties: version_file: flutter_master.version target_file: linux_platform_tests.yaml channel: master # Install Chrome as a default handler for schemes for url_launcher. dependencies: >- [ {"dependency": "chrome_and_driver", "version": "version:114.0"} ] env_variables: >- { "CHANNEL": "master" } - name: Linux_desktop platform_tests stable recipe: packages/packages presubmit: false timeout: 30 properties: version_file: flutter_stable.version target_file: linux_platform_tests.yaml channel: stable # Install Chrome as a default handler for schemes for url_launcher. dependencies: >- [ {"dependency": "chrome_and_driver", "version": "version:114.0"} ] env_variables: >- { "CHANNEL": "stable" } ### iOS+macOS tasks ### # TODO(stuartmorgan): Move this to ARM once google_maps_flutter has ARM # support. `pod lint` makes a synthetic target that doesn't respect the # pod's arch exclusions, so fails to build. - name: Mac_x64 check_podspecs recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_repo_checks.yaml dependencies: > [ {"dependency": "swift_format", "version": "build_id:8797338980206841409"} ] ### macOS desktop tasks ### # macos-platform_tests builds all the packages on ARM, so this build is run # on Intel to give us build coverage of both host types. - name: Mac_x64 build_all_packages master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_build_all_packages.yaml channel: master env_variables: >- { "CHANNEL": "master" } - name: Mac_x64 build_all_packages stable recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_stable.version target_file: macos_build_all_packages.yaml channel: stable env_variables: >- { "CHANNEL": "stable" } # TODO(stuartmorgan): Remove "- packages" from all task names once # flutter/plugins is merged into this repo and turned down; it's here only # because names must be unique across all flutter repositories. - name: Mac_arm64 macos_platform_tests master - packages recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_platform_tests.yaml env_variables: >- { "CHANNEL": "master" } - name: Mac_arm64 macos_platform_tests stable - packages recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: macos_platform_tests.yaml env_variables: >- { "CHANNEL": "stable" } - name: Mac_arm64 custom_package_tests master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_custom_package_tests.yaml channel: master env_variables: >- { "CHANNEL": "master" } dependencies: > [ {"dependency": "swift_format", "version": "build_id:8797338979890974865"} ] - name: Mac_arm64 custom_package_tests stable recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" version_file: flutter_stable.version target_file: macos_custom_package_tests.yaml channel: stable env_variables: >- { "CHANNEL": "stable" } dependencies: > [ {"dependency": "swift_format", "version": "build_id:8797338979890974865"} ] ### iOS tasks ### # ios_platform_tests builds all the packages on ARM, so this build is run # on Intel to give us build coverage of both host types. - name: Mac_x64 ios_build_all_packages master recipe: packages/packages timeout: 30 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_build_all_packages.yaml env_variables: >- { "CHANNEL": "master" } - name: Mac_x64 ios_build_all_packages stable recipe: packages/packages timeout: 30 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_build_all_packages.yaml env_variables: >- { "CHANNEL": "stable" } - name: Mac_arm64 ios_platform_tests_shard_1 master recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 0 --shardCount 5" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_2 master recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 1 --shardCount 5" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_3 master recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 2 --shardCount 5" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_4 master recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 3 --shardCount 5" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_5 master recipe: packages/packages timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 4 --shardCount 5" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 5" } # Don't run full platform tests on both channels in pre-submit. - name: Mac_arm64 ios_platform_tests_shard_1 stable recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 0 --shardCount 5" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_2 stable recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 1 --shardCount 5" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_3 stable recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 2 --shardCount 5" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 2 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_4 stable recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 3 --shardCount 5" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 3 --shardCount 5" } - name: Mac_arm64 ios_platform_tests_shard_5 stable recipe: packages/packages presubmit: false timeout: 60 properties: channel: stable version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 4 --shardCount 5" env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 4 --shardCount 5" } ### Windows desktop tasks ### - name: Windows_x64 custom_package_tests master - packages recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: windows_custom_package_tests.yaml channel: master version_file: flutter_master.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "master" } - name: Windows_x64 dart_unit_tests_shard_1 master recipe: packages/packages timeout: 60 properties: target_file: windows_dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Windows_x64 dart_unit_tests_shard_2 master recipe: packages/packages timeout: 60 properties: target_file: windows_dart_unit_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 2" env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Windows_x64 win32-platform_tests_shard_1 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 0 --shardCount 2" dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Windows_x64 win32-platform_tests_shard_2 master recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: master version_file: flutter_master.version package_sharding: "--shardIndex 1 --shardCount 2" dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "master", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Windows_x64 win32-platform_tests_shard_1 stable recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 0 --shardCount 2" dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 0 --shardCount 2" } - name: Windows_x64 win32-platform_tests_shard_2 stable recipe: packages/packages timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: stable version_file: flutter_stable.version package_sharding: "--shardIndex 1 --shardCount 2" dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "stable", "PACKAGE_SHARDING": "--shardIndex 1 --shardCount 2" } - name: Windows_x64 windows-build_all_packages master recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" target_file: windows_build_all_packages.yaml channel: master version_file: flutter_master.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "master" } - name: Windows_arm64 windows-build_all_packages master recipe: packages/packages presubmit: false timeout: 30 bringup: true # https://github.com/flutter/flutter/issues/134083 properties: add_recipes_cq: "true" target_file: windows_build_all_packages.yaml channel: master version_file: flutter_master.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "master" } - name: Windows_x64 windows-build_all_packages stable recipe: packages/packages timeout: 30 properties: target_file: windows_build_all_packages.yaml channel: stable version_file: flutter_stable.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "stable" } - name: Windows_arm64 windows-build_all_packages stable recipe: packages/packages presubmit: false timeout: 30 bringup: true properties: add_recipes_cq: "true" target_file: windows_build_all_packages.yaml channel: stable version_file: flutter_stable.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] env_variables: >- { "CHANNEL": "stable" } - name: Windows_x64 repo_tools_tests recipe: packages/packages timeout: 30 properties: add_recipes_cq: "true" target_file: repo_tools_tests.yaml channel: master version_file: flutter_master.version env_variables: >- { "CHANNEL": "master" } - name: Linux ci_yaml packages roller recipe: infra/ci_yaml timeout: 30 runIf: - .ci.yaml properties: backfill: "false"
packages/.ci.yaml/0
{ "file_path": "packages/.ci.yaml", "repo_id": "packages", "token_count": 20508 }
913
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; /// The demo page for [FadeThroughTransition]. class FadeThroughTransitionDemo extends StatefulWidget { /// Creates the demo page for [FadeThroughTransition]. const FadeThroughTransitionDemo({super.key}); @override State<FadeThroughTransitionDemo> createState() => _FadeThroughTransitionDemoState(); } class _FadeThroughTransitionDemoState extends State<FadeThroughTransitionDemo> { int pageIndex = 0; List<Widget> pageList = <Widget>[ _FirstPage(), _SecondPage(), _ThirdPage(), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Fade through')), body: PageTransitionSwitcher( transitionBuilder: ( Widget child, Animation<double> animation, Animation<double> secondaryAnimation, ) { return FadeThroughTransition( animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, child: pageList[pageIndex], ), bottomNavigationBar: BottomNavigationBar( currentIndex: pageIndex, onTap: (int newValue) { setState(() { pageIndex = newValue; }); }, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.photo_library), label: 'Albums', ), BottomNavigationBarItem( icon: Icon(Icons.photo), label: 'Photos', ), BottomNavigationBarItem( icon: Icon(Icons.search), label: 'Search', ), ], ), ); } } class _ExampleCard extends StatelessWidget { @override Widget build(BuildContext context) { return Expanded( child: Card( child: Stack( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded( child: ColoredBox( color: Colors.black26, child: Padding( padding: const EdgeInsets.all(30.0), child: Ink.image( image: const AssetImage('assets/placeholder_image.png'), ), ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( '123 photos', style: Theme.of(context).textTheme.bodyLarge, ), Text( '123 photos', style: Theme.of(context).textTheme.bodySmall, ), ], ), ), ], ), InkWell( splashColor: Colors.black38, onTap: () {}, ), ], ), ), ); } } class _FirstPage extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: <Widget>[ Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ), ), Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ), ), Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ), ), ], ); } } class _SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: <Widget>[ _ExampleCard(), _ExampleCard(), ], ); } } class _ThirdPage extends StatelessWidget { @override Widget build(BuildContext context) { return ListView.builder( itemBuilder: (BuildContext context, int index) { return ListTile( leading: Image.asset( 'assets/avatar_logo.png', width: 40, ), title: Text('List item ${index + 1}'), subtitle: const Text('Secondary text'), ); }, itemCount: 10, ); } }
packages/packages/animations/example/lib/fade_through_transition.dart/0
{ "file_path": "packages/packages/animations/example/lib/fade_through_transition.dart", "repo_id": "packages", "token_count": 2555 }
914
name: animations description: Fancy pre-built animations that can easily be integrated into any Flutter application. repository: https://github.com/flutter/packages/tree/main/packages/animations issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+animations%22 version: 2.0.11 environment: sdk: ">=3.2.0 <4.0.0" flutter: ">=3.16.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter vector_math: ^2.1.0 topics: - animation - ui screenshots: - description: 'Examples of the container transform pattern.' path: example/screenshots/container_transform_lineup.webp - description: 'Examples of the fade pattern.' path: example/screenshots/fade_lineup.webp - description: 'Examples of the fade through pattern.' path: example/screenshots/fade_through_lineup.webp - description: 'Examples of the shared axis pattern.' path: example/screenshots/shared_axis_lineup.webp
packages/packages/animations/pubspec.yaml/0
{ "file_path": "packages/packages/animations/pubspec.yaml", "repo_id": "packages", "token_count": 346 }
915
// 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 <Flutter/Flutter.h> #import <UIKit/UIKit.h> #import "AppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { // The setup logic in `AppDelegate::didFinishLaunchingWithOptions:` eventually sends camera // operations on the background queue, which would run concurrently with the test cases during // unit tests, making the debugging process confusing. This setup is actually not necessary for // the unit tests, so it is better to skip the AppDelegate when running unit tests. BOOL isTesting = NSClassFromString(@"XCTestCase") != nil; return UIApplicationMain(argc, argv, nil, isTesting ? nil : NSStringFromClass([AppDelegate class])); } }
packages/packages/camera/camera/example/ios/Runner/main.m/0
{ "file_path": "packages/packages/camera/camera/example/ios/Runner/main.m", "repo_id": "packages", "token_count": 285 }
916
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:camera/camera.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'camera_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MockStreamingCameraPlatform mockPlatform; setUp(() { mockPlatform = MockStreamingCameraPlatform(); CameraPlatform.instance = mockPlatform; }); test('startImageStream() throws $CameraException when uninitialized', () { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); expect( () => cameraController.startImageStream((CameraImage image) {}), throwsA( isA<CameraException>() .having( (CameraException error) => error.code, 'code', 'Uninitialized CameraController', ) .having( (CameraException error) => error.description, 'description', 'startImageStream() was called on an uninitialized CameraController.', ), ), ); }); test('startImageStream() throws $CameraException when recording videos', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); cameraController.value = cameraController.value.copyWith(isRecordingVideo: true); expect( () => cameraController.startImageStream((CameraImage image) {}), throwsA(isA<CameraException>().having( (CameraException error) => error.description, 'A video recording is already started.', 'startImageStream was called while a video is being recorded.', ))); }); test( 'startImageStream() throws $CameraException when already streaming images', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); cameraController.value = cameraController.value.copyWith(isStreamingImages: true); expect( () => cameraController.startImageStream((CameraImage image) {}), throwsA(isA<CameraException>().having( (CameraException error) => error.description, 'A camera has started streaming images.', 'startImageStream was called while a camera was streaming images.', ))); }); test('startImageStream() calls CameraPlatform', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); await cameraController.startImageStream((CameraImage image) {}); expect(mockPlatform.streamCallLog, <String>['onStreamedFrameAvailable', 'listen']); }); test('stopImageStream() throws $CameraException when uninitialized', () { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); expect( cameraController.stopImageStream, throwsA( isA<CameraException>() .having( (CameraException error) => error.code, 'code', 'Uninitialized CameraController', ) .having( (CameraException error) => error.description, 'description', 'stopImageStream() was called on an uninitialized CameraController.', ), ), ); }); test('stopImageStream() throws $CameraException when not streaming images', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); expect( cameraController.stopImageStream, throwsA(isA<CameraException>().having( (CameraException error) => error.description, 'No camera is streaming images', 'stopImageStream was called when no camera is streaming images.', ))); }); test('stopImageStream() intended behaviour', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); await cameraController.startImageStream((CameraImage image) {}); await cameraController.stopImageStream(); expect(mockPlatform.streamCallLog, <String>['onStreamedFrameAvailable', 'listen', 'cancel']); }); test('startVideoRecording() can stream images', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); await cameraController.startVideoRecording( onAvailable: (CameraImage image) {}); expect( mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), isTrue); }); test('startVideoRecording() by default does not stream', () async { final CameraController cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, sensorOrientation: 90), ResolutionPreset.max); await cameraController.initialize(); await cameraController.startVideoRecording(); expect(mockPlatform.streamCallLog.contains('startVideoCapturing'), isTrue); }); } class MockStreamingCameraPlatform extends MockCameraPlatform { List<String> streamCallLog = <String>[]; StreamController<CameraImageData>? _streamController; @override Stream<CameraImageData> onStreamedFrameAvailable(int cameraId, {CameraImageStreamOptions? options}) { streamCallLog.add('onStreamedFrameAvailable'); _streamController = StreamController<CameraImageData>( onListen: _onFrameStreamListen, onCancel: _onFrameStreamCancel, ); return _streamController!.stream; } @override Future<XFile> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) { streamCallLog.add('startVideoRecording'); return super .startVideoRecording(cameraId, maxVideoDuration: maxVideoDuration); } @override Future<void> startVideoCapturing(VideoCaptureOptions options) { if (options.streamCallback == null) { streamCallLog.add('startVideoCapturing'); } else { streamCallLog.add('startVideoCapturing with stream'); } return super.startVideoCapturing(options); } void _onFrameStreamListen() { streamCallLog.add('listen'); } FutureOr<void> _onFrameStreamCancel() async { streamCallLog.add('cancel'); _streamController = null; } }
packages/packages/camera/camera/test/camera_image_stream_test.dart/0
{ "file_path": "packages/packages/camera/camera/test/camera_image_stream_test.dart", "repo_id": "packages", "token_count": 2916 }
917
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera; import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camera.CameraPermissions.PermissionsRegistry; import io.flutter.view.TextureRegistry; /** * Platform implementation of the camera_plugin. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. * See {@code io.flutter.plugins.camera.MainActivity} for an example. * * <p>Call {@link #registerWith(io.flutter.plugin.common.PluginRegistry.Registrar)} to register an * implementation of this that uses the stable {@code io.flutter.plugin.common} package. */ public final class CameraPlugin implements FlutterPlugin, ActivityAware { private static final String TAG = "CameraPlugin"; private @Nullable FlutterPluginBinding flutterPluginBinding; private @Nullable MethodCallHandlerImpl methodCallHandler; /** * Initialize this within the {@code #configureFlutterEngine} of a Flutter activity or fragment. * * <p>See {@code io.flutter.plugins.camera.MainActivity} for an example. */ public CameraPlugin() {} /** * Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common} * package. * * <p>Calling this automatically initializes the plugin. However plugins initialized this way * won't react to changes in activity or context, unlike {@link CameraPlugin}. */ @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { CameraPlugin plugin = new CameraPlugin(); plugin.maybeStartListening( registrar.activity(), registrar.messenger(), registrar::addRequestPermissionsResultListener, registrar.view()); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { this.flutterPluginBinding = binding; } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { this.flutterPluginBinding = null; } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { maybeStartListening( binding.getActivity(), flutterPluginBinding.getBinaryMessenger(), binding::addRequestPermissionsResultListener, flutterPluginBinding.getTextureRegistry()); } @Override public void onDetachedFromActivity() { // Could be on too low of an SDK to have started listening originally. if (methodCallHandler != null) { methodCallHandler.stopListening(); methodCallHandler = null; } } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { onAttachedToActivity(binding); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } private void maybeStartListening( Activity activity, BinaryMessenger messenger, PermissionsRegistry permissionsRegistry, TextureRegistry textureRegistry) { methodCallHandler = new MethodCallHandlerImpl( activity, messenger, new CameraPermissions(), permissionsRegistry, textureRegistry); } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraPlugin.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraPlugin.java", "repo_id": "packages", "token_count": 1116 }
918
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features.sensororientation; import android.annotation.SuppressLint; import android.app.Activity; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DartMessenger; import io.flutter.plugins.camera.features.CameraFeature; import io.flutter.plugins.camera.features.resolution.ResolutionFeature; /** Provides access to the sensor orientation of the camera devices. */ public class SensorOrientationFeature extends CameraFeature<Integer> { @NonNull private Integer currentSetting = 0; @NonNull private final DeviceOrientationManager deviceOrientationListener; @Nullable private PlatformChannel.DeviceOrientation lockedCaptureOrientation; /** * Creates a new instance of the {@link ResolutionFeature}. * * @param cameraProperties Collection of characteristics for the current camera device. * @param activity Current Android {@link android.app.Activity}, used to detect UI orientation * changes. * @param dartMessenger Instance of a {@link DartMessenger} used to communicate orientation * updates back to the client. */ public SensorOrientationFeature( @NonNull CameraProperties cameraProperties, @NonNull Activity activity, @NonNull DartMessenger dartMessenger) { super(cameraProperties); setValue(cameraProperties.getSensorOrientation()); boolean isFrontFacing = cameraProperties.getLensFacing() == CameraMetadata.LENS_FACING_FRONT; deviceOrientationListener = DeviceOrientationManager.create(activity, dartMessenger, isFrontFacing, currentSetting); deviceOrientationListener.start(); } @NonNull @Override public String getDebugName() { return "SensorOrientationFeature"; } @SuppressLint("KotlinPropertyAccess") @NonNull @Override public Integer getValue() { return currentSetting; } @Override public void setValue(@NonNull Integer value) { this.currentSetting = value; } @Override public boolean checkIsSupported() { return true; } @Override public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) { // Noop: when setting the sensor orientation there is no need to update the request builder. } /** * Gets the instance of the {@link DeviceOrientationManager} used to detect orientation changes. * * @return The instance of the {@link DeviceOrientationManager}. */ @NonNull public DeviceOrientationManager getDeviceOrientationManager() { return this.deviceOrientationListener; } /** * Lock the capture orientation, indicating that the device orientation should not influence the * capture orientation. * * @param orientation The orientation in which to lock the capture orientation. */ public void lockCaptureOrientation(@NonNull PlatformChannel.DeviceOrientation orientation) { this.lockedCaptureOrientation = orientation; } /** * Unlock the capture orientation, indicating that the device orientation should be used to * configure the capture orientation. */ public void unlockCaptureOrientation() { this.lockedCaptureOrientation = null; } /** * Gets the configured locked capture orientation. * * @return The configured locked capture orientation. */ @Nullable public PlatformChannel.DeviceOrientation getLockedCaptureOrientation() { return this.lockedCaptureOrientation; } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeature.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeature.java", "repo_id": "packages", "token_count": 1081 }
919
sdk=30
packages/packages/camera/camera_android/android/src/test/resources/robolectric.properties/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/resources/robolectric.properties", "repo_id": "packages", "token_count": 4 }
920
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-all.zip
packages/packages/camera/camera_android/example/android/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "packages/packages/camera/camera_android/example/android/gradle/wrapper/gradle-wrapper.properties", "repo_id": "packages", "token_count": 71 }
921
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.CameraControl; import androidx.camera.core.FocusMeteringAction; import androidx.camera.core.FocusMeteringResult; import androidx.core.content.ContextCompat; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraControlHostApi; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; import java.util.Objects; /** * Host API implementation for {@link CameraControl}. * * <p>This class handles instantiating and adding native object instances that are attached to a * Dart instance or handle method calls on the associated native class or an instance of the class. */ public class CameraControlHostApiImpl implements CameraControlHostApi { private final InstanceManager instanceManager; private final CameraControlProxy proxy; /** Proxy for methods of {@link CameraControl}. */ @VisibleForTesting public static class CameraControlProxy { Context context; BinaryMessenger binaryMessenger; InstanceManager instanceManager; /** Enables or disables the torch of the specified {@link CameraControl} instance. */ @NonNull public void enableTorch( @NonNull CameraControl cameraControl, @NonNull Boolean torch, @NonNull GeneratedCameraXLibrary.Result<Void> result) { if (context == null) { throw new IllegalStateException("Context must be set to enable the torch."); } ListenableFuture<Void> enableTorchFuture = cameraControl.enableTorch(torch); Futures.addCallback( enableTorchFuture, new FutureCallback<Void>() { public void onSuccess(Void voidResult) { result.success(null); } public void onFailure(Throwable t) { result.error(t); } }, ContextCompat.getMainExecutor(context)); } /** Sets the zoom ratio of the specified {@link CameraControl} instance. */ @NonNull public void setZoomRatio( @NonNull CameraControl cameraControl, @NonNull Double ratio, @NonNull GeneratedCameraXLibrary.Result<Void> result) { if (context == null) { throw new IllegalStateException("Context must be set to set zoom ratio."); } float ratioAsFloat = ratio.floatValue(); ListenableFuture<Void> setZoomRatioFuture = cameraControl.setZoomRatio(ratioAsFloat); Futures.addCallback( setZoomRatioFuture, new FutureCallback<Void>() { public void onSuccess(Void voidResult) { result.success(null); } public void onFailure(Throwable t) { if (t instanceof CameraControl.OperationCanceledException) { // Operation was canceled due to camera being closed or a new request was submitted, which // is not actionable and should not block a new value from potentially being submitted. result.success(null); return; } result.error(t); } }, ContextCompat.getMainExecutor(context)); } /** * Starts a focus and metering action configured by the {@code FocusMeteringAction}. * * <p>Will trigger an auto focus action and enable auto focus/auto exposure/auto white balance * metering regions. * * <p>Will send a {@link GeneratedCameraXLibrary.Result} with a null result if operation was * canceled. */ public void startFocusAndMetering( @NonNull CameraControl cameraControl, @NonNull FocusMeteringAction focusMeteringAction, @NonNull GeneratedCameraXLibrary.Result<Long> result) { if (context == null) { throw new IllegalStateException("Context must be set to set zoom ratio."); } ListenableFuture<FocusMeteringResult> focusMeteringResultFuture = cameraControl.startFocusAndMetering(focusMeteringAction); Futures.addCallback( focusMeteringResultFuture, new FutureCallback<FocusMeteringResult>() { public void onSuccess(FocusMeteringResult focusMeteringResult) { final FocusMeteringResultFlutterApiImpl flutterApi = new FocusMeteringResultFlutterApiImpl(binaryMessenger, instanceManager); flutterApi.create(focusMeteringResult, reply -> {}); result.success(instanceManager.getIdentifierForStrongReference(focusMeteringResult)); } public void onFailure(Throwable t) { if (t instanceof CameraControl.OperationCanceledException) { // Operation was canceled due to camera being closed or a new request was submitted, which // is not actionable and should not block a new value from potentially being submitted. result.success(null); return; } result.error(t); } }, ContextCompat.getMainExecutor(context)); } /** * Cancels current {@code FocusMeteringAction} and clears auto focus/auto exposure/auto white * balance regions. */ public void cancelFocusAndMetering( @NonNull CameraControl cameraControl, @NonNull Result<Void> result) { ListenableFuture<Void> cancelFocusAndMeteringFuture = cameraControl.cancelFocusAndMetering(); Futures.addCallback( cancelFocusAndMeteringFuture, new FutureCallback<Void>() { public void onSuccess(Void voidResult) { result.success(null); } public void onFailure(Throwable t) { result.error(t); } }, ContextCompat.getMainExecutor(context)); } /** * Sets the exposure compensation index for the specified {@link CameraControl} instance and * returns the new target exposure value. * * <p>The exposure compensation value set on the camera must be within the range of {@code * ExposureState#getExposureCompensationRange()} for the current {@code ExposureState} for the * call to succeed. * * <p>Will send a {@link GeneratedCameraXLibrary.Result} with a null result if operation was * canceled. */ public void setExposureCompensationIndex( @NonNull CameraControl cameraControl, @NonNull Long index, @NonNull Result<Long> result) { ListenableFuture<Integer> setExposureCompensationIndexFuture = cameraControl.setExposureCompensationIndex(index.intValue()); Futures.addCallback( setExposureCompensationIndexFuture, new FutureCallback<Integer>() { public void onSuccess(Integer integerResult) { result.success(integerResult.longValue()); } public void onFailure(Throwable t) { if (t instanceof CameraControl.OperationCanceledException) { // Operation was canceled due to camera being closed or a new request was submitted, which // is not actionable and should not block a new value from potentially being submitted. result.success(null); return; } result.error(t); } }, ContextCompat.getMainExecutor(context)); } } /** * Constructs an {@link CameraControlHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with attached Dart objects * @param context {@link Context} used to retrieve {@code Executor} */ public CameraControlHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull Context context) { this(binaryMessenger, instanceManager, new CameraControlProxy(), context); } /** * Constructs an {@link CameraControlHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with attached Dart objects * @param proxy proxy for methods of {@link CameraControl} * @param context {@link Context} used to retrieve {@code Executor} */ @VisibleForTesting CameraControlHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull CameraControlProxy proxy, @NonNull Context context) { this.instanceManager = instanceManager; this.proxy = proxy; proxy.context = context; // proxy.startFocusAndMetering needs to access these to create a FocusMeteringResult when it becomes available: proxy.instanceManager = instanceManager; proxy.binaryMessenger = binaryMessenger; } /** * Sets the context that the {@code CameraControl} will use to enable/disable torch mode and set * the zoom ratio. * * <p>If using the camera plugin in an add-to-app context, ensure that this is called anytime that * the context changes. */ public void setContext(@NonNull Context context) { this.proxy.context = context; } @Override public void enableTorch( @NonNull Long identifier, @NonNull Boolean torch, @NonNull GeneratedCameraXLibrary.Result<Void> result) { proxy.enableTorch(getCameraControlInstance(identifier), torch, result); } @Override public void setZoomRatio( @NonNull Long identifier, @NonNull Double ratio, @NonNull GeneratedCameraXLibrary.Result<Void> result) { proxy.setZoomRatio(getCameraControlInstance(identifier), ratio, result); } @Override public void startFocusAndMetering( @NonNull Long identifier, @NonNull Long focusMeteringActionId, @NonNull Result<Long> result) { proxy.startFocusAndMetering( getCameraControlInstance(identifier), Objects.requireNonNull(instanceManager.getInstance(focusMeteringActionId)), result); } @Override public void cancelFocusAndMetering(@NonNull Long identifier, @NonNull Result<Void> result) { proxy.cancelFocusAndMetering(getCameraControlInstance(identifier), result); } @Override public void setExposureCompensationIndex( @NonNull Long identifier, @NonNull Long index, @NonNull Result<Long> result) { proxy.setExposureCompensationIndex(getCameraControlInstance(identifier), index, result); } private CameraControl getCameraControlInstance(@NonNull Long identifier) { return Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java", "repo_id": "packages", "token_count": 3913 }
922
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.video.FallbackStrategy; import androidx.camera.video.Quality; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FallbackStrategyHostApi; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoResolutionFallbackRule; /** * Host API implementation for {@link FallbackStrategy}. * * <p>This class may handle instantiating and adding native object instances that are attached to a * Dart instance or handle method calls on the associated native class or an instance of the class. */ public class FallbackStrategyHostApiImpl implements FallbackStrategyHostApi { private final InstanceManager instanceManager; private final FallbackStrategyProxy proxy; /** Proxy for constructor of {@link FallbackStrategy}. */ @VisibleForTesting public static class FallbackStrategyProxy { /** Creates an instance of {@link FallbackStrategy}. */ public @NonNull FallbackStrategy create( @NonNull VideoQuality videoQuality, @NonNull VideoResolutionFallbackRule fallbackRule) { Quality quality = QualitySelectorHostApiImpl.getQualityFromVideoQuality(videoQuality); switch (fallbackRule) { case HIGHER_QUALITY_OR_LOWER_THAN: return FallbackStrategy.higherQualityOrLowerThan(quality); case HIGHER_QUALITY_THAN: return FallbackStrategy.higherQualityThan(quality); case LOWER_QUALITY_OR_HIGHER_THAN: return FallbackStrategy.lowerQualityOrHigherThan(quality); case LOWER_QUALITY_THAN: return FallbackStrategy.lowerQualityThan(quality); } throw new IllegalArgumentException( "Specified fallback rule " + fallbackRule + " unrecognized."); } } /** * Constructs a {@link FallbackStrategyHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public FallbackStrategyHostApiImpl(@NonNull InstanceManager instanceManager) { this(instanceManager, new FallbackStrategyProxy()); } /** * Constructs a {@link FallbackStrategyHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with attached Dart objects * @param proxy proxy for constructor of {@link FallbackStrategy} */ FallbackStrategyHostApiImpl( @NonNull InstanceManager instanceManager, @NonNull FallbackStrategyProxy proxy) { this.instanceManager = instanceManager; this.proxy = proxy; } /** * Creates a {@link FallbackStrategy} instance with the video quality and fallback rule specified. */ @Override public void create( @NonNull Long identifier, @NonNull VideoQuality videoQuality, @NonNull VideoResolutionFallbackRule fallbackRule) { instanceManager.addDartCreatedInstance(proxy.create(videoQuality, fallbackRule), identifier); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java", "repo_id": "packages", "token_count": 995 }
923
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.camera.video.PendingRecording; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PendingRecordingFlutterApi; public class PendingRecordingFlutterApiImpl extends PendingRecordingFlutterApi { private final InstanceManager instanceManager; public PendingRecordingFlutterApiImpl( @Nullable BinaryMessenger binaryMessenger, @Nullable InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } void create(@NonNull PendingRecording pendingRecording, @Nullable Reply<Void> reply) { create(instanceManager.addHostCreatedInstance(pendingRecording), reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java", "repo_id": "packages", "token_count": 286 }
924