code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
name: clean_app description: Generates a new Flutter app with a clean architecture structure version: 1.0.0 repository: https://github.com/Dardila11/mason_bricks/tree/master/bricks/clean_app environment: mason: ">=0.1.0-dev <0.1.0" vars: name: type: string description: Project name default: clean_app prompt: What is the project name? description: type: string description: Project description default: Flutter app starter with a clean architecture structure prompt: What is the description? org: type: string description: Organization name default: com.example prompt: What is your organization name?
mason_bricks/bricks/clean_app/brick.yaml/0
{'file_path': 'mason_bricks/bricks/clean_app/brick.yaml', 'repo_id': 'mason_bricks', 'token_count': 222}
import 'dart:async'; import 'package:flutter/widgets.dart'; class DemoLocalization { final String unicornTitle = "Unicorn"; static DemoLocalization of(BuildContext context) { return Localizations.of<DemoLocalization>(context, DemoLocalization); } } class DemoDelegate extends LocalizationsDelegate<DemoLocalization> { @override bool isSupported(Locale locale) { return true; } @override Future<DemoLocalization> load(Locale locale) async { return DemoLocalization(); } @override bool shouldReload(LocalizationsDelegate<DemoLocalization> old) { return false; } }
meetup-18-10-18/lib/localization.dart/0
{'file_path': 'meetup-18-10-18/lib/localization.dart', 'repo_id': 'meetup-18-10-18', 'token_count': 197}
import 'dart:async'; void unused() { print('foo'); } void main() async { print('jere'); while (true) { await Future.delayed(const Duration(seconds: 1)); } }
meetup-18-10-18/lib/tree-shaking.dart/0
{'file_path': 'meetup-18-10-18/lib/tree-shaking.dart', 'repo_id': 'meetup-18-10-18', 'token_count': 65}
name: mini_sprite repository: https://github.com/bluefireteam/mini_sprite packages: - packages/** - .
mini_sprite/melos.yaml/0
{'file_path': 'mini_sprite/melos.yaml', 'repo_id': 'mini_sprite', 'token_count': 38}
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; part 'hub_entry_result.g.dart'; /// {@template hub_entry_result} /// Model representing a hub entry resulted from a search. /// {@endtemplate} @JsonSerializable() class HubEntryResult extends Equatable { /// {@macro hub_entry} const HubEntryResult({ required this.name, required this.description, required this.path, }); /// {@macro hub_entry_result} factory HubEntryResult.fromJson(Map<String, dynamic> json) => _$HubEntryResultFromJson(json); /// This as a json. Map<String, dynamic> toJson() => _$HubEntryResultToJson(this); /// The name of the entry. final String name; /// The description of the entry. final String description; /// The path of the entry. final String path; @override List<Object?> get props => [ name, description, path, ]; }
mini_sprite/packages/mini_hub_client/lib/src/hub_entry_result.dart/0
{'file_path': 'mini_sprite/packages/mini_hub_client/lib/src/hub_entry_result.dart', 'repo_id': 'mini_sprite', 'token_count': 324}
// ignore_for_file: prefer_const_constructors import 'package:mini_sprite/mini_sprite.dart'; import 'package:test/test.dart'; void main() { group('MiniLibrary', () { test('empty returns an empty library', () { expect( MiniLibrary.empty().sprites, isEmpty, ); }); test('toDataString returns the correct data', () { expect( MiniLibrary( const { 'A': MiniSprite( [ [1, 1], [1, 1], ], ), 'B': MiniSprite( [ [0, 0], [0, 0], ], ), }, ).toDataString(), equals('A|2,2;4,1\nB|2,2;4,0'), ); }); test('fromDataString returns the correct parsed instance', () { expect( MiniLibrary.fromDataString('A|2,2;4,1\nB|2,2;4,0'), equals( MiniLibrary( const { 'A': MiniSprite( [ [1, 1], [1, 1], ], ), 'B': MiniSprite( [ [0, 0], [0, 0], ], ), }, ), ), ); }); }); }
mini_sprite/packages/mini_sprite/test/src/mini_library_test.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite/test/src/mini_library_test.dart', 'repo_id': 'mini_sprite', 'token_count': 823}
import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mini_sprite_editor/config/config.dart'; import 'package:mini_sprite_editor/l10n/l10n.dart'; import 'package:mini_sprite_editor/library/library.dart'; import 'package:mini_sprite_editor/map/map.dart'; import 'package:mini_sprite_editor/sprite/view/view.dart'; class MapPage extends StatelessWidget { const MapPage({super.key}); @override Widget build(BuildContext context) { return BlocProvider<MapToolCubit>( create: (_) => MapToolCubit(), child: const MapView(), ); } } class MapView extends StatelessWidget { const MapView({super.key}); @override Widget build(BuildContext context) { final mapToolCubit = context.watch<MapToolCubit>(); final mapToolState = mapToolCubit.state; final tool = mapToolState.tool; final gridActive = mapToolState.gridActive; final l10n = context.l10n; return Padding( padding: const EdgeInsets.all(8), child: Column( children: [ Card( child: Row( children: [ IconButton( key: const Key('resize_map_key'), onPressed: () async { final cubit = context.read<MapCubit>(); final value = await MapSizeDialog.show(context); if (value != null) { cubit.setSize( value.dx.toInt(), value.dy.toInt(), ); } }, tooltip: l10n.mapSizeTitle, icon: const Icon(Icons.iso_sharp), ), IconButton( key: const Key('clear_map_key'), onPressed: () async { final cubit = context.read<MapCubit>(); final value = await ConfirmDialog.show(context); if (value ?? false) { cubit.clearMap(); } }, tooltip: l10n.clearMap, icon: const Icon(Icons.delete), ), IconButton( key: const Key('toogle_grid_key'), onPressed: () async { context.read<MapToolCubit>().toogleGrid(); }, tooltip: l10n.toogleGrid, icon: Icon( gridActive ? Icons.grid_on : Icons.grid_off, ), ), IconButton( key: const Key('copy_to_clipboard_key'), onPressed: () { context.read<MapCubit>().copyToClipboard(); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(l10n.copiedWithSuccess)), ); }, tooltip: l10n.copyToClipboard, icon: const Icon(Icons.download), ), IconButton( key: const Key('import_from_clipboard_key'), onPressed: () { context.read<MapCubit>().importFromClipboard(); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(l10n.importSuccess)), ); }, tooltip: l10n.importFromClipBoard, icon: const Icon(Icons.import_export), ), IconButton( key: const Key('config_key'), onPressed: () { ConfigDialog.show(context); }, tooltip: l10n.configurations, icon: const Icon(Icons.settings), ), ], ), ), Expanded( child: Stack( children: [ Positioned.fill( child: Row( children: [ Expanded( child: ClipRect( child: GameWidget.controlled( gameFactory: () { return MapBoardGame( configCubit: context.read<ConfigCubit>(), libraryCubit: context.read<LibraryCubit>(), mapCubit: context.read<MapCubit>(), mapToolCubit: context.read<MapToolCubit>(), primaryColor: Theme.of(context) .buttonTheme .colorScheme ?.primary ?? Colors.blue, ); }, ), ), ), Column( children: [ SizedBox( width: 122, child: Card( child: Center( child: Wrap( children: [ IconButton( key: const Key('map_cursor_key'), onPressed: tool == MapTool.none ? null : () { context .read<MapToolCubit>() .selectTool(MapTool.none); }, tooltip: l10n.cursor, icon: const Icon(Icons.mouse), ), IconButton( key: const Key('map_brush_key'), onPressed: tool == MapTool.brush ? null : () { context .read<MapToolCubit>() .selectTool(MapTool.brush); }, tooltip: l10n.brush, icon: const Icon(Icons.brush), ), IconButton( key: const Key('map_eraser_key'), onPressed: tool == MapTool.eraser ? null : () { context .read<MapToolCubit>() .selectTool(MapTool.eraser); }, tooltip: l10n.eraser, icon: const Icon(Icons.rectangle), ), IconButton( key: const Key('map_zoom_in_key'), onPressed: () { context .read<MapToolCubit>() .increaseZoom(); }, tooltip: l10n.zoomIn, icon: const Icon(Icons.zoom_in), ), IconButton( key: const Key('map_zoom_out_key'), onPressed: () { context .read<MapToolCubit>() .decreaseZoom(); }, tooltip: l10n.zoomOut, icon: const Icon(Icons.zoom_out), ), ], ), ), ), ), const Expanded( child: LibraryPanel(readOnly: true), ), ], ), ], ), ), const Positioned( top: 8, left: 8, child: ObjectPanel(), ), ], ), ), ], ), ); } }
mini_sprite/packages/mini_sprite_editor/lib/map/view/map_page.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/map/view/map_page.dart', 'repo_id': 'mini_sprite', 'token_count': 6401}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mini_sprite_editor/config/config.dart'; import 'package:mini_sprite_editor/l10n/l10n.dart'; import 'package:mini_sprite_editor/library/library.dart'; import 'package:mini_sprite_editor/sprite/cubit/tools_cubit.dart'; import 'package:mini_sprite_editor/sprite/sprite.dart'; class SpritePage extends StatelessWidget { const SpritePage({super.key}); @override Widget build(BuildContext context) { return BlocProvider<ToolsCubit>( create: (context) => ToolsCubit(), child: const SpriteView(), ); } } class SpriteView extends StatelessWidget { const SpriteView({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final spriteState = context.watch<SpriteCubit>().state; final toolsState = context.watch<ToolsCubit>().state; final configCubit = context.watch<ConfigCubit>(); final palette = configCubit.palette(); final configState = configCubit.state; final libraryState = context.watch<LibraryCubit>().state; final pixels = spriteState.pixels; final cursorPosition = spriteState.cursorPosition; final tool = toolsState.tool; final gridActive = toolsState.gridActive; final pixelSize = toolsState.pixelSize; final spriteHeight = pixelSize * pixels.length; final spriteWidth = pixelSize * pixels[0].length; return PageShortcuts( child: Stack( children: [ Positioned.fill( child: SizedBox.expand( child: Center( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: SingleChildScrollView( child: MouseRegion( onHover: (event) { context.read<SpriteCubit>().cursorHover( event.localPosition, pixelSize.toDouble(), tool, toolsState.currentColor, ); }, child: GestureDetector( onPanStart: (event) { context.read<SpriteCubit>().cursorDown( event.localPosition, pixelSize.toDouble(), tool, toolsState.currentColor, ); }, onPanEnd: (event) { context.read<SpriteCubit>().cursorUp( tool, toolsState.currentColor, ); }, onPanUpdate: (event) { context.read<SpriteCubit>().cursorHover( event.localPosition, pixelSize.toDouble(), tool, toolsState.currentColor, ); }, child: BlocListener<LibraryCubit, LibraryState>( listenWhen: (previous, current) => previous.selected != current.selected, listener: (context, state) { context.read<SpriteCubit>().setSprite( state.sprites[state.selected]!.pixels, ); }, child: Container( color: configState.backgroundColor, key: const Key('board_key'), width: spriteWidth.toDouble(), height: spriteHeight.toDouble(), child: Column( children: [ for (var y = 0; y < pixels.length; y++) Row( children: [ for (var x = 0; x < pixels[y].length; x++) PixelCell( pixelSize: pixelSize, color: pixels[y][x] >= 0 ? palette[pixels[y][x]] : configState.backgroundColor, hasBorder: gridActive, hovered: cursorPosition == Offset( x.toDouble(), y.toDouble(), ), ), ], ), ], ), ), ), ), ), ), ), ), ), ), Positioned( top: 8, right: 8, left: 8, child: Card( child: Row( children: [ IconButton( key: const Key('resize_sprite_key'), onPressed: () async { final cubit = context.read<SpriteCubit>(); final value = await SpriteSizeDialog.show(context); if (value != null) { cubit.setSize( value.dx.toInt(), value.dy.toInt(), ); } }, tooltip: l10n.spriteSizeTitle, icon: const Icon(Icons.iso_sharp), ), IconButton( key: const Key('clear_sprite_key'), onPressed: () async { final cubit = context.read<SpriteCubit>(); final value = await ConfirmDialog.show(context); if (value ?? false) { cubit.clearSprite(); } }, tooltip: l10n.clearSprite, icon: const Icon(Icons.delete), ), IconButton( key: const Key('toogle_grid_key'), onPressed: () async { context.read<ToolsCubit>().toogleGrid(); }, tooltip: l10n.toogleGrid, icon: Icon( gridActive ? Icons.grid_on : Icons.grid_off, ), ), IconButton( key: const Key('copy_to_clipboard_key'), onPressed: () { context.read<SpriteCubit>().copyToClipboard(); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(l10n.copiedWithSuccess)), ); }, tooltip: l10n.copyToClipboard, icon: const Icon(Icons.download), ), IconButton( key: const Key('import_from_clipboard_key'), onPressed: () { context.read<SpriteCubit>().importFromClipboard(); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(l10n.importSuccess)), ); }, tooltip: l10n.importFromClipBoard, icon: const Icon(Icons.import_export), ), IconButton( key: const Key('export_to_image'), onPressed: () async { final messenger = ScaffoldMessenger.of(context); await context.read<SpriteCubit>().exportToImage( pixelSize: pixelSize, palette: palette, backgroundColor: configState.backgroundColor, ); messenger.showSnackBar( SnackBar(content: Text(l10n.spriteExported)), ); }, tooltip: l10n.exportToImage, icon: const Icon(Icons.image), ), IconButton( key: const Key('config_key'), onPressed: () { ConfigDialog.show(context); }, tooltip: l10n.configurations, icon: const Icon(Icons.settings), ), ], ), ), ), Positioned( top: 64, right: 64, child: Card( child: Padding( padding: const EdgeInsets.all(8), child: Column( children: [ InkWell( onTap: () { context.read<ToolsCubit>().setColor(0); }, child: Container( color: configState.filledColor.withOpacity( toolsState.currentColor == 0 ? .2 : 1, ), width: 16, height: 16, ), ), InkWell( onTap: () { context.read<ToolsCubit>().setColor(1); }, child: Container( color: configState.unfilledColor.withOpacity( toolsState.currentColor == 1 ? .2 : 1, ), width: 16, height: 16, ), ), ], ), ), ), ), Positioned( top: 64, right: 8, child: Card( child: Column( children: [ IconButton( key: const Key('brush_key'), onPressed: tool == SpriteTool.brush ? null : () { context .read<ToolsCubit>() .selectTool(SpriteTool.brush); }, tooltip: l10n.brush, icon: const Icon(Icons.brush), ), IconButton( key: const Key('eraser_key'), onPressed: tool == SpriteTool.eraser ? null : () { context .read<ToolsCubit>() .selectTool(SpriteTool.eraser); }, tooltip: l10n.eraser, icon: const Icon(Icons.rectangle), ), IconButton( key: const Key('bucket_key'), onPressed: tool == SpriteTool.bucket ? null : () { context .read<ToolsCubit>() .selectTool(SpriteTool.bucket); }, tooltip: l10n.bucket, icon: const Icon(Icons.egg_sharp), ), IconButton( key: const Key('bucket_eraser_key'), onPressed: tool == SpriteTool.bucketEraser ? null : () { context .read<ToolsCubit>() .selectTool(SpriteTool.bucketEraser); }, tooltip: l10n.bucketEraser, icon: const Icon(Icons.egg_outlined), ), IconButton( key: const Key('zoom_in_key'), onPressed: () { context.read<ToolsCubit>().zoomIn(); }, tooltip: l10n.zoomIn, icon: const Icon(Icons.zoom_in), ), IconButton( key: const Key('zoom_out_key'), onPressed: () { context.read<ToolsCubit>().zoomOut(); }, tooltip: l10n.zoomOut, icon: const Icon(Icons.zoom_out), ), ], ), ), ), Positioned( top: 64, left: 8, bottom: libraryState.sprites.isEmpty ? null : 16, child: const LibraryPanel(), ), ], ), ); } }
mini_sprite/packages/mini_sprite_editor/lib/sprite/view/sprite_page.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/sprite/view/sprite_page.dart', 'repo_id': 'mini_sprite', 'token_count': 8867}
// ignore_for_file: prefer_const_constructors, one_member_abstracts import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mini_sprite/mini_sprite.dart'; import 'package:mini_sprite_editor/library/library.dart'; import 'package:mocktail/mocktail.dart'; abstract class _SetClipboardStub { Future<void> setClipboardData(ClipboardData data); } class SetClipboardStub extends Mock implements _SetClipboardStub {} abstract class _GetClipboardStub { Future<ClipboardData?> getClipboardData(String format); } class GetClipboardStub extends Mock implements _GetClipboardStub {} void main() { group('LibraryCubit', () { setUpAll(() { registerFallbackValue(const ClipboardData(text: '')); }); blocTest<LibraryCubit, LibraryState>( 'startCollection initializes the state', build: LibraryCubit.new, act: (cubit) => cubit.startCollection([ [1], ]), expect: () => [ LibraryState( sprites: const { 'sprite_1': MiniSprite([ [1], ]), }, selected: 'sprite_1', ), ], ); blocTest<LibraryCubit, LibraryState>( 'updates the selected sprite', seed: () => LibraryState( sprites: const { 'player': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'player', ), build: LibraryCubit.new, act: (cubit) => cubit.updateSelected([ [1, 0], [0, 1], ]), expect: () => [ LibraryState( sprites: const { 'player': MiniSprite( [ [1, 0], [0, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'player', ), ], ); blocTest<LibraryCubit, LibraryState>( 'renames a sprite', seed: () => LibraryState( sprites: const { 'player': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'player', ), build: LibraryCubit.new, act: (cubit) => cubit.rename('player', 'char'), expect: () => [ LibraryState( sprites: const { 'char': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'char', ), ], ); blocTest<LibraryCubit, LibraryState>( 'renames a sprite that is not selected', seed: () => LibraryState( sprites: const { 'player': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'tile', ), build: LibraryCubit.new, act: (cubit) => cubit.rename('player', 'char'), expect: () => [ LibraryState( sprites: const { 'char': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'tile', ), ], ); blocTest<LibraryCubit, LibraryState>( 'removes a sprite', seed: () => LibraryState( sprites: const { 'player': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'tile', ), build: LibraryCubit.new, act: (cubit) => cubit.removeSprite('player'), expect: () => [ LibraryState( sprites: const { 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'tile', ), ], ); blocTest<LibraryCubit, LibraryState>( 'removes a sprite that is selected', seed: () => LibraryState( sprites: const { 'player': MiniSprite( [ [1, 1], [1, 1], ], ), 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'player', ), build: LibraryCubit.new, act: (cubit) => cubit.removeSprite('player'), expect: () => [ LibraryState( sprites: const { 'tile': MiniSprite( [ [0, 1], [1, 0], ], ), }, selected: 'tile', ), ], ); blocTest<LibraryCubit, LibraryState>( 'adds a sprite', seed: () => const LibraryState( sprites: {}, selected: '', ), build: LibraryCubit.new, act: (cubit) => cubit.addSprite(2, 2), expect: () => [ LibraryState( sprites: const { 'sprite_1': MiniSprite( [ [-1, -1], [-1, -1], ], ), }, selected: '', ), ], ); blocTest<LibraryCubit, LibraryState>( 'can handle name conflict on addSprite', seed: () => const LibraryState( sprites: { 'sprite_2': MiniSprite( [ [0, 0], [0, 0], ], ), }, selected: '', ), build: LibraryCubit.new, act: (cubit) => cubit.addSprite(2, 2), expect: () => [ LibraryState( sprites: const { 'sprite_2': MiniSprite( [ [0, 0], [0, 0], ], ), 'sprite_3': MiniSprite( [ [-1, -1], [-1, -1], ], ), }, selected: '', ), ], ); blocTest<LibraryCubit, LibraryState>( 'selects a sprite', seed: () => LibraryState( sprites: {'player': MiniSprite.empty(1, 1)}, selected: '', ), build: LibraryCubit.new, act: (cubit) => cubit.select('player'), expect: () => [ LibraryState( sprites: {'player': MiniSprite.empty(1, 1)}, selected: 'player', ), ], ); }); group('importFromClipboard', () { late GetClipboardStub stub; final sprite = MiniSprite(const [ [1, 0], [0, 1], ]); final library = MiniLibrary({ 'player': sprite, }); setUp(() { stub = GetClipboardStub(); }); blocTest<LibraryCubit, LibraryState>( 'emits the updated library when there is data', build: () => LibraryCubit(getClipboardData: stub.getClipboardData), setUp: () { when(() => stub.getClipboardData('text/plain')).thenAnswer( (_) async => ClipboardData(text: library.toDataString()), ); }, act: (cubit) => cubit.importFromClipboard(), expect: () => [ LibraryState(sprites: {'player': sprite}, selected: 'player'), ], ); }); test( 'copyToClipboard sets the serialized library to the clipboard', () async { final stub = SetClipboardStub(); when(() => stub.setClipboardData(any())).thenAnswer((_) async {}); final cubit = LibraryCubit(setClipboardData: stub.setClipboardData); final expected = MiniLibrary(cubit.state.sprites).toDataString(); cubit.copyToClipboard(); verify( () => stub.setClipboardData( any( that: isA<ClipboardData>().having( (data) => data.text, 'text', equals(expected), ), ), ), ).called(1); }, ); }
mini_sprite/packages/mini_sprite_editor/test/library/cubit/library_cubit_test.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/test/library/cubit/library_cubit_test.dart', 'repo_id': 'mini_sprite', 'token_count': 4974}
import 'package:flame/game.dart' hide Route; import 'package:flutter/material.dart'; import 'package:mini_treasure_quest/game/game.dart'; class GamePage extends StatelessWidget { const GamePage({super.key, required this.stage}); final int stage; static Route<void> route(int stageId) { return MaterialPageRoute( builder: (context) { return GamePage(stage: stageId); }, ); } @override Widget build(BuildContext context) { return GameView(stage: stage); } } class GameView extends StatelessWidget { const GameView({super.key, required this.stage}); final int stage; @override Widget build(BuildContext context) { return Scaffold( body: GameWidget( game: MiniTreasureQuest(stage: stage), ), ); } }
mini_sprite/packages/mini_treasure_quest/lib/game/views/game_view.dart/0
{'file_path': 'mini_sprite/packages/mini_treasure_quest/lib/game/views/game_view.dart', 'repo_id': 'mini_sprite', 'token_count': 281}
part of '../observable_collections.dart'; Atom _listAtom<T>(ReactiveContext context) { final ctx = context ?? mainContext; return Atom(name: ctx.nameFor('ObservableList<$T>'), context: ctx); } /// Create a list of [T]. /// /// The ObservableList tracks the various read-methods (eg: [List.first], [List.last]) and /// write-methods (eg: [List.add], [List.insert]) making it easier to use it inside reactions. /// /// ```dart /// final list = ObservableList<int>.of([1]); /// /// autorun((_) { /// print(list.first); /// }) // prints 1 /// /// list[0] = 100; // autorun prints 100 /// ``` class ObservableList<T> with // ignore: prefer_mixin ListMixin<T> implements Listenable<ListChange<T>> { ObservableList({ReactiveContext context}) : this._wrap(context, _listAtom<T>(context), []); ObservableList.of(Iterable<T> elements, {ReactiveContext context}) : this._wrap(context, _listAtom<T>(context), List<T>.of(elements, growable: true)); ObservableList._wrap(ReactiveContext context, this._atom, this._list) : _context = context ?? mainContext; final ReactiveContext _context; final Atom _atom; final List<T> _list; Listeners<ListChange<T>> _listenersField; Listeners<ListChange<T>> get _listeners => _listenersField ??= Listeners(_context); String get name => _atom.name; @override int get length { _atom.reportObserved(); return _list.length; } @override set length(int value) { _context.checkIfStateModificationsAreAllowed(_atom); _list.length = value; _notifyListUpdate(0, null, null); } @override List<T> operator +(List<T> other) { final newList = _list + other; _atom.reportObserved(); return newList; } @override T operator [](int index) { _atom.reportObserved(); return _list[index]; } @override void operator []=(int index, T value) { _context.checkIfStateModificationsAreAllowed(_atom); final oldValue = _list[index]; if (oldValue != value) { _list[index] = value; _notifyChildUpdate(index, value, oldValue); } } @override void add(T element) { _context.checkIfStateModificationsAreAllowed(_atom); _list.add(element); _notifyListUpdate(_list.length, [element], null); } @override void addAll(Iterable<T> iterable) { _context.checkIfStateModificationsAreAllowed(_atom); _list.addAll(iterable); _notifyListUpdate(0, iterable.toList(growable: false), null); } @override Iterator<T> get iterator { _atom.reportObserved(); return _list.iterator; } @override int lastIndexWhere(bool Function(T element) test, [int start]) { _atom.reportObserved(); return _list.lastIndexWhere(test, start); } @override T lastWhere(bool Function(T element) test, {T Function() orElse}) { _atom.reportObserved(); return _list.lastWhere(test, orElse: orElse); } @override T get single { _atom.reportObserved(); return _list.single; } @override List<T> sublist(int start, [int end]) { _atom.reportObserved(); return _list.sublist(start, end); } @override Map<int, T> asMap() => ObservableMap._wrap(_context, _list.asMap(), _atom); @override List<R> cast<R>() => ObservableList._wrap(_context, _atom, _list.cast<R>()); @override List<T> toList({bool growable = true}) { _atom.reportObserved(); return _list.toList(growable: growable); } @override set first(T value) { _context.checkIfStateModificationsAreAllowed(_atom); final oldValue = _list.first; _list.first = value; _notifyChildUpdate(0, value, oldValue); } @override void clear() { _context.checkIfStateModificationsAreAllowed(_atom); final oldItems = _list.toList(growable: false); _list.clear(); _notifyListUpdate(0, null, oldItems); } @override void fillRange(int start, int end, [T fill]) { _context.checkIfStateModificationsAreAllowed(_atom); _list.fillRange(start, end, fill); _notifyListUpdate(start, null, null); } @override void insert(int index, T element) { _context.checkIfStateModificationsAreAllowed(_atom); _list.insert(index, element); _notifyListUpdate(index, [element], null); } @override void insertAll(int index, Iterable<T> iterable) { _context.checkIfStateModificationsAreAllowed(_atom); _list.insertAll(index, iterable); _notifyListUpdate(index, iterable.toList(growable: false), null); } @override bool remove(Object element) { _context.checkIfStateModificationsAreAllowed(_atom); final index = _list.indexOf(element); final didRemove = _list.remove(element); if (didRemove) { _notifyListUpdate(index, null, element == null ? null : [element]); } return didRemove; } @override T removeAt(int index) { _context.checkIfStateModificationsAreAllowed(_atom); final value = _list.removeAt(index); _notifyListUpdate(index, null, value == null ? null : [value]); return value; } @override T removeLast() { _context.checkIfStateModificationsAreAllowed(_atom); final value = _list.removeLast(); // Index is _list.length as it points to the index before the last element is removed _notifyListUpdate(_list.length, null, value == null ? null : [value]); return value; } @override void removeRange(int start, int end) { _context.checkIfStateModificationsAreAllowed(_atom); final removedItems = _list.sublist(start, end); _list.removeRange(start, end); _notifyListUpdate(start, null, removedItems); } @override void removeWhere(bool Function(T element) test) { _context.checkIfStateModificationsAreAllowed(_atom); final removedItems = _list.where(test).toList(growable: false); _list.removeWhere(test); _notifyListUpdate(0, null, removedItems); } @override void replaceRange(int start, int end, Iterable<T> newContents) { _context.checkIfStateModificationsAreAllowed(_atom); _list.replaceRange(start, end, newContents); _notifyListUpdate(start, null, null); } @override void retainWhere(bool Function(T element) test) { _context.checkIfStateModificationsAreAllowed(_atom); final removedItems = _list.where((_) => !test(_)).toList(growable: false); _list.retainWhere(test); _notifyListUpdate(0, null, removedItems); } @override void setAll(int index, Iterable<T> iterable) { _context.checkIfStateModificationsAreAllowed(_atom); _list.setAll(index, iterable); _notifyListUpdate(index, null, null); } @override void setRange(int start, int end, Iterable<T> iterable, [int skipCount = 0]) { _context.checkIfStateModificationsAreAllowed(_atom); _list.setRange(start, end, iterable, skipCount); _notifyListUpdate(start, null, null); } @override void shuffle([Random random]) { _context.checkIfStateModificationsAreAllowed(_atom); _list.shuffle(random); _notifyListUpdate(0, null, null); } @override void sort([int Function(T a, T b) compare]) { _context.checkIfStateModificationsAreAllowed(_atom); _list.sort(compare); _notifyListUpdate(0, null, null); } @override Dispose observe(Listener<ListChange<T>> listener, {bool fireImmediately}) { if (fireImmediately == true) { final change = ListChange( object: this, index: 0, type: OperationType.add, added: toList(growable: false)); listener(change); } return _listeners.add(listener); } void _notifyChildUpdate(int index, T newValue, T oldValue) { _atom.reportChanged(); final change = ListChange( index: index, newValue: newValue, oldValue: oldValue, object: this, type: OperationType.update); _listeners.notifyListeners(change); } void _notifyListUpdate(int index, List<T> added, List<T> removed) { _atom.reportChanged(); final change = ListChange( index: index, added: added, removed: removed, object: this, type: (added != null && added.isNotEmpty) ? OperationType.add : (removed != null && removed.isNotEmpty ? OperationType.remove : OperationType.update)); _listeners.notifyListeners(change); } } typedef ListChangeListener<TNotification> = void Function( ListChange<TNotification>); class ListChange<T> { ListChange( {this.index, this.type, this.newValue, this.oldValue, this.object, this.added, this.removed}); final OperationType type; final int index; final T newValue; final T oldValue; final List<T> added; final List<T> removed; final ObservableList<T> object; } @visibleForTesting ObservableList<T> wrapInObservableList<T>(Atom atom, List<T> list) => ObservableList._wrap(mainContext, atom, list);
mobx.dart/mobx/lib/src/api/observable_collections/observable_list.dart/0
{'file_path': 'mobx.dart/mobx/lib/src/api/observable_collections/observable_list.dart', 'repo_id': 'mobx.dart', 'token_count': 3351}
import 'dart:async'; const Duration ms = Duration(milliseconds: 1); Timer Function(void Function()) createDelayedScheduler(int delayMs) => (fn) => Timer(ms * delayMs, fn);
mobx.dart/mobx/lib/src/utils.dart/0
{'file_path': 'mobx.dart/mobx/lib/src/utils.dart', 'repo_id': 'mobx.dart', 'token_count': 61}
import 'package:mobx/mobx.dart'; import 'package:test/test.dart'; void main() { group('observe', () { test('works', () { final x = Observable(10); var executed = false; final dispose = x.observe((change) { expect(change.newValue, equals(10)); expect(change.oldValue, isNull); executed = true; }, fireImmediately: true); expect(executed, isTrue); dispose(); }); test('fires when changed', () { final x = Observable(10); var executed = false; final dispose = x.observe((change) { expect(change.newValue, equals(100)); expect(change.oldValue, 10); executed = true; }); expect(executed, isFalse); x.value = 100; expect(executed, isTrue); dispose(); }); test('can be disposed', () { final x = Observable(10); var executed = false; final dispose = x.observe((change) { executed = true; }, fireImmediately: true); expect(executed, isTrue); dispose(); x.value = 100; executed = false; expect(executed, isFalse); }); test('can have multiple listeners', () { final x = Observable(10); var executionCount = 0; final dispose1 = x.observe((change) { executionCount++; }); final dispose2 = x.observe((change) { executionCount++; }); final dispose3 = x.observe((change) { executionCount++; }); x.value = 100; expect(executionCount, 3); dispose1(); dispose2(); dispose3(); x.value = 200; expect(executionCount, 3); // no change here }); }); group('onBecomeObserved / onBecomeUnobserved', () { test('works for observables', () { final x = Observable(10); var executionCount = 0; final d1 = x.onBecomeObserved(() { executionCount++; }); final d2 = x.onBecomeUnobserved(() { executionCount++; }); final d3 = autorun((_) { x.value; }); expect(executionCount, equals(1)); d3(); // dispose the autorun expect(executionCount, equals(2)); d1(); d2(); }); test('works for computeds', () { final x = Observable(10); final x1 = Computed(() { // ignore: unnecessary_statements x.value + 1; }); var executionCount = 0; final d1 = x1.onBecomeObserved(() { executionCount++; }); final d2 = x1.onBecomeUnobserved(() { executionCount++; }); final d3 = autorun((_) { x1.value; }); expect(executionCount, equals(1)); d3(); // dispose the autorun expect(executionCount, equals(2)); d1(); d2(); }); test('throws if null is passed', () { final x = Observable(10); expect(() { x.onBecomeObserved(null); }, throwsException); expect(() { x.onBecomeUnobserved(null); }, throwsException); }); test('multiple can be attached', () { final x = Observable(10); var observedCount = 0; var unobservedCount = 0; final disposers = <Function>[ x.onBecomeObserved(() { observedCount++; }), x.onBecomeObserved(() { observedCount++; }), x.onBecomeUnobserved(() { unobservedCount++; }), x.onBecomeUnobserved(() { unobservedCount++; }), ]; final d = autorun((_) { x.value; }); expect(observedCount, equals(2)); d(); expect(unobservedCount, equals(2)); // ignore: avoid_function_literals_in_foreach_calls disposers.forEach((f) => f()); }); test('fails for null handler', () { final x = Observable(100); var observeFailed = false; var interceptFailed = false; try { x.observe(null); // ignore: avoid_catching_errors } on AssertionError catch (_) { observeFailed = true; } expect(observeFailed, isTrue); try { x.intercept(null); // ignore: avoid_catching_errors } on AssertionError catch (_) { interceptFailed = true; } expect(interceptFailed, isTrue); }); }); }
mobx.dart/mobx/test/observe_test.dart/0
{'file_path': 'mobx.dart/mobx/test/observe_test.dart', 'repo_id': 'mobx.dart', 'token_count': 1970}
library mobx_codegen_example;
mobx.dart/mobx_codegen/example/lib/example.dart/0
{'file_path': 'mobx.dart/mobx_codegen/example/lib/example.dart', 'repo_id': 'mobx.dart', 'token_count': 10}
import 'package:mobx_codegen/src/template/method_override.dart'; class ObservableFutureTemplate { MethodOverrideTemplate method; @override String toString() => """ @override ObservableFuture${method.returnTypeArgs} ${method.name}${method.typeParams}(${method.params}) { final _\$future = super.${method.name}${method.typeArgs}(${method.args}); return ObservableFuture${method.returnTypeArgs}(_\$future); }"""; }
mobx.dart/mobx_codegen/lib/src/template/observable_future.dart/0
{'file_path': 'mobx.dart/mobx_codegen/lib/src/template/observable_future.dart', 'repo_id': 'mobx.dart', 'token_count': 143}
import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:hnpwa_client/hnpwa_client.dart'; import 'package:mobx/mobx.dart'; import 'package:mobx_examples/hackernews/news_store.dart'; class HackerNewsExample extends StatefulWidget { const HackerNewsExample(); @override _HackerNewsExampleState createState() => _HackerNewsExampleState(); } class _HackerNewsExampleState extends State<HackerNewsExample> with SingleTickerProviderStateMixin { final HackerNewsStore store = HackerNewsStore(); TabController _tabController; final _tabs = [FeedType.latest, FeedType.top]; @override void initState() { _tabController = TabController(length: 2, vsync: this) ..addListener(_onTabChange); store.loadNews(_tabs.first); super.initState(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: const Text('Hacker News'), bottom: TabBar( controller: _tabController, tabs: const [Tab(text: 'Newest'), Tab(text: 'Top')], ), ), body: SafeArea( child: TabBarView(controller: _tabController, children: [ FeedItemsView(store, FeedType.latest), FeedItemsView(store, FeedType.top), ]), )); void _onTabChange() { store.loadNews(_tabs[_tabController.index]); } } class FeedItemsView extends StatelessWidget { const FeedItemsView(this.store, this.type); final HackerNewsStore store; final FeedType type; @override Widget build(BuildContext context) => Observer(builder: (_) { final future = type == FeedType.latest ? store.latestItemsFuture : store.topItemsFuture; switch (future.status) { case FutureStatus.pending: return Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ CircularProgressIndicator(), Text('Loading items...'), ], ); case FutureStatus.rejected: return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'Failed to load items.', style: TextStyle(color: Colors.red), ), RaisedButton( child: const Text('Tap to try again'), onPressed: _refresh, ) ], ); case FutureStatus.fulfilled: final List<FeedItem> items = future.result; return RefreshIndicator( onRefresh: _refresh, child: ListView.builder( physics: const AlwaysScrollableScrollPhysics(), itemCount: items.length, itemBuilder: (_, index) { final item = items[index]; return ListTile( leading: Text( '${item.points}', style: const TextStyle(fontSize: 20), ), title: Text( item.title, style: const TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text( '- ${item.user}, ${item.commentsCount} comment(s)'), onTap: () => store.openUrl(item.url), ); }), ); } }); Future _refresh() => (type == FeedType.latest) ? store.fetchLatest() : store.fetchTop(); }
mobx.dart/mobx_examples/lib/hackernews/news_widgets.dart/0
{'file_path': 'mobx.dart/mobx_examples/lib/hackernews/news_widgets.dart', 'repo_id': 'mobx.dart', 'token_count': 1768}
name: example concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: push: branches: - main pull_request: branches: - main jobs: semantic_pull_request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_channel: stable working_directory: example runs_on: macos-latest
mockingjay/.github/workflows/example.yaml/0
{'file_path': 'mockingjay/.github/workflows/example.yaml', 'repo_id': 'mockingjay', 'token_count': 204}
import 'package:example/ui/ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import '../helpers.dart'; class FakeRoute<T> extends Fake implements Route<T> {} void main() { group('HomeScreen', () { const showPincodeScreenTextButtonKey = Key('homeScreen_showPincodeScreen_textButton'); const showQuizDialogTextButtonKey = Key('homeScreen_showQuizDialog_textButton'); late MockNavigator navigator; setUpAll(() { registerFallbackValue(FakeRoute<String?>()); registerFallbackValue(FakeRoute<QuizOption>()); }); setUp(() { navigator = MockNavigator(); when(() => navigator.canPop()).thenReturn(true); when(() => navigator.push<String?>(any())).thenAnswer((_) async => null); when( () => navigator.push<QuizOption>(any()), ).thenAnswer((_) async => null); }); group('show pincode screen button', () { testWidgets('is rendered', (tester) async { await tester.pumpTest( builder: (context) { return const HomeScreen(); }, ); expect( find.byKey(showPincodeScreenTextButtonKey), findsOneWidget, ); }); testWidgets('navigates to PincodeScreen when pressed', (tester) async { await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap( find.byKey(showPincodeScreenTextButtonKey), ); verify( () => navigator.push<String?>( any(that: isRoute<String?>(whereName: equals('/pincode_screen'))), ), ).called(1); }); testWidgets('displays snackbar with selected pincode', (tester) async { when( () => navigator.push<String?>( any(that: isRoute<String?>(whereName: equals('/pincode_screen'))), ), ).thenAnswer((_) async => '123456'); await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showPincodeScreenTextButtonKey)); await tester.pumpAndSettle(); expect( find.widgetWithText(SnackBar, 'Pincode is "123456" 🔒'), findsOneWidget, ); }); testWidgets( 'displays snackbar when no pincode was submitted', (tester) async { when( () => navigator.push<String?>( any( that: isRoute<String?>( whereName: equals('/pincode_screen'), ), ), ), ).thenAnswer((_) async => null); await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showPincodeScreenTextButtonKey)); await tester.pumpAndSettle(); expect( find.widgetWithText(SnackBar, 'No pincode submitted. 😲'), findsOneWidget, ); }, ); }); group('show quiz dialog button', () { testWidgets('is rendered', (tester) async { await tester.pumpTest( builder: (context) { return const HomeScreen(); }, ); expect( find.byKey(showQuizDialogTextButtonKey), findsOneWidget, ); }); testWidgets('shows quiz dialog when pressed', (tester) async { await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showQuizDialogTextButtonKey)); verify( () => navigator.push<QuizOption>(any(that: isRoute<QuizOption>())), ).called(1); }); testWidgets( 'displays snackbar when pizza was selected', (tester) async { when( () => navigator.push<QuizOption>(any(that: isRoute<QuizOption>())), ).thenAnswer((_) async => QuizOption.pizza); await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showQuizDialogTextButtonKey)); await tester.pumpAndSettle(); expect( find.widgetWithText(SnackBar, 'Pizza all the way! 🍕'), findsOneWidget, ); }, ); testWidgets( 'displays snackbar when hamburger was selected', (tester) async { when( () => navigator.push<QuizOption>(any(that: isRoute<QuizOption>())), ).thenAnswer((_) async => QuizOption.hamburger); await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showQuizDialogTextButtonKey)); await tester.pumpAndSettle(); expect( find.widgetWithText(SnackBar, 'Hamburger all the way! 🍔'), findsOneWidget, ); }, ); testWidgets( 'displays snackbar when no answer was selected', (tester) async { when( () => navigator.push<QuizOption>(any(that: isRoute<QuizOption>())), ).thenAnswer((_) async => null); await tester.pumpTest( builder: (context) { return MockNavigatorProvider( navigator: navigator, child: const HomeScreen(), ); }, ); await tester.tap(find.byKey(showQuizDialogTextButtonKey)); await tester.pumpAndSettle(); expect( find.widgetWithText(SnackBar, 'No answer selected. 😲'), findsOneWidget, ); }, ); }); }); }
mockingjay/example/test/ui/home_screen_test.dart/0
{'file_path': 'mockingjay/example/test/ui/home_screen_test.dart', 'repo_id': 'mockingjay', 'token_count': 3271}
// Copyright 2016 Dart Mockito authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:collection/collection.dart'; import 'package:matcher/matcher.dart'; import 'package:meta/meta.dart'; import 'package:mockito/src/mock.dart'; /// Returns a matcher that expects an invocation that matches arguments given. /// /// Both [positionalArguments] and [namedArguments] can also be [Matcher]s: /// // Expects an invocation of "foo(String a, bool b)" where "a" must be /// // the value 'hello' but "b" may be any value. This would match both /// // foo('hello', true), foo('hello', false), and foo('hello', null). /// expect(fooInvocation, invokes( /// #foo, /// positionalArguments: ['hello', any] /// )); /// /// Suitable for use in mocking libraries, where `noSuchMethod` can be used to /// get a handle to attempted [Invocation] objects and then compared against /// what a user expects to be called. Matcher invokes( Symbol memberName, { List<dynamic> positionalArguments = const [], Map<Symbol, dynamic> namedArguments = const {}, bool isGetter = false, bool isSetter = false, }) { if (isGetter && isSetter) { throw ArgumentError('Cannot set isGetter and iSetter'); } if (positionalArguments == null) { throw ArgumentError.notNull('positionalArguments'); } if (namedArguments == null) { throw ArgumentError.notNull('namedArguments'); } return _InvocationMatcher(_InvocationSignature( memberName: memberName, positionalArguments: positionalArguments, namedArguments: namedArguments, isGetter: isGetter, isSetter: isSetter, )); } /// Returns a matcher that matches the name and arguments of an [invocation]. /// /// To expect the same _signature_ see [invokes]. Matcher isInvocation(Invocation invocation) => _InvocationMatcher(invocation); class _InvocationSignature extends Invocation { @override final Symbol memberName; @override final List positionalArguments; @override final Map<Symbol, dynamic> namedArguments; @override final bool isGetter; @override final bool isSetter; _InvocationSignature({ @required this.memberName, this.positionalArguments = const [], this.namedArguments = const {}, this.isGetter = false, this.isSetter = false, }); @override bool get isMethod => !isAccessor; } class _InvocationMatcher implements Matcher { static Description _describeInvocation(Description d, Invocation invocation) { // For a getter or a setter, just return get <member> or set <member> <arg>. if (invocation.isAccessor) { d = d .add(invocation.isGetter ? 'get ' : 'set ') .add(_symbolToString(invocation.memberName)); if (invocation.isSetter) { d = d.add(' ').addDescriptionOf(invocation.positionalArguments.first); } return d; } // For a method, return <member>(<args>). d = d .add(_symbolToString(invocation.memberName)) .add('(') .addAll('', ', ', '', invocation.positionalArguments); if (invocation.positionalArguments.isNotEmpty && invocation.namedArguments.isNotEmpty) { d = d.add(', '); } // Also added named arguments, if any. return d.addAll('', ', ', '', _namedArgsAndValues(invocation)).add(')'); } // Returns named arguments as an iterable of '<name>: <value>'. static Iterable<String> _namedArgsAndValues(Invocation invocation) => invocation.namedArguments.keys.map((name) => '${_symbolToString(name)}: ${invocation.namedArguments[name]}'); // This will give is a mangled symbol in dart2js/aot with minification // enabled, but it's safe to assume very few people will use the invocation // matcher in a production test anyway due to noSuchMethod. static String _symbolToString(Symbol symbol) { return symbol.toString().split('"')[1]; } final Invocation _invocation; _InvocationMatcher(this._invocation) { if (_invocation == null) { throw ArgumentError.notNull(); } } @override Description describe(Description d) => _describeInvocation(d, _invocation); // TODO(matanl): Better implement describeMismatch and use state from matches. // Specifically, if a Matcher is passed as an argument, we'd like to get an // error like "Expected fly(miles: > 10), Actual: fly(miles: 5)". @override Description describeMismatch(item, Description d, _, __) { if (item is Invocation) { d = d.add('Does not match '); return _describeInvocation(d, item); } return d.add('Is not an Invocation'); } @override bool matches(item, _) => item is Invocation && _invocation.memberName == item.memberName && _invocation.isSetter == item.isSetter && _invocation.isGetter == item.isGetter && const ListEquality<dynamic /* Matcher | E */ >(_MatcherEquality()) .equals(_invocation.positionalArguments, item.positionalArguments) && const MapEquality<dynamic, dynamic /* Matcher | E */ >( values: _MatcherEquality()) .equals(_invocation.namedArguments, item.namedArguments); } // Uses both DeepCollectionEquality and custom matching for invocation matchers. class _MatcherEquality extends DeepCollectionEquality /* <Matcher | E> */ { const _MatcherEquality(); @override bool equals(e1, e2) { // All argument matches are wrapped in `ArgMatcher`, so we have to unwrap // them into the raw `Matcher` type in order to finish our equality checks. if (e1 is ArgMatcher) { e1 = e1.matcher; } if (e2 is ArgMatcher) { e2 = e2.matcher; } if (e1 is Matcher && e2 is! Matcher) { return e1.matches(e2, {}); } if (e2 is Matcher && e1 is! Matcher) { return e2.matches(e1, {}); } return super.equals(e1, e2); } // We force collisions on every value so equals() is called. @override int hash(_) => 0; }
mockito/lib/src/invocation_matcher.dart/0
{'file_path': 'mockito/lib/src/invocation_matcher.dart', 'repo_id': 'mockito', 'token_count': 2219}
// Copyright 2018 Dart Mockito authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'utils.dart'; class _RealClass { _RealClass innerObj; String methodWithoutArgs() => 'Real'; String methodWithNormalArgs(int x) => 'Real'; String methodWithListArgs(List<int> x) => 'Real'; String methodWithOptionalArg([int x]) => 'Real'; String methodWithPositionalArgs(int x, [int y]) => 'Real'; String methodWithNamedArgs(int x, {int y}) => 'Real'; String methodWithOnlyNamedArgs({int y, int z}) => 'Real'; String methodWithObjArgs(_RealClass x) => 'Real'; String get getter => 'Real'; set setter(String arg) { throw StateError('I must be mocked'); } String methodWithLongArgs(LongToString a, LongToString b, {LongToString c, LongToString d}) => 'Real'; } class LongToString { final List aList; final Map aMap; final String aString; LongToString(this.aList, this.aMap, this.aString); @override String toString() => 'LongToString<\n' ' aList: $aList\n' ' aMap: $aMap\n' ' aString: $aString\n' '>'; } class _MockedClass extends Mock implements _RealClass {} void expectFail(Pattern expectedMessage, void Function() expectedToFail) { try { expectedToFail(); fail('It was expected to fail!'); } on TestFailure catch (e) { expect(e.message, expectedMessage is String ? expectedMessage : contains(expectedMessage), reason: 'Failed but with unexpected message'); } } const noMatchingCallsFooter = '(If you called `verify(...).called(0);`, ' 'please instead use `verifyNever(...);`.)'; void main() { _MockedClass mock; var isNsmForwarding = assessNsmForwarding(); setUp(() { mock = _MockedClass(); }); tearDown(() { // In some of the tests that expect an Error to be thrown, Mockito's // global state can become invalid. Reset it. resetMockitoState(); }); group('verify', () { test('should verify method without args', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); }); test('should verify method with normal args', () { mock.methodWithNormalArgs(42); verify(mock.methodWithNormalArgs(42)); }); test('should mock method with positional args', () { mock.methodWithPositionalArgs(42, 17); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithPositionalArgs(42, 17)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithPositionalArgs(42)); }); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithPositionalArgs(42, 17)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithPositionalArgs(42, 18)); }); verify(mock.methodWithPositionalArgs(42, 17)); }); test('should mock method with named args', () { mock.methodWithNamedArgs(42, y: 17); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithNamedArgs(42, {y: 17})\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNamedArgs(42)); }); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithNamedArgs(42, {y: 17})\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNamedArgs(42, y: 18)); }); verify(mock.methodWithNamedArgs(42, y: 17)); }); test('should mock method with list args', () { mock.methodWithListArgs([42]); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithListArgs([42])\n' '$noMatchingCallsFooter', () { verify(mock.methodWithListArgs([43])); }); verify(mock.methodWithListArgs([42])); }); test('should mock method with argument matcher', () { mock.methodWithNormalArgs(100); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithNormalArgs(100)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNormalArgs(argThat(greaterThan(100)))); }); verify(mock.methodWithNormalArgs(argThat(greaterThanOrEqualTo(100)))); }); test('should mock method with mix of argument matchers and real things', () { mock.methodWithPositionalArgs(100, 17); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithPositionalArgs(100, 17)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithPositionalArgs( argThat(greaterThanOrEqualTo(100)), 18)); }); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithPositionalArgs(100, 17)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithPositionalArgs(argThat(greaterThan(100)), 17)); }); verify(mock.methodWithPositionalArgs( argThat(greaterThanOrEqualTo(100)), 17)); }); test('should mock getter', () { mock.getter; verify(mock.getter); }); test('should mock setter', () { mock.setter = 'A'; final expectedMessage = RegExp.escape('No matching calls. ' 'All calls: _MockedClass.setter==A\n$noMatchingCallsFooter'); // RegExp needed because of https://github.com/dart-lang/sdk/issues/33565 var expectedPattern = RegExp(expectedMessage.replaceFirst('==', '=?=')); expectFail(expectedPattern, () => verify(mock.setter = 'B')); verify(mock.setter = 'A'); }); test('should throw meaningful errors when verification is interrupted', () { var badHelper = () => throw 'boo'; try { verify(mock.methodWithNamedArgs(42, y: badHelper())); fail('verify call was expected to throw!'); } catch (_) {} // At this point, verification was interrupted, so // `_verificationInProgress` is still `true`. Calling mock methods below // adds items to `_verifyCalls`. mock.methodWithNamedArgs(42, y: 17); mock.methodWithNamedArgs(42, y: 17); try { verify(mock.methodWithNamedArgs(42, y: 17)); fail('verify call was expected to throw!'); } catch (e) { expect(e, TypeMatcher<StateError>()); expect( e.message, contains('Verification appears to be in progress. ' '2 verify calls have been stored.')); } }); }); group('verify should fail when no matching call is found', () { test('and there are no unmatched calls', () { expectFail( 'No matching calls (actually, no calls at all).\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNormalArgs(43)); }); }); test('and there is one unmatched call', () { mock.methodWithNormalArgs(42); expectFail( 'No matching calls. All calls: _MockedClass.methodWithNormalArgs(42)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNormalArgs(43)); }); }); test('and there is one unmatched call without args', () { mock.methodWithOptionalArg(); var nsmForwardedArgs = isNsmForwarding ? 'null' : ''; expectFail( 'No matching calls. All calls: _MockedClass.methodWithOptionalArg($nsmForwardedArgs)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithOptionalArg(43)); }); }); test('and there are multiple unmatched calls', () { mock.methodWithNormalArgs(41); mock.methodWithNormalArgs(42); expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithNormalArgs(41), ' '_MockedClass.methodWithNormalArgs(42)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNormalArgs(43)); }); }); test('and unmatched calls have only named args', () { mock.methodWithOnlyNamedArgs(y: 1); var nsmForwardedArgs = isNsmForwarding ? '{y: 1, z: null}' : '{y: 1}'; expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithOnlyNamedArgs($nsmForwardedArgs)\n' '$noMatchingCallsFooter', () { verify(mock.methodWithOnlyNamedArgs()); }); }); }); group('verify qualifies', () { group('unqualified as at least one', () { test('zero fails', () { expectFail( 'No matching calls (actually, no calls at all).\n' '$noMatchingCallsFooter', () { verify(mock.methodWithoutArgs()); }); }); test('one passes', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); }); test('more than one passes', () { mock.methodWithoutArgs(); mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); }); }); group('expecting one call', () { test('zero actual calls fails', () { expectFail( 'No matching calls (actually, no calls at all).\n' '$noMatchingCallsFooter', () { verify(mock.methodWithoutArgs()).called(1); }); }); test('one actual call passes', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()).called(1); }); test('more than one actual call fails', () { mock.methodWithoutArgs(); mock.methodWithoutArgs(); expectFail('Expected: <1>\n Actual: <2>\nUnexpected number of calls\n', () { verify(mock.methodWithoutArgs()).called(1); }); }); }); group('expecting more than two calls', () { test('zero actual calls fails', () { expectFail( 'No matching calls (actually, no calls at all).\n' '$noMatchingCallsFooter', () { verify(mock.methodWithoutArgs()).called(greaterThan(2)); }); }); test('one actual call fails', () { mock.methodWithoutArgs(); expectFail( 'Expected: a value greater than <2>\n' ' Actual: <1>\n' ' Which: is not a value greater than <2>\n' 'Unexpected number of calls\n', () { verify(mock.methodWithoutArgs()).called(greaterThan(2)); }); }); test('three actual calls passes', () { mock.methodWithoutArgs(); mock.methodWithoutArgs(); mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()).called(greaterThan(2)); }); }); group('expecting zero calls', () { test('zero actual calls passes', () { expectFail( 'No matching calls (actually, no calls at all).\n' '$noMatchingCallsFooter', () { verify(mock.methodWithoutArgs()).called(0); }); }); test('one actual call fails', () { mock.methodWithoutArgs(); expectFail( 'Expected: <0>\n' ' Actual: <1>\n' 'Unexpected number of calls\n', () { verify(mock.methodWithoutArgs()).called(0); }); }); }); group('verifyNever', () { test('zero passes', () { verifyNever(mock.methodWithoutArgs()); }); test('one fails', () { // Add one verified method that should not appear in message. mock.methodWithNormalArgs(1); verify(mock.methodWithNormalArgs(1)).called(1); mock.methodWithoutArgs(); expectFail('Unexpected calls: _MockedClass.methodWithoutArgs()', () { verifyNever(mock.methodWithoutArgs()); }); }); }); group('does not count already verified again', () { test('fail case', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); expectFail( 'No matching calls. ' 'All calls: [VERIFIED] _MockedClass.methodWithoutArgs()\n' '$noMatchingCallsFooter', () { verify(mock.methodWithoutArgs()); }); }); test('pass case', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); }); }); }); group('verifyZeroInteractions', () { test('never touched pass', () { verifyZeroInteractions(mock); }); test('any touch fails', () { mock.methodWithoutArgs(); expectFail( 'No interaction expected, but following found: ' '_MockedClass.methodWithoutArgs()', () { verifyZeroInteractions(mock); }); }); test('verified call fails', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); expectFail( 'No interaction expected, but following found: ' '[VERIFIED] _MockedClass.methodWithoutArgs()', () { verifyZeroInteractions(mock); }); }); }); group('verifyNoMoreInteractions', () { test('never touched pass', () { verifyNoMoreInteractions(mock); }); test('any unverified touch fails', () { mock.methodWithoutArgs(); expectFail( 'No more calls expected, but following found: ' '_MockedClass.methodWithoutArgs()', () { verifyNoMoreInteractions(mock); }); }); test('verified touch passes', () { mock.methodWithoutArgs(); verify(mock.methodWithoutArgs()); verifyNoMoreInteractions(mock); }); test('throws if given a real object', () { expect(() => verifyNoMoreInteractions(_RealClass()), throwsArgumentError); }); }); group('verifyInOrder', () { test('right order passes', () { mock.methodWithoutArgs(); mock.getter; verifyInOrder([mock.methodWithoutArgs(), mock.getter]); }); test('wrong order fails', () { mock.methodWithoutArgs(); mock.getter; expectFail( 'Matching call #1 not found. All calls: ' '_MockedClass.methodWithoutArgs(), _MockedClass.getter', () { verifyInOrder([mock.getter, mock.methodWithoutArgs()]); }); }); test('incomplete fails', () { mock.methodWithoutArgs(); expectFail( 'Matching call #1 not found. All calls: ' '_MockedClass.methodWithoutArgs()', () { verifyInOrder([mock.methodWithoutArgs(), mock.getter]); }); }); test('methods can be called again and again', () { mock.methodWithoutArgs(); mock.getter; mock.methodWithoutArgs(); verifyInOrder( [mock.methodWithoutArgs(), mock.getter, mock.methodWithoutArgs()]); }); test('methods can be called again and again - fail case', () { mock.methodWithoutArgs(); mock.methodWithoutArgs(); mock.getter; expectFail( 'Matching call #2 not found. All calls: ' '_MockedClass.methodWithoutArgs(), _MockedClass.methodWithoutArgs(), ' '_MockedClass.getter', () { verifyInOrder( [mock.methodWithoutArgs(), mock.getter, mock.methodWithoutArgs()]); }); }); }); group('multiline toStrings on objects', () { test( '"No matching calls" message visibly separates unmatched calls, ' 'if an arg\'s string representations is multiline', () { mock.methodWithLongArgs(LongToString([1, 2], {1: 'a', 2: 'b'}, 'c'), LongToString([4, 5], {3: 'd', 4: 'e'}, 'f')); mock.methodWithLongArgs(null, null, c: LongToString([5, 6], {5: 'g', 6: 'h'}, 'i'), d: LongToString([7, 8], {7: 'j', 8: 'k'}, 'l')); var nsmForwardedNamedArgs = isNsmForwarding ? '>, {c: null, d: null}),' : '>),'; expectFail( 'No matching calls. All calls: ' '_MockedClass.methodWithLongArgs(\n' ' LongToString<\n' ' aList: [1, 2]\n' ' aMap: {1: a, 2: b}\n' ' aString: c\n' ' >,\n' ' LongToString<\n' ' aList: [4, 5]\n' ' aMap: {3: d, 4: e}\n' ' aString: f\n' ' $nsmForwardedNamedArgs\n' '_MockedClass.methodWithLongArgs(null, null, {\n' ' c: LongToString<\n' ' aList: [5, 6]\n' ' aMap: {5: g, 6: h}\n' ' aString: i\n' ' >,\n' ' d: LongToString<\n' ' aList: [7, 8]\n' ' aMap: {7: j, 8: k}\n' ' aString: l\n' ' >})\n' '$noMatchingCallsFooter', () { verify(mock.methodWithNormalArgs(43)); }); }); }); }
mockito/test/verify_test.dart/0
{'file_path': 'mockito/test/verify_test.dart', 'repo_id': 'mockito', 'token_count': 7371}
import 'package:mocktail/mocktail.dart'; import 'package:mocktail/src/mocktail.dart'; import 'package:test/test.dart'; class _RealClass { _RealClass? innerObj; String? methodWithoutArgs() => 'Real'; String? methodWithNormalArgs(int? x) => 'Real'; String? methodWithListArgs(List<int?>? x) => 'Real'; String? methodWithPositionalArgs(int? x, [int? y]) => 'Real'; String? methodWithNamedArgs(int? x, {int? y}) => 'Real'; String? methodWithTwoNamedArgs(int? x, {int? y, int? z}) => 'Real'; String? methodWithObjArgs(_RealClass x) => 'Real'; String? methodWithDynamicArgs(dynamic x) => 'Real'; Future<String>? methodReturningFuture() => Future.value('Real'); Stream<String>? methodReturningStream() => Stream.fromIterable(['Real']); String? get getter => 'Real'; } class _Dynamic { const _Dynamic(this.value); final dynamic value; } // ignore: one_member_abstracts abstract class _Foo { String? bar(); } abstract class _AbstractFoo implements _Foo { @override String? bar() => baz(); String? baz(); String quux() => 'Real'; } class _MockFoo extends _AbstractFoo with Mock {} class _MockedClass extends Mock implements _RealClass {} void expectFail(String expectedMessage, void Function() expectedToFail) { try { expectedToFail(); fail('It was expected to fail!'); } catch (e) { if (e is! TestFailure) { rethrow; } else { if (expectedMessage != e.message) { // ignore: only_throw_errors throw TestFailure('Failed, but with wrong message: ${e.message}'); } } } } void main() { late _MockedClass mock; setUpAll(() { registerFallbackValue(_RealClass()); }); setUp(() { mock = _MockedClass(); }); tearDown(resetMocktailState); group('mixin support', () { test('should work', () { final foo = _MockFoo(); when(foo.baz).thenReturn('baz'); expect(foo.bar(), 'baz'); }); }); group('when()', () { test('should mock method without args', () { when(() => mock.methodWithoutArgs()).thenReturn('A'); expect(mock.methodWithoutArgs(), equals('A')); }); test('should mock method with normal args', () { when(() => mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect(mock.methodWithNormalArgs(43), isNull); expect(mock.methodWithNormalArgs(42), equals('Ultimate Answer')); }); test('should mock method with mock args', () { final m1 = _MockedClass(); when(() => mock.methodWithObjArgs(m1)).thenReturn('Ultimate Answer'); expect(mock.methodWithObjArgs(_MockedClass()), isNull); expect(mock.methodWithObjArgs(m1), equals('Ultimate Answer')); }); test('should throw ArgumentError if passing matcher as nested arg', () { expect( () => when( () => mock.methodWithDynamicArgs(_Dynamic(any<dynamic>())), ).thenReturn('Utimate Answer'), throwsArgumentError, ); }); test('should mock method with positional args', () { when(() => mock.methodWithPositionalArgs(42, 17)) .thenReturn('Answer and...'); expect(mock.methodWithPositionalArgs(42), isNull); expect(mock.methodWithPositionalArgs(42, 18), isNull); expect(mock.methodWithPositionalArgs(42, 17), equals('Answer and...')); }); test('should mock method with named args', () { when(() => mock.methodWithNamedArgs(42, y: 17)).thenReturn('Why answer?'); expect(mock.methodWithNamedArgs(42), isNull); expect(mock.methodWithNamedArgs(42, y: 18), isNull); expect(mock.methodWithNamedArgs(42, y: 17), equals('Why answer?')); }); test('should mock method with List args', () { when(() => mock.methodWithListArgs([42])).thenReturn('Ultimate answer'); expect(mock.methodWithListArgs([43]), isNull); expect(mock.methodWithListArgs([42]), equals('Ultimate answer')); }); test('should mock method with argument matcher', () { when( () => mock.methodWithNormalArgs(any(that: greaterThan(100))), ).thenReturn('A lot!'); expect(mock.methodWithNormalArgs(100), isNull); expect(mock.methodWithNormalArgs(101), equals('A lot!')); }); test('should mock method with any argument matcher', () { when(() => mock.methodWithNormalArgs(any())).thenReturn('A lot!'); expect(mock.methodWithNormalArgs(100), equals('A lot!')); expect(mock.methodWithNormalArgs(101), equals('A lot!')); }); test('should mock method with any list argument matcher', () { when(() => mock.methodWithListArgs(any())).thenReturn('A lot!'); expect(mock.methodWithListArgs([42]), equals('A lot!')); expect(mock.methodWithListArgs([43]), equals('A lot!')); }); test('should mock method with multiple named args and matchers', () { when( () => mock.methodWithTwoNamedArgs( any(), y: any(named: 'y'), ), ).thenReturn('x y'); when( () => mock.methodWithTwoNamedArgs( any(), z: any(named: 'z'), ), ).thenReturn('x z'); expect(mock.methodWithTwoNamedArgs(42), 'x z'); expect(mock.methodWithTwoNamedArgs(42, y: 18), equals('x y')); expect(mock.methodWithTwoNamedArgs(42, z: 17), equals('x z')); expect(mock.methodWithTwoNamedArgs(42, y: 18, z: 17), isNull); when( () => mock.methodWithTwoNamedArgs( any(), y: any(named: 'y'), z: any(named: 'z'), ), ).thenReturn('x y z'); expect(mock.methodWithTwoNamedArgs(42, y: 18, z: 17), equals('x y z')); }); test('should mock method with mix of argument matchers and real things', () { when( () => mock.methodWithPositionalArgs( any( that: greaterThan(100), ), 17, ), ).thenReturn('A lot with 17'); expect(mock.methodWithPositionalArgs(100, 17), isNull); expect(mock.methodWithPositionalArgs(101, 18), isNull); expect(mock.methodWithPositionalArgs(101, 17), equals('A lot with 17')); }); test('should mock getter', () { when(() => mock.getter).thenReturn('A'); expect(mock.getter, equals('A')); }); test('should have hashCode when it is not mocked', () { expect(mock.hashCode, isNotNull); }); test('should have default toString when it is not mocked', () { expect(mock.toString(), equals('_MockedClass')); }); test('should use identical equality between it is not mocked', () { final anotherMock = _MockedClass(); expect(mock == anotherMock, isFalse); expect(mock == mock, isTrue); }); test('should mock method with thrown result', () { when(() => mock.methodWithNormalArgs(any())).thenThrow(StateError('Boo')); expect(() => mock.methodWithNormalArgs(42), throwsStateError); }); test('should mock method with calculated result', () { when(() => mock.methodWithNormalArgs(any())).thenAnswer( (Invocation inv) => inv.positionalArguments[0].toString(), ); expect(mock.methodWithNormalArgs(43), equals('43')); expect(mock.methodWithNormalArgs(42), equals('42')); }); test('should return mock to make simple oneline mocks', () { final _RealClass mockWithSetup = _MockedClass(); when(mockWithSetup.methodWithoutArgs).thenReturn('oneline'); expect(mockWithSetup.methodWithoutArgs(), equals('oneline')); }); test('should use latest matching when definition', () { when(() => mock.methodWithoutArgs()).thenReturn('A'); when(() => mock.methodWithoutArgs()).thenReturn('B'); expect(mock.methodWithoutArgs(), equals('B')); }); test('should mock method with calculated result', () { when( () => mock.methodWithNormalArgs( any( that: equals(43), ), ), ).thenReturn('43'); when( () => mock.methodWithNormalArgs( any( that: equals(42), ), ), ).thenReturn('42'); expect(mock.methodWithNormalArgs(43), equals('43')); }); // Error path tests. test('should throw if `when` is called while stubbing', () { expect( () { _RealClass responseHelper() { final mock2 = _MockedClass(); when(() => mock2.getter).thenReturn('A'); return mock2; } when(() => mock.innerObj).thenReturn(responseHelper()); }, throwsStateError, ); }); test('thenReturn throws if provided Future', () { expect( () => when(() => mock.methodReturningFuture()).thenReturn( Future.value('stub'), ), throwsArgumentError, ); }); test('thenReturn throws if provided Stream', () { expect( () => when(() => mock.methodReturningStream()) .thenReturn(Stream.fromIterable(['stub'])), throwsArgumentError, ); }); test('thenAnswer supports stubbing method returning a Future', () async { when(() => mock.methodReturningFuture()) .thenAnswer((_) => Future.value('stub')); expect(await mock.methodReturningFuture(), 'stub'); }); test('thenAnswer supports stubbing method returning a Stream', () async { when(() => mock.methodReturningStream()) .thenAnswer((_) => Stream.fromIterable(['stub'])); expect(await mock.methodReturningStream()?.toList(), ['stub']); }); test('should throw if named matcher is passed as the wrong name', () { expect( () { when( () => mock.methodWithNamedArgs(42, y: any(named: 'z')), ).thenReturn('99'); }, throwsArgumentError, ); }); test('should throw if attempting to stub a real method', () { final foo = _MockFoo(); expect( () { when(foo.quux).thenReturn('Stub'); }, throwsStateError, ); }); }); group('throwOnMissingStub', () { test('should throw when a mock was called without a matching stub', () { throwOnMissingStub(mock); when(() => mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect( () => mock.methodWithoutArgs(), throwsA(const TypeMatcher<MissingStubError>()), ); }); test('should not throw when a mock was called with a matching stub', () { throwOnMissingStub(mock); when(() => mock.methodWithoutArgs()).thenReturn('A'); expect(() => mock.methodWithoutArgs(), returnsNormally); }); test( 'should throw the exception when a mock was called without a matching ' 'stub and an exception builder is set.', () { throwOnMissingStub( mock, exceptionBuilder: (_) { throw Exception('test message'); }, ); when(() => mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect(() => mock.methodWithoutArgs(), throwsException); }); }); group('Mocktail.throwOnMissingStub', () { test('should throw when a mock was called without a matching stub', () { Mock.throwOnMissingStub(); when(() => mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect( () => mock.methodWithoutArgs(), throwsA(const TypeMatcher<MissingStubError>()), ); }); test('should not throw when a mock was called with a matching stub', () { Mock.throwOnMissingStub(); when(() => mock.methodWithoutArgs()).thenReturn('A'); expect(() => mock.methodWithoutArgs(), returnsNormally); }); test( 'should throw the exception when a mock was called without a matching ' 'stub and an exception builder is set.', () { Mock.throwOnMissingStub( exceptionBuilder: (_) { throw Exception('test message'); }, ); when(() => mock.methodWithNormalArgs(42)).thenReturn('Ultimate Answer'); expect(() => mock.methodWithoutArgs(), throwsException); }); }); }
mocktail/packages/mocktail/test/mockito_compat/mockito_test.dart/0
{'file_path': 'mocktail/packages/mocktail/test/mockito_compat/mockito_test.dart', 'repo_id': 'mocktail', 'token_count': 4790}
include: package:lints/recommended.yaml analyzer: errors: missing_required_param: error missing_return: error unused_import: error unused_local_variable: error dead_code: error language: strict-casts: true strict-raw-types: true
money.dart/analysis_options.yaml/0
{'file_path': 'money.dart/analysis_options.yaml', 'repo_id': 'money.dart', 'token_count': 95}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:json_annotation/json_annotation.dart'; import 'package:path/path.dart' as p; import 'user_exception.dart'; import 'yaml.dart'; part 'mono_config.g.dart'; final _monoConfigFileName = 'mono_repo.yaml'; /// The top-level keys that cannot be set under `travis:` in `mono_repo.yaml` const _reservedTravisKeys = ['cache', 'jobs', 'language']; class MonoConfig { final Map<String, dynamic> travis; final Map<String, ConditionalStage> conditionalStages; MonoConfig._(this.travis, this.conditionalStages); factory MonoConfig(Map travis) { var overlappingKeys = travis.keys.where(_reservedTravisKeys.contains).toList(); if (overlappingKeys.isNotEmpty) { throw CheckedFromJsonException(travis, overlappingKeys.first.toString(), 'MonoConfig', 'Contains illegal keys: ${overlappingKeys.join(', ')}'); } var conditionalStages = <String, ConditionalStage>{}; var rawStageValue = travis['stages']; if (rawStageValue != null) { if (rawStageValue is List) { for (var item in rawStageValue) { if (item is Map) { var stage = _$ConditionalStageFromJson(item); if (conditionalStages.containsKey(stage.name)) { throw CheckedFromJsonException(travis, 'stages', 'MonoConfig', '`${stage.name}` appears more than once.'); } conditionalStages[stage.name] = stage; } else { throw CheckedFromJsonException(travis, 'stages', 'MonoConfig', 'All values must be Map instances.'); } } } else { throw CheckedFromJsonException( travis, 'stages', 'MonoConfig', '`stages` must be an array.'); } } // Removing this at the last minute so any throw CheckedFromJsonException // will have the right value // ... but the code that writes the values won't write stages seperately travis.remove('stages'); return MonoConfig._( travis.map((k, v) => MapEntry((k as String), v)), conditionalStages); } factory MonoConfig.fromJson(Map json) { var nonTravisKeys = json.keys.where((k) => k != 'travis').toList(); if (nonTravisKeys.isNotEmpty) { throw CheckedFromJsonException(json, nonTravisKeys.first as String, 'MonoConfig', 'Only `travis` key is supported.'); } var travis = json['travis']; if (travis is Map) { return MonoConfig(travis); } throw CheckedFromJsonException( json, 'travis', 'MonoConfig', '`travis` must be a Map.'); } factory MonoConfig.fromRepo({String rootDirectory}) { rootDirectory ??= p.current; var yaml = yamlMapOrNull(rootDirectory, _monoConfigFileName); if (yaml == null || yaml.isEmpty) { return MonoConfig({}); } try { return MonoConfig.fromJson(yaml); } on CheckedFromJsonException catch (e) { throw UserException('Error parsing $_monoConfigFileName', details: prettyPrintCheckedFromJsonException(e)); } } } @JsonSerializable(disallowUnrecognizedKeys: true) class ConditionalStage { @JsonKey(required: true, disallowNullValue: true) final String name; @JsonKey(name: 'if', required: true, disallowNullValue: true) final String ifCondition; ConditionalStage(this.name, this.ifCondition); Map<String, dynamic> toJson() => _$ConditionalStageToJson(this); }
mono_repo/mono_repo/lib/src/mono_config.dart/0
{'file_path': 'mono_repo/mono_repo/lib/src/mono_config.dart', 'repo_id': 'mono_repo', 'token_count': 1388}
/// Custom exception used with Http requests class HttpException implements Exception { /// Creates a new instance of [HttpException] HttpException({ this.title, this.message, this.statusCode, }); /// Exception title final String? title; /// Exception message final String? message; /// Exception http response code final int? statusCode; }
movies_app/lib/core/exceptions/http_exception.dart/0
{'file_path': 'movies_app/lib/core/exceptions/http_exception.dart', 'repo_id': 'movies_app', 'token_count': 105}
import 'package:flutter/material.dart'; import 'package:movies_app/core/widgets/shimmer.dart'; /// Widget used for a list shimmer effect class ListItemShimmer extends StatelessWidget { /// Creates a new instance of [ListItemShimmer] const ListItemShimmer({super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 10), child: Row( children: [ const Expanded( flex: 1, child: Shimmer(height: 90), ), const SizedBox(width: 20), Expanded( flex: 3, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Shimmer(height: 15), const SizedBox(height: 20), Shimmer( height: 15, width: MediaQuery.of(context).size.width * 0.4, ), ], ), ), ], ), ); } }
movies_app/lib/core/widgets/list_item_shimmer.dart/0
{'file_path': 'movies_app/lib/core/widgets/list_item_shimmer.dart', 'repo_id': 'movies_app', 'token_count': 532}
import 'package:flutter/material.dart'; import 'package:movies_app/core/widgets/app_cached_network_image.dart'; import 'package:movies_app/features/people/models/person_image.dart'; import 'package:movies_app/features/people/views/widgets/save_image_slider_action.dart'; import 'package:movies_app/features/people/views/widgets/slider_action.dart'; /// Slider widget for person images class PersonImagesSliderPage extends StatefulWidget { /// Creates a new instance of [PersonImagesSliderPage] const PersonImagesSliderPage({ super.key, this.initialImageIndex = 0, required this.images, }); /// The initial image index to the slider should first open to final int initialImageIndex; /// The list of person images displayed in the slider final List<PersonImage> images; @override State<PersonImagesSliderPage> createState() => PersonImagesSliderPageState(); } /// Person images slider widget state class PersonImagesSliderPageState extends State<PersonImagesSliderPage> { /// Page controller attached to the slider [PageView] widget late final PageController pageController; /// Indicates if saving image to device gallery is loading bool isLoadingImageSave = false; @override void initState() { pageController = PageController(initialPage: widget.initialImageIndex); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SafeArea( child: Stack( children: [ PageView.builder( controller: pageController, itemCount: widget.images.length, itemBuilder: (BuildContext context, int index) { return Stack( children: [ Positioned.fill( child: SizedBox( width: MediaQuery.of(context).size.width, child: widget.images[index].imageUrl == null ? Container() : AppCachedNetworkImage( key: ValueKey( '__person_image_slider_${index}__', ), imageUrl: widget.images[index].imageUrl!, fit: BoxFit.fitWidth, isLoaderShimmer: false, alignment: Alignment.topCenter, ), ), ), if (widget.images[index].imageUrl != null) PositionedDirectional( top: 20, end: 17, child: SaveImageSliderAction( imageUrl: widget.images[index].imageUrl!, ), ), ], ); }, ), PositionedDirectional( bottom: 0, start: 20, child: SliderAction( key: const ValueKey('__slider_previous_button__'), icon: const Icon(Icons.arrow_back), onTap: () { pageController.previousPage( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, ); }, ), ), PositionedDirectional( bottom: 0, end: 20, child: SliderAction( key: const ValueKey('__slider_next_button__'), icon: const Icon(Icons.arrow_forward), onTap: () { pageController.nextPage( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, ); }, ), ), ], ), ), ); } }
movies_app/lib/features/people/views/pages/person_images_slider_page.dart/0
{'file_path': 'movies_app/lib/features/people/views/pages/person_images_slider_page.dart', 'repo_id': 'movies_app', 'token_count': 2076}
import 'package:flutter/material.dart'; import 'package:movies_app/core/configs/styles/app_colors.dart'; /// Slider action widget like next, prev, download class SliderAction extends StatelessWidget { /// Creates a new instance of [SliderAction] const SliderAction({ super.key, required this.icon, this.onTap, this.color = AppColors.primary, }); /// Icons widget inside the slider action final Widget icon; /// onTap action final VoidCallback? onTap; /// widget background color final Color color; @override Widget build(BuildContext context) { return Center( child: ClipOval( child: Material( color: color, child: InkWell( onTap: onTap, child: Padding( padding: const EdgeInsets.all(8), child: icon, ), ), ), ), ); } }
movies_app/lib/features/people/views/widgets/slider_action.dart/0
{'file_path': 'movies_app/lib/features/people/views/widgets/slider_action.dart', 'repo_id': 'movies_app', 'token_count': 373}
import 'package:flutter_test/flutter_test.dart'; import 'package:movies_app/features/people/enums/gender.dart'; void main() { test('Female gender is equivalent to 1', () { expect(Gender.female.toInt, equals(1)); expect(Gender.fromInt(1), Gender.female); }); test('Male gender is equivalent to 2', () { expect(Gender.male.toInt, equals(2)); expect(Gender.fromInt(2), Gender.male); }); }
movies_app/test/features/people/enums/gender_test.dart/0
{'file_path': 'movies_app/test/features/people/enums/gender_test.dart', 'repo_id': 'movies_app', 'token_count': 148}
import 'package:flutter_test/flutter_test.dart'; import 'package:movies_app/core/widgets/app_cached_network_image.dart'; import 'package:movies_app/features/people/models/person_image.dart'; import 'package:movies_app/features/people/views/widgets/person_images_grid_item.dart'; import '../../../../test-utils/dummy-data/dummy_people.dart'; import '../../../../test-utils/pump_app.dart'; void main() { testWidgets( 'renders asset image for null thumbnail', (WidgetTester tester) async { await tester.pumpApp( PersonImagesGridItem( PersonImage.fromJson(DummyPeople.rawDummyPersonImage1), ), ); await tester.pumpAndSettle(); expect( find.byType(AppCachedNetworkImage), findsNothing, ); }, ); testWidgets( 'renders network image for a thumbnail url', (WidgetTester tester) async { await tester.pumpApp( PersonImagesGridItem(DummyPeople.dummyPersonImage1), ); await tester.pump(); expect( find.byType(AppCachedNetworkImage), findsOneWidget, ); }, ); }
movies_app/test/features/people/views/widgets/person_images_grid_item_test.dart/0
{'file_path': 'movies_app/test/features/people/views/widgets/person_images_grid_item_test.dart', 'repo_id': 'movies_app', 'token_count': 468}
language: node_js node_js: - "0.11" before_install: - export DISPLAY=:99.0 script: - ./tool/travis.sh
mustache/.travis.yml/0
{'file_path': 'mustache/.travis.yml', 'repo_id': 'mustache', 'token_count': 48}
import 'mustache_specs.dart' as specs; import 'mustache_test.dart' as test; import 'parser_test.dart' as parser; void main() { specs.main(); test.main(); parser.main(); }
mustache/test/all.dart/0
{'file_path': 'mustache/test/all.dart', 'repo_id': 'mustache', 'token_count': 68}
enum AppTheme { light, dark }
new_flutter_template/evaluations/journal_clean_architecture/lib/domain/entities/app_theme.dart/0
{'file_path': 'new_flutter_template/evaluations/journal_clean_architecture/lib/domain/entities/app_theme.dart', 'repo_id': 'new_flutter_template', 'token_count': 9}
import 'package:flutter/material.dart'; import 'package:list_detail_mvc_cubit/src/app.dart'; import 'package:list_detail_mvc_cubit/src/users/user_list_controller.dart'; import 'package:list_detail_mvc_cubit/src/users/user_repository.dart'; void main() async { // Setup Repositories which are responsible for storing and retrieving data final repository = UserRepository(); // Setup Controllers which bind Data Storage (Repositories) to Flutter // Widgets. final controller = UserController(repository); runApp(UserListApp(controller: controller)); }
new_flutter_template/evaluations/list_detail_mvc_cubit/lib/main.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_cubit/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 174}
import 'package:flutter/material.dart'; import 'package:list_detail_mvc_mobx/src/user.dart'; class UserDetailsPage extends StatelessWidget { final User user; const UserDetailsPage({Key key, this.user}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('User Details'), ), body: Center( child: Text('User #${user.id}'), ), ); } }
new_flutter_template/evaluations/list_detail_mvc_mobx/lib/src/user_details.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_mobx/lib/src/user_details.dart', 'repo_id': 'new_flutter_template', 'token_count': 179}
import 'package:list_detail_mvc_state_notifier/src/users/user.dart'; import 'package:list_detail_mvc_state_notifier/src/users/user_list_model.dart'; import 'package:list_detail_mvc_state_notifier/src/users/user_repository.dart'; import 'package:state_notifier/state_notifier.dart'; class UserListController extends StateNotifier<UserListModel> { UserListController(this.repository) : super(UserListModel.initial()); final UserRepository repository; Future<void> loadUsers() async { state = UserListModel.loading(); try { state = UserListModel.populated(await repository.users()); } catch (error) { state = UserListModel.error(); } } Future<void> addUser(User user) async { state = UserListModel.populated([...state.users, user]); await repository.addUser(user); } Future<void> removeUser(User user) async { state = UserListModel.populated(state.users..remove(user)); await repository.addUser(user); } }
new_flutter_template/evaluations/list_detail_mvc_state_notifier/lib/src/users/user_list_controller.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_state_notifier/lib/src/users/user_list_controller.dart', 'repo_id': 'new_flutter_template', 'token_count': 332}
import 'dart:math'; import 'dart:ui'; import 'package:flutter/rendering.dart'; final random = Random(); class User { final int id; final Color color; User(this.id) : color = HSLColor.fromAHSL( 1, random.nextInt(360).toDouble(), (random.nextInt(99 - 42).toDouble() + 42) / 100, (random.nextInt(90 - 40).toDouble() + 40) / 100) .toColor(); }
new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user.dart', 'repo_id': 'new_flutter_template', 'token_count': 213}
import 'package:flutter/cupertino.dart'; import 'package:list_detail_mvc_vn_two_features/src/settings/settings.dart'; import 'package:list_detail_mvc_vn_two_features/src/settings/settings_repository.dart'; class SettingsController extends ValueNotifier<Settings> { final SettingsRepository repository; SettingsController(this.repository) : super(Settings()); Future<void> loadSettings() async { value = await repository.settings(); } Future<void> updateTheme(AppTheme theme) async { value = Settings(theme); await repository.updateSettings(value); } }
new_flutter_template/evaluations/list_detail_mvc_vn_two_features/lib/src/settings/settings_controller.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_two_features/lib/src/settings/settings_controller.dart', 'repo_id': 'new_flutter_template', 'token_count': 179}
class PantoneColor { final int id; final String name; final int year; final String color; final String pantoneValue; PantoneColor({ this.id, this.name, this.year, this.color, this.pantoneValue, }); PantoneColor.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], year = json['year'], color = json['color'], pantoneValue = json['pantone_value']; Map<String, dynamic> toJson() { return { 'id': id, 'name': name, 'year': year, 'color': color, 'pantone_value': pantoneValue, }; } }
new_flutter_template/evaluations/login_mvc/lib/src/pantone_colors/pantone_color.dart/0
{'file_path': 'new_flutter_template/evaluations/login_mvc/lib/src/pantone_colors/pantone_color.dart', 'repo_id': 'new_flutter_template', 'token_count': 278}
include: package:pedantic/analysis_options.yaml
new_flutter_template/evaluations/tiny_journal_mvc/analysis_options.yaml/0
{'file_path': 'new_flutter_template/evaluations/tiny_journal_mvc/analysis_options.yaml', 'repo_id': 'new_flutter_template', 'token_count': 14}
import 'package:flutter/cupertino.dart'; import 'package:uuid/uuid.dart'; class JournalEntry { final String id; final String title; final DateTime date; final String body; JournalEntry({ @required this.title, @required this.body, String id, DateTime date, }) : id = id ?? Uuid().v4(), date = date ?? DateTime.now(); JournalEntry.fromJson(Map<String, dynamic> json) : id = json['id'], title = json['title'], date = DateTime.parse(json['date']), body = json['body']; Map<String, dynamic> toJson() { return { 'id': id, 'title': title, 'date': date.toIso8601String(), 'body': body, }; } }
new_flutter_template/evaluations/tiny_journal_mvc/lib/src/journal/journal_entry.dart/0
{'file_path': 'new_flutter_template/evaluations/tiny_journal_mvc/lib/src/journal/journal_entry.dart', 'repo_id': 'new_flutter_template', 'token_count': 293}
name: api concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - "flutter_news_example/api/**" - ".github/workflows/api.yaml" branches: - main jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 with: dart_sdk: 3.0.2 working_directory: flutter_news_example/api analyze_directories: "routes lib test" coverage_excludes: "**/*.g.dart" report_on: "routes,lib"
news_toolkit/.github/workflows/api.yaml/0
{'file_path': 'news_toolkit/.github/workflows/api.yaml', 'repo_id': 'news_toolkit', 'token_count': 237}
name: news_repository concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - "flutter_news_example/packages/news_repository/**" - ".github/workflows/news_repository.yaml" branches: - main jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_version: 3.10.2 working_directory: flutter_news_example/packages/news_repository
news_toolkit/.github/workflows/news_repository.yaml/0
{'file_path': 'news_toolkit/.github/workflows/news_repository.yaml', 'repo_id': 'news_toolkit', 'token_count': 202}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'subscription.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Subscription _$SubscriptionFromJson(Map<String, dynamic> json) => Subscription( id: json['id'] as String, name: $enumDecode(_$SubscriptionPlanEnumMap, json['name']), cost: SubscriptionCost.fromJson(json['cost'] as Map<String, dynamic>), benefits: (json['benefits'] as List<dynamic>).map((e) => e as String).toList(), ); Map<String, dynamic> _$SubscriptionToJson(Subscription instance) => <String, dynamic>{ 'id': instance.id, 'name': _$SubscriptionPlanEnumMap[instance.name]!, 'cost': instance.cost.toJson(), 'benefits': instance.benefits, }; const _$SubscriptionPlanEnumMap = { SubscriptionPlan.none: 'none', SubscriptionPlan.basic: 'basic', SubscriptionPlan.plus: 'plus', SubscriptionPlan.premium: 'premium', }; SubscriptionCost _$SubscriptionCostFromJson(Map<String, dynamic> json) => SubscriptionCost( monthly: json['monthly'] as int, annual: json['annual'] as int, ); Map<String, dynamic> _$SubscriptionCostToJson(SubscriptionCost instance) => <String, dynamic>{ 'monthly': instance.monthly, 'annual': instance.annual, };
news_toolkit/flutter_news_example/api/lib/src/data/models/subscription.g.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/data/models/subscription.g.dart', 'repo_id': 'news_toolkit', 'token_count': 489}
export 'article_response/article_response.dart'; export 'categories_response/categories_response.dart'; export 'current_user_response/current_user_response.dart'; export 'feed_response/feed_response.dart'; export 'popular_search_response/popular_search_response.dart'; export 'related_articles_response/related_articles_response.dart'; export 'relevant_search_response/relevant_search_response.dart'; export 'subscriptions_response/subscriptions_response.dart';
news_toolkit/flutter_news_example/api/lib/src/models/models.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/models/models.dart', 'repo_id': 'news_toolkit', 'token_count': 134}
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'banner_ad_block.g.dart'; /// The size of a [BannerAdBlock]. enum BannerAdSize { /// The normal size of a banner ad. normal, /// The large size of a banner ad. large, /// The extra large size of a banner ad. extraLarge, /// The anchored adaptive size of a banner ad. anchoredAdaptive } /// {@template banner_ad_block} /// A block which represents a banner ad. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=35%3A5151 /// {@endtemplate} @JsonSerializable() class BannerAdBlock with EquatableMixin implements NewsBlock { /// {@macro banner_ad_block} const BannerAdBlock({ required this.size, this.type = BannerAdBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [BannerAdBlock] instance. factory BannerAdBlock.fromJson(Map<String, dynamic> json) => _$BannerAdBlockFromJson(json); /// The banner ad block type identifier. static const identifier = '__banner_ad__'; /// The size of this banner ad. final BannerAdSize size; @override final String type; @override Map<String, dynamic> toJson() => _$BannerAdBlockToJson(this); @override List<Object> get props => [size, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/banner_ad_block.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/banner_ad_block.dart', 'repo_id': 'news_toolkit', 'token_count': 463}
import 'package:equatable/equatable.dart'; import 'package:news_blocks/news_blocks.dart'; /// {@template post_block} /// An abstract block which represents a post block. /// {@endtemplate} abstract class PostBlock with EquatableMixin implements NewsBlock { /// {@macro post_block} const PostBlock({ required this.id, required this.category, required this.author, required this.publishedAt, required this.title, required this.type, this.imageUrl, this.description, this.action, this.isPremium = false, this.isContentOverlaid = false, }); /// The medium post block type identifier. static const identifier = '__post_medium__'; /// The identifier of this post. final String id; /// The category of this post. final PostCategory category; /// The author of this post. final String author; /// The date when this post was published. final DateTime publishedAt; /// The image URL of this post. final String? imageUrl; /// The title of this post. final String title; /// The optional description of this post. final String? description; /// An optional action which occurs upon interaction. @BlockActionConverter() final BlockAction? action; /// Whether this post requires a premium subscription to access. /// /// Defaults to false. final bool isPremium; /// Whether the content of this post is overlaid on the image. /// /// Defaults to false. final bool isContentOverlaid; @override final String type; @override List<Object?> get props => [ id, category, author, publishedAt, imageUrl, title, description, action, isPremium, isContentOverlaid, type, ]; } /// The extension on [PostBlock] that provides information about actions. extension PostBlockActions on PostBlock { /// Whether the action of this post is navigation. bool get hasNavigationAction => action?.actionType == BlockActionType.navigation; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_block.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_block.dart', 'repo_id': 'news_toolkit', 'token_count': 654}
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'slideshow_block.g.dart'; /// {@template slideshow_block} /// A block which represents a slideshow. /// {@endtemplate} @JsonSerializable() class SlideshowBlock with EquatableMixin implements NewsBlock { /// {@macro slideshow_block} const SlideshowBlock({ required this.title, required this.slides, this.type = SlideshowBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [SlideshowBlock] instance. factory SlideshowBlock.fromJson(Map<String, dynamic> json) => _$SlideshowBlockFromJson(json); /// The title of this slideshow. final String title; /// List of slides to be displayed. final List<SlideBlock> slides; /// The slideshow block type identifier. static const identifier = '__slideshow__'; @override Map<String, dynamic> toJson() => _$SlideshowBlockToJson(this); @override List<Object> get props => [type, title, slides]; @override final String type; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_block.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_block.dart', 'repo_id': 'news_toolkit', 'token_count': 344}
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'unknown_block.g.dart'; /// {@template unknown_block} /// A block which represents an unknown type. /// {@endtemplate} @JsonSerializable() class UnknownBlock with EquatableMixin implements NewsBlock { /// {@macro unknown_block} const UnknownBlock({this.type = UnknownBlock.identifier}); /// Converts a `Map<String, dynamic>` into a [UnknownBlock] instance. factory UnknownBlock.fromJson(Map<String, dynamic> json) => _$UnknownBlockFromJson(json); /// The unknown block type identifier. static const identifier = '__unknown__'; @override final String type; @override Map<String, dynamic> toJson() => _$UnknownBlockToJson(this); @override List<Object> get props => [type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/unknown_block.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/unknown_block.dart', 'repo_id': 'news_toolkit', 'token_count': 270}
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('NewsBlocksConverter', () { test('can (de)serialize List<NewsBlock>', () { final converter = NewsBlocksConverter(); final newsBlocks = <NewsBlock>[ SectionHeaderBlock(title: 'title'), DividerHorizontalBlock(), SpacerBlock(spacing: Spacing.medium), PostSmallBlock( id: 'id', category: PostCategory.health, author: 'author', publishedAt: DateTime(2022, 3, 11), imageUrl: 'imageUrl', title: 'title', description: 'description', ), ]; expect( converter.fromJson(converter.toJson(newsBlocks)), equals(newsBlocks), ); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/news_blocks_converter_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/news_blocks_converter_test.dart', 'repo_id': 'news_toolkit', 'token_count': 369}
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('TextParagraphBlock', () { test('can be (de)serialized', () { final block = TextParagraphBlock(text: 'Paragraph text'); expect(TextParagraphBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/text_paragraph_block_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/text_paragraph_block_test.dart', 'repo_id': 'news_toolkit', 'token_count': 135}
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 reqUser = context.read<RequestUser>(); if (reqUser.isAnonymous) return Response(statusCode: HttpStatus.badRequest); final user = await context.read<NewsDataSource>().getUser(userId: reqUser.id); if (user == null) return Response(statusCode: HttpStatus.notFound); final response = CurrentUserResponse(user: user); return Response.json(body: response); }
news_toolkit/flutter_news_example/api/routes/api/v1/users/me.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/routes/api/v1/users/me.dart', 'repo_id': 'news_toolkit', 'token_count': 210}
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example_api/api.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('RelatedArticles', () { test('can be (de)serialized', () { final blockA = SectionHeaderBlock(title: 'sectionA'); final blockB = SectionHeaderBlock(title: 'sectionB'); final relatedArticles = RelatedArticles( blocks: [blockA, blockB], totalBlocks: 2, ); expect( RelatedArticles.fromJson(relatedArticles.toJson()), equals(relatedArticles), ); }); }); }
news_toolkit/flutter_news_example/api/test/src/data/models/related_articles_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/test/src/data/models/related_articles_test.dart', 'repo_id': 'news_toolkit', 'token_count': 250}
export 'bloc/app_bloc.dart'; export 'routes/routes.dart'; export 'view/app.dart'; export 'widgets/widgets.dart';
news_toolkit/flutter_news_example/lib/app/app.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/app/app.dart', 'repo_id': 'news_toolkit', 'token_count': 50}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/ads/ads.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/network_error/network_error.dart'; import 'package:flutter_news_example_api/client.dart'; import 'package:visibility_detector/visibility_detector.dart'; class ArticleContent extends StatelessWidget { const ArticleContent({super.key}); @override Widget build(BuildContext context) { final status = context.select((ArticleBloc bloc) => bloc.state.status); final hasMoreContent = context.select((ArticleBloc bloc) => bloc.state.hasMoreContent); if (status == ArticleStatus.initial) { return const ArticleContentLoaderItem( key: Key('articleContent_empty_loaderItem'), ); } return ArticleContentSeenListener( child: BlocListener<ArticleBloc, ArticleState>( listener: (context, state) { if (state.status == ArticleStatus.failure && state.content.isEmpty) { Navigator.of(context).push<void>( NetworkError.route( onRetry: () { context.read<ArticleBloc>().add(const ArticleRequested()); Navigator.of(context).pop(); }, ), ); } else if (state.status == ArticleStatus.shareFailure) { _handleShareFailure(context); } }, child: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ SelectionArea( child: CustomScrollView( slivers: [ const ArticleContentItemList(), if (!hasMoreContent) const ArticleTrailingContent(), ], ), ), const StickyAd(), ], ), ), ); } void _handleShareFailure(BuildContext context) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar( key: const Key('articleContent_shareFailure_snackBar'), content: Text( context.l10n.shareFailure, ), ), ); } } class ArticleContentSeenListener extends StatelessWidget { const ArticleContentSeenListener({ required this.child, super.key, }); final Widget child; @override Widget build(BuildContext context) { return BlocListener<ArticleBloc, ArticleState>( listener: (context, state) => context.read<AnalyticsBloc>().add( TrackAnalyticsEvent( ArticleMilestoneEvent( milestonePercentage: state.contentMilestone, articleTitle: state.title!, ), ), ), listenWhen: (previous, current) => previous.contentMilestone != current.contentMilestone, child: child, ); } } class ArticleContentItemList extends StatelessWidget { const ArticleContentItemList({super.key}); @override Widget build(BuildContext context) { final isFailure = context.select( (ArticleBloc bloc) => bloc.state.status == ArticleStatus.failure, ); final hasMoreContent = context.select((ArticleBloc bloc) => bloc.state.hasMoreContent); final status = context.select((ArticleBloc bloc) => bloc.state.status); final content = context.select((ArticleBloc bloc) => bloc.state.content); final uri = context.select((ArticleBloc bloc) => bloc.state.uri); final isArticlePreview = context.select((ArticleBloc bloc) => bloc.state.isPreview); return SliverList( delegate: SliverChildBuilderDelegate( (context, index) { if (index == content.length) { if (isFailure) { return NetworkError( onRetry: () { context.read<ArticleBloc>().add(const ArticleRequested()); }, ); } return hasMoreContent ? Padding( padding: EdgeInsets.only( top: content.isEmpty ? AppSpacing.xxxlg : 0, ), child: ArticleContentLoaderItem( key: const Key( 'articleContent_moreContent_loaderItem', ), onPresented: () { if (status != ArticleStatus.loading) { context .read<ArticleBloc>() .add(const ArticleRequested()); } }, ), ) : const SizedBox(); } return _buildArticleItem( context, index, content, uri, isArticlePreview, ); }, childCount: content.length + 1, ), ); } Widget _buildArticleItem( BuildContext context, int index, List<NewsBlock> content, Uri? uri, bool isArticlePreview, ) { final block = content[index]; final isFinalItem = index == content.length - 1; final visibilityDetectorWidget = VisibilityDetector( key: ValueKey(block), onVisibilityChanged: (visibility) { if (!visibility.visibleBounds.isEmpty) { context .read<ArticleBloc>() .add(ArticleContentSeen(contentIndex: index)); } }, child: ArticleContentItem( block: block, onSharePressed: uri != null && uri.toString().isNotEmpty ? () => context.read<ArticleBloc>().add( ShareRequested(uri: uri), ) : null, ), ); return isFinalItem && isArticlePreview ? Stack( alignment: Alignment.bottomCenter, children: [visibilityDetectorWidget, const ArticleTrailingShadow()], ) : visibilityDetectorWidget; } }
news_toolkit/flutter_news_example/lib/article/widgets/article_content.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/article/widgets/article_content.dart', 'repo_id': 'news_toolkit', 'token_count': 2905}
part of 'feed_bloc.dart'; enum FeedStatus { initial, loading, populated, failure, } @JsonSerializable() class FeedState extends Equatable { const FeedState({ required this.status, this.feed = const {}, this.hasMoreNews = const {}, }); const FeedState.initial() : this( status: FeedStatus.initial, ); factory FeedState.fromJson(Map<String, dynamic> json) => _$FeedStateFromJson(json); final FeedStatus status; final Map<Category, List<NewsBlock>> feed; final Map<Category, bool> hasMoreNews; @override List<Object> get props => [ status, feed, hasMoreNews, ]; FeedState copyWith({ FeedStatus? status, Map<Category, List<NewsBlock>>? feed, Map<Category, bool>? hasMoreNews, }) { return FeedState( status: status ?? this.status, feed: feed ?? this.feed, hasMoreNews: hasMoreNews ?? this.hasMoreNews, ); } Map<String, dynamic> toJson() => _$FeedStateToJson(this); }
news_toolkit/flutter_news_example/lib/feed/bloc/feed_state.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/feed/bloc/feed_state.dart', 'repo_id': 'news_toolkit', 'token_count': 400}
import 'dart:async'; import 'package:analytics_repository/analytics_repository.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:form_inputs/form_inputs.dart'; import 'package:user_repository/user_repository.dart'; part 'login_event.dart'; part 'login_state.dart'; class LoginBloc extends Bloc<LoginEvent, LoginState> { LoginBloc({ required UserRepository userRepository, }) : _userRepository = userRepository, super(const LoginState()) { on<LoginEmailChanged>(_onEmailChanged); on<SendEmailLinkSubmitted>(_onSendEmailLinkSubmitted); on<LoginGoogleSubmitted>(_onGoogleSubmitted); on<LoginAppleSubmitted>(_onAppleSubmitted); on<LoginTwitterSubmitted>(_onTwitterSubmitted); on<LoginFacebookSubmitted>(_onFacebookSubmitted); } final UserRepository _userRepository; void _onEmailChanged(LoginEmailChanged event, Emitter<LoginState> emit) { final email = Email.dirty(event.email); emit( state.copyWith( email: email, valid: Formz.validate([email]), ), ); } Future<void> _onSendEmailLinkSubmitted( SendEmailLinkSubmitted event, Emitter<LoginState> emit, ) async { if (!state.valid) return; emit(state.copyWith(status: FormzSubmissionStatus.inProgress)); try { await _userRepository.sendLoginEmailLink( email: state.email.value, ); emit(state.copyWith(status: FormzSubmissionStatus.success)); } catch (error, stackTrace) { emit(state.copyWith(status: FormzSubmissionStatus.failure)); addError(error, stackTrace); } } Future<void> _onGoogleSubmitted( LoginGoogleSubmitted event, Emitter<LoginState> emit, ) async { emit(state.copyWith(status: FormzSubmissionStatus.inProgress)); try { await _userRepository.logInWithGoogle(); emit(state.copyWith(status: FormzSubmissionStatus.success)); } on LogInWithGoogleCanceled { emit(state.copyWith(status: FormzSubmissionStatus.canceled)); } catch (error, stackTrace) { emit(state.copyWith(status: FormzSubmissionStatus.failure)); addError(error, stackTrace); } } Future<void> _onAppleSubmitted( LoginAppleSubmitted event, Emitter<LoginState> emit, ) async { emit(state.copyWith(status: FormzSubmissionStatus.inProgress)); try { await _userRepository.logInWithApple(); emit(state.copyWith(status: FormzSubmissionStatus.success)); } catch (error, stackTrace) { emit(state.copyWith(status: FormzSubmissionStatus.failure)); addError(error, stackTrace); } } Future<void> _onTwitterSubmitted( LoginTwitterSubmitted event, Emitter<LoginState> emit, ) async { emit(state.copyWith(status: FormzSubmissionStatus.inProgress)); try { await _userRepository.logInWithTwitter(); emit(state.copyWith(status: FormzSubmissionStatus.success)); } on LogInWithTwitterCanceled { emit(state.copyWith(status: FormzSubmissionStatus.canceled)); } catch (error, stackTrace) { emit(state.copyWith(status: FormzSubmissionStatus.failure)); addError(error, stackTrace); } } Future<void> _onFacebookSubmitted( LoginFacebookSubmitted event, Emitter<LoginState> emit, ) async { emit(state.copyWith(status: FormzSubmissionStatus.inProgress)); try { await _userRepository.logInWithFacebook(); emit(state.copyWith(status: FormzSubmissionStatus.success)); } on LogInWithFacebookCanceled { emit(state.copyWith(status: FormzSubmissionStatus.canceled)); } catch (error, stackTrace) { emit(state.copyWith(status: FormzSubmissionStatus.failure)); addError(error, stackTrace); } } }
news_toolkit/flutter_news_example/lib/login/bloc/login_bloc.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/login/bloc/login_bloc.dart', 'repo_id': 'news_toolkit', 'token_count': 1396}
export 'magic_link_prompt_page.dart'; export 'magic_link_prompt_view.dart';
news_toolkit/flutter_news_example/lib/magic_link_prompt/view/view.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/magic_link_prompt/view/view.dart', 'repo_id': 'news_toolkit', 'token_count': 30}
part of 'newsletter_bloc.dart'; abstract class NewsletterEvent extends Equatable { const NewsletterEvent(); } class NewsletterSubscribed extends NewsletterEvent { const NewsletterSubscribed(); @override List<Object> get props => []; } class EmailChanged extends NewsletterEvent { const EmailChanged({required this.email}); final String email; @override List<Object?> get props => [email]; }
news_toolkit/flutter_news_example/lib/newsletter/bloc/newsletter_event.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/newsletter/bloc/newsletter_event.dart', 'repo_id': 'news_toolkit', 'token_count': 112}
import 'package:ads_consent_client/ads_consent_client.dart'; import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/onboarding/onboarding.dart'; import 'package:notifications_repository/notifications_repository.dart'; class OnboardingPage extends StatelessWidget { const OnboardingPage({super.key}); static Page<void> page() => const MaterialPage<void>(child: OnboardingPage()); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.darkBackground, body: BlocProvider( create: (_) => OnboardingBloc( notificationsRepository: context.read<NotificationsRepository>(), adsConsentClient: context.read<AdsConsentClient>(), ), child: const OnboardingView(), ), ); } }
news_toolkit/flutter_news_example/lib/onboarding/view/onboarding_page.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/onboarding/view/onboarding_page.dart', 'repo_id': 'news_toolkit', 'token_count': 320}
import 'package:article_repository/article_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_news_example/slideshow/slideshow.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:share_launcher/share_launcher.dart'; class SlideshowPage extends StatelessWidget { const SlideshowPage({ required this.slideshow, required this.articleId, super.key, }); static Route<void> route({ required SlideshowBlock slideshow, required String articleId, }) { return MaterialPageRoute<void>( builder: (_) => SlideshowPage( slideshow: slideshow, articleId: articleId, ), ); } final SlideshowBlock slideshow; final String articleId; @override Widget build(BuildContext context) { return BlocProvider( create: (context) => ArticleBloc( articleId: articleId, shareLauncher: const ShareLauncher(), articleRepository: context.read<ArticleRepository>(), ), child: SlideshowView( block: slideshow, ), ); } }
news_toolkit/flutter_news_example/lib/slideshow/view/slideshow_page.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/slideshow/view/slideshow_page.dart', 'repo_id': 'news_toolkit', 'token_count': 431}
export 'view/view.dart'; export 'widgets/widgets.dart';
news_toolkit/flutter_news_example/lib/terms_of_service/terms_of_service.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/terms_of_service/terms_of_service.dart', 'repo_id': 'news_toolkit', 'token_count': 22}
export 'user_profile_page.dart';
news_toolkit/flutter_news_example/lib/user_profile/view/view.dart/0
{'file_path': 'news_toolkit/flutter_news_example/lib/user_profile/view/view.dart', 'repo_id': 'news_toolkit', 'token_count': 12}
import 'package:analytics_repository/analytics_repository.dart'; /// {@template ntg_event} /// An analytics event following News Tagging Guidelines event taxonomy. /// https://newsinitiative.withgoogle.com/training/states/ntg/assets/ntg-playbook.pdf#page=245 /// {@endtemplate} abstract class NTGEvent extends AnalyticsEvent { /// {@macro ntg_event} NTGEvent({ required String name, required String category, required String action, required bool nonInteraction, String? label, Object? value, String? hitType, }) : super( name, properties: <String, Object>{ 'eventCategory': category, 'eventAction': action, 'nonInteraction': '$nonInteraction', if (label != null) 'eventLabel': label, if (value != null) 'eventValue': value, if (hitType != null) 'hitType': hitType, }, ); } /// {@template newsletter_event} /// An analytics event for tracking newsletter sign up and impression. /// {@endtemplate} class NewsletterEvent extends NTGEvent { /// An analytics event for tracking newsletter sign up. NewsletterEvent.signUp() : super( name: 'newsletter_signup', category: 'NTG newsletter', action: 'newsletter signup', label: 'success', nonInteraction: false, ); /// An analytics event for tracking newsletter impression. NewsletterEvent.impression({String? articleTitle}) : super( name: 'newsletter_impression', category: 'NTG newsletter', action: 'newsletter modal impression 3', label: articleTitle ?? '', nonInteraction: false, ); } /// {@template login_event} /// An analytics event for tracking user login. /// {@endtemplate} class LoginEvent extends NTGEvent { /// {@macro login_event} LoginEvent() : super( name: 'login', category: 'NTG account', action: 'login', label: 'success', nonInteraction: false, ); } /// {@template registration_event} /// An analytics event for tracking user registration. /// {@endtemplate} class RegistrationEvent extends NTGEvent { /// {@macro registration_event} RegistrationEvent() : super( name: 'registration', category: 'NTG account', action: 'registration', label: 'success', nonInteraction: false, ); } /// {@template article_milestone_event} /// An analytics event for tracking article completion milestones. /// {@endtemplate} class ArticleMilestoneEvent extends NTGEvent { /// {@macro article_milestone_event} ArticleMilestoneEvent({ required int milestonePercentage, required String articleTitle, }) : super( name: 'article_milestone', category: 'NTG article milestone', action: '$milestonePercentage%', label: articleTitle, value: milestonePercentage, nonInteraction: true, hitType: 'event', ); } /// {@template article_comment_event} /// An analytics event for tracking article comments. /// {@endtemplate} class ArticleCommentEvent extends NTGEvent { /// {@macro article_comment_event} ArticleCommentEvent({required String articleTitle}) : super( name: 'comment', category: 'NTG user', action: 'comment added', label: articleTitle, nonInteraction: false, ); } /// {@template social_share_event} /// An analytics event for tracking social sharing. /// {@endtemplate} class SocialShareEvent extends NTGEvent { /// {@macro social_share_event} SocialShareEvent() : super( name: 'social_share', category: 'NTG social', action: 'social share', label: 'OS share menu', nonInteraction: false, ); } /// {@template push_notification_subscription_event} /// An analytics event for tracking push notification subscription. /// {@endtemplate} class PushNotificationSubscriptionEvent extends NTGEvent { /// {@macro push_notification_subscription_event} PushNotificationSubscriptionEvent() : super( name: 'push_notification_click', category: 'NTG push notification', action: 'click', nonInteraction: false, ); } /// {@template paywall_prompt_event} /// An analytics event for tracking paywall prompt impression and click. /// {@endtemplate} class PaywallPromptEvent extends NTGEvent { /// An analytics event for tracking paywall prompt impression. PaywallPromptEvent.impression({ required PaywallPromptImpression impression, required String articleTitle, }) : super( name: 'paywall_impression', category: 'NTG paywall', action: 'paywall modal impression $impression', label: articleTitle, nonInteraction: true, ); /// An analytics event for tracking paywall prompt click. PaywallPromptEvent.click({required String articleTitle}) : super( name: 'paywall_click', category: 'NTG paywall', action: 'click', label: articleTitle, nonInteraction: false, ); } /// {@template paywall_prompt_impression} /// The available paywall prompt impressions. /// {@endtemplate} enum PaywallPromptImpression { /// The rewarded paywall prompt impression. rewarded(1), /// The subscription paywall prompt impression. subscription(2); /// {@macro paywall_prompt_impression} const PaywallPromptImpression(this._impressionType); final int _impressionType; @override String toString() => _impressionType.toString(); } /// {@template user_subscription_conversion_event} /// An analytics event for tracking user subscription conversion. /// {@endtemplate} class UserSubscriptionConversionEvent extends NTGEvent { /// {@macro user_subscription_conversion_event} UserSubscriptionConversionEvent() : super( name: 'subscription_submit', category: 'NTG subscription', action: 'submit', label: 'success', nonInteraction: false, ); }
news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/models/ntg_event.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/analytics_repository/lib/src/models/ntg_event.dart', 'repo_id': 'news_toolkit', 'token_count': 2304}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class ShowAppModalPage extends StatelessWidget { const ShowAppModalPage({super.key}); static Route<void> route() { return MaterialPageRoute<void>(builder: (_) => const ShowAppModalPage()); } @override Widget build(BuildContext context) { const contentSpace = 10.0; final buttons = [ Padding( padding: const EdgeInsets.only(bottom: AppSpacing.lg), child: ElevatedButton( onPressed: () => _showModal(context: context), style: ElevatedButton.styleFrom( backgroundColor: AppColors.oceanBlue, padding: const EdgeInsets.symmetric( horizontal: AppSpacing.xxlg + contentSpace, vertical: AppSpacing.xlg, ), textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), child: const Text('Show app modal'), ), ), ]; return Scaffold( appBar: AppBar( title: const Text('Modal App'), ), body: ColoredBox( color: AppColors.white, child: Align( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: buttons, ), ), ), ); } void _showModal({ required BuildContext context, }) { showAppModal<void>( context: context, builder: (context) => Column( mainAxisSize: MainAxisSize.min, children: [ Container( height: 300, color: AppColors.darkAqua, alignment: Alignment.center, ), Container( height: 200, color: AppColors.blue, alignment: Alignment.center, ), ], ), ); } }
news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/show_app_modal_page.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/show_app_modal_page.dart', 'repo_id': 'news_toolkit', 'token_count': 878}
export 'app_back_button.dart'; export 'app_button.dart'; export 'app_email_text_field.dart'; export 'app_logo.dart'; export 'app_switch.dart'; export 'app_text_field.dart'; export 'content_theme_override_builder.dart'; export 'show_app_modal.dart';
news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/widgets.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/widgets.dart', 'repo_id': 'news_toolkit', 'token_count': 97}
// This package is just an abstraction. // See firebase_authentication_client for a concrete implementation // ignore_for_file: prefer_const_constructors import 'package:authentication_client/authentication_client.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; // AuthenticationClient is exported and can be implemented class FakeAuthenticationClient extends Fake implements AuthenticationClient {} void main() { test('AuthenticationClient can be implemented', () { expect(FakeAuthenticationClient.new, returnsNormally); }); test('exports SendLoginEmailLinkFailure', () { expect( () => SendLoginEmailLinkFailure('oops'), returnsNormally, ); }); test('exports IsLogInWithEmailLinkFailure', () { expect( () => IsLogInWithEmailLinkFailure('oops'), returnsNormally, ); }); test('exports LogInWithEmailLinkFailure', () { expect( () => LogInWithEmailLinkFailure('oops'), returnsNormally, ); }); test('exports LogInWithAppleFailure', () { expect( () => LogInWithAppleFailure('oops'), returnsNormally, ); }); test('exports LogInWithGoogleFailure', () { expect( () => LogInWithGoogleFailure('oops'), returnsNormally, ); }); test('exports LogInWithGoogleCanceled', () { expect( () => LogInWithGoogleCanceled('oops'), returnsNormally, ); }); test('exports LogInWithFacebookFailure', () { expect( () => LogInWithFacebookFailure('oops'), returnsNormally, ); }); test('exports LogInWithFacebookCanceled', () { expect( () => LogInWithFacebookCanceled('oops'), returnsNormally, ); }); test('exports LogInWithTwitterFailure', () { expect( () => LogInWithTwitterFailure('oops'), returnsNormally, ); }); test('exports LogInWithTwitterCanceled', () { expect( () => LogInWithTwitterCanceled('oops'), returnsNormally, ); }); test('exports LogOutFailure', () { expect( () => LogOutFailure('oops'), returnsNormally, ); }); }
news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/test/src/authentication_client_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/test/src/authentication_client_test.dart', 'repo_id': 'news_toolkit', 'token_count': 741}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/deep_link_client/analysis_options.yaml/0
{'file_path': 'news_toolkit/flutter_news_example/packages/deep_link_client/analysis_options.yaml', 'repo_id': 'news_toolkit', 'token_count': 23}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks_ui/src/newsletter/index.dart'; /// {@template newsletter_success} /// A reusable newsletter success news block widget. /// {@endtemplate} class NewsletterSucceeded extends StatelessWidget { /// {@macro newsletter_success} const NewsletterSucceeded({ required this.headerText, required this.content, required this.footerText, super.key, }); /// The header displayed message. final String headerText; /// The widget displayed in a center of [NewsletterSucceeded] view. final Widget content; /// The footer displayed message. final String footerText; @override Widget build(BuildContext context) { final theme = Theme.of(context); return NewsletterContainer( child: Column( children: [ Text( headerText, textAlign: TextAlign.center, style: theme.textTheme.headlineMedium?.copyWith( color: AppColors.highEmphasisPrimary, ), ), const SizedBox(height: AppSpacing.lg + AppSpacing.lg), content, const SizedBox(height: AppSpacing.lg + AppSpacing.lg), Text( footerText, textAlign: TextAlign.center, style: theme.textTheme.bodyLarge?.copyWith( color: AppColors.mediumHighEmphasisPrimary, ), ), ], ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/newsletter_succeeded.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/newsletter/newsletter_succeeded.dart', 'repo_id': 'news_toolkit', 'token_count': 617}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; /// {@template text_headline} /// A reusable text headline news block widget. /// {@endtemplate} class TextHeadline extends StatelessWidget { /// {@macro text_headline} const TextHeadline({required this.block, super.key}); /// The associated [TextHeadlineBlock] instance. final TextHeadlineBlock block; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: Text( block.text, style: Theme.of(context).textTheme.displayMedium, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/text_headline.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/text_headline.dart', 'repo_id': 'news_toolkit', 'token_count': 245}
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template post_footer} /// A reusable footer of a post news block widget. /// {@endtemplate} class PostFooter extends StatelessWidget { /// {@macro post_footer} const PostFooter({ super.key, this.publishedAt, this.author, this.onShare, this.isContentOverlaid = false, }); /// The author of this post. final String? author; /// The date when this post was published. final DateTime? publishedAt; /// Called when the share button is tapped. final VoidCallback? onShare; /// Whether footer is displayed in reversed color theme. /// /// Defaults to false. final bool isContentOverlaid; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final textColor = isContentOverlaid ? AppColors.mediumHighEmphasisPrimary : AppColors.mediumEmphasisSurface; return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ RichText( text: TextSpan( style: textTheme.bodySmall?.copyWith(color: textColor), children: <InlineSpan>[ if (author != null) TextSpan( text: author, ), if (author != null && publishedAt != null) ...[ const WidgetSpan(child: SizedBox(width: AppSpacing.sm)), const TextSpan( text: '•', ), const WidgetSpan(child: SizedBox(width: AppSpacing.sm)), ], if (publishedAt != null) TextSpan( text: publishedAt!.mDY, ), ], ), ), if (onShare != null) IconButton( icon: Icon( Icons.share, color: textColor, ), onPressed: onShare, ), ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_footer.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/post_footer.dart', 'repo_id': 'news_toolkit', 'token_count': 940}
// ignore_for_file: prefer_const_constructors import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/sliver_grid_custom_delegate.dart'; void main() { group('HeaderGridTileLayout', () { testWidgets( 'getMinChildIndexForScrollOffset when ' 'super.getMinChildIndexForScrollOffset is 0', (tester) async { final headerTileLayout = HeaderGridTileLayout( crossAxisCount: 1, mainAxisStride: 14, crossAxisStride: 15, childMainAxisExtent: 2, childCrossAxisExtent: 3, reverseCrossAxis: false, ); final result = headerTileLayout.getMinChildIndexForScrollOffset(0); expect(result, 0); }); testWidgets( 'getMinChildIndexForScrollOffset when ' 'super.getMinChildIndexForScrollOffset is greater than 0', (tester) async { final headerTileLayout = HeaderGridTileLayout( crossAxisCount: 1, mainAxisStride: 14, crossAxisStride: 15, childMainAxisExtent: 2, childCrossAxisExtent: 3, reverseCrossAxis: false, ); final result = headerTileLayout.getMinChildIndexForScrollOffset(100); expect(result, 6); }); testWidgets( 'getGeometryForChildIndex when index is equal to 0 (first element) ', (tester) async { final headerTileLayout = HeaderGridTileLayout( crossAxisCount: 1, mainAxisStride: 14, crossAxisStride: 15, childMainAxisExtent: 2, childCrossAxisExtent: 3, reverseCrossAxis: false, ); final geometry = headerTileLayout.getGeometryForChildIndex(0); final expectedGeometry = SliverGridGeometry( scrollOffset: 0, crossAxisOffset: 0, mainAxisExtent: 16, crossAxisExtent: 18, ); expect(geometry.crossAxisExtent, expectedGeometry.crossAxisExtent); expect(geometry.scrollOffset, expectedGeometry.scrollOffset); expect(geometry.mainAxisExtent, expectedGeometry.mainAxisExtent); expect(geometry.crossAxisExtent, expectedGeometry.crossAxisExtent); }); testWidgets('getGeometryForChildIndex when index is not equal to 0', (tester) async { final headerTileLayout = HeaderGridTileLayout( crossAxisCount: 1, mainAxisStride: 14, crossAxisStride: 15, childMainAxisExtent: 2, childCrossAxisExtent: 3, reverseCrossAxis: false, ); final geometry = headerTileLayout.getGeometryForChildIndex(2); final expectedGeometry = SliverGridGeometry( scrollOffset: 44, crossAxisOffset: 0, mainAxisExtent: 14, crossAxisExtent: 3, ); expect(geometry.crossAxisExtent, expectedGeometry.crossAxisExtent); expect(geometry.scrollOffset, expectedGeometry.scrollOffset); expect(geometry.mainAxisExtent, expectedGeometry.mainAxisExtent); expect(geometry.crossAxisExtent, expectedGeometry.crossAxisExtent); }); testWidgets('computeMaxScrollOffset', (tester) async { final headerTileLayout = HeaderGridTileLayout( crossAxisCount: 1, mainAxisStride: 14, crossAxisStride: 15, childMainAxisExtent: 2, childCrossAxisExtent: 3, reverseCrossAxis: false, ); final maxScrollOffset = headerTileLayout.computeMaxScrollOffset(2); expect(maxScrollOffset, 58); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/header_grid_tile_layout_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/header_grid_tile_layout_test.dart', 'repo_id': 'news_toolkit', 'token_count': 1463}
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import '../helpers/helpers.dart'; void main() { const category = PostCategory.technology; const videoUrl = 'https://cdn.vox-cdn.com/thumbor/OTpmptgr7XcTVAJ27UBvIxl0vrg=' '/0x146:2040x1214/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset' '/file/22049166/shollister_201117_4303_0003.0.jpg'; const title = 'Nvidia and AMD GPUs are returning to shelves ' 'and prices are finally falling'; group('VideoIntroduction', () { setUpAll( () { final fakeVideoPlayerPlatform = FakeVideoPlayerPlatform(); VideoPlayerPlatform.instance = fakeVideoPlayerPlatform; setUpTolerantComparator(); }, ); testWidgets('renders correctly', (tester) async { final technologyVideoIntroduction = VideoIntroductionBlock( category: category, videoUrl: videoUrl, title: title, ); await mockNetworkImages( () async => tester.pumpContentThemedApp( SingleChildScrollView( child: Column( children: [ VideoIntroduction(block: technologyVideoIntroduction), ], ), ), ), ); expect(find.byType(InlineVideo), findsOneWidget); expect(find.byType(PostContent), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/video_introduction_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/video_introduction_test.dart', 'repo_id': 'news_toolkit', 'token_count': 716}
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:notifications_client/notifications_client.dart'; /// {@template firebase_notifications_client} /// A Firebase Cloud Messaging notifications client. /// {@endtemplate} class FirebaseNotificationsClient implements NotificationsClient { /// {@macro firebase_notifications_client} const FirebaseNotificationsClient({ required FirebaseMessaging firebaseMessaging, }) : _firebaseMessaging = firebaseMessaging; final FirebaseMessaging _firebaseMessaging; /// Subscribes to the notification group based on [category]. @override Future<void> subscribeToCategory(String category) async { try { await _firebaseMessaging.subscribeToTopic(category); } catch (error, stackTrace) { Error.throwWithStackTrace( SubscribeToCategoryFailure(error), stackTrace, ); } } /// Unsubscribes from the notification group based on [category]. @override Future<void> unsubscribeFromCategory(String category) async { try { await _firebaseMessaging.unsubscribeFromTopic(category); } catch (error, stackTrace) { Error.throwWithStackTrace( UnsubscribeFromCategoryFailure(error), stackTrace, ); } } }
news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/lib/src/firebase_notifications_client.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/notifications_client/firebase_notifications_client/lib/src/firebase_notifications_client.dart', 'repo_id': 'news_toolkit', 'token_count': 417}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:notifications_client/notifications_client.dart'; import 'package:one_signal_notifications_client/one_signal_notifications_client.dart'; import 'package:onesignal_flutter/onesignal_flutter.dart'; class MockOneSignal extends Mock implements OneSignal {} void main() { group('OneSignalNotificationsClient', () { late OneSignal oneSignal; late OneSignalNotificationsClient oneSignalNotificationsClient; const category = 'category'; setUp(() { oneSignal = MockOneSignal(); oneSignalNotificationsClient = OneSignalNotificationsClient( oneSignal: oneSignal, ); }); group('when OneSignalNotificationsClient.subscribeToCategory called', () { test('calls OneSignal.sendTag', () async { when( () => oneSignal.sendTag(category, true), ).thenAnswer((_) async => {}); await oneSignalNotificationsClient.subscribeToCategory(category); verify(() => oneSignal.sendTag(category, true)).called(1); }); test( 'throws SubscribeToCategoryFailure ' 'when OneSignal.deleteTag fails', () async { when( () => oneSignal.sendTag(category, true), ).thenAnswer((_) async => throw Exception()); expect( () => oneSignalNotificationsClient.subscribeToCategory(category), throwsA(isA<SubscribeToCategoryFailure>()), ); }); }); group('when OneSignalNotificationsClient.unsubscribeFromCategory called', () { test('calls OneSignal.deleteTag', () async { when(() => oneSignal.deleteTag(category)).thenAnswer((_) async => {}); await oneSignalNotificationsClient.unsubscribeFromCategory(category); verify(() => oneSignal.deleteTag(category)).called(1); }); test( 'throws UnsubscribeFromCategoryFailure ' 'when OneSignal.deleteTag fails', () async { when( () => oneSignal.deleteTag(category), ).thenAnswer((_) async => throw Exception()); expect( () => oneSignalNotificationsClient.unsubscribeFromCategory(category), throwsA(isA<UnsubscribeFromCategoryFailure>()), ); }); }); }); }
news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/test/src/one_signal_notifications_client_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/test/src/one_signal_notifications_client_test.dart', 'repo_id': 'news_toolkit', 'token_count': 918}
// ignore_for_file: prefer_const_constructors import 'package:package_info_client/package_info_client.dart'; import 'package:test/test.dart'; void main() { group('PackageInfoClient', () { test('returns correct package info', () async { const appName = 'App'; const packageName = 'com.example.app'; const packageVersion = '1.0.0'; final packageInfoClient = PackageInfoClient( appName: appName, packageName: packageName, packageVersion: packageVersion, ); expect(packageInfoClient.appName, appName); expect(packageInfoClient.packageName, packageName); expect(packageInfoClient.packageVersion, packageVersion); }); }); }
news_toolkit/flutter_news_example/packages/package_info_client/test/src/package_info_client_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/package_info_client/test/src/package_info_client_test.dart', 'repo_id': 'news_toolkit', 'token_count': 253}
export 'src/secure_storage.dart';
news_toolkit/flutter_news_example/packages/storage/secure_storage/lib/secure_storage.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/storage/secure_storage/lib/secure_storage.dart', 'repo_id': 'news_toolkit', 'token_count': 12}
export 'package:authentication_client/authentication_client.dart' show AuthenticationException, IsLogInWithEmailLinkFailure, LogInWithAppleFailure, LogInWithEmailLinkFailure, LogInWithFacebookCanceled, LogInWithFacebookFailure, LogInWithGoogleCanceled, LogInWithGoogleFailure, LogInWithTwitterCanceled, LogInWithTwitterFailure, LogOutFailure, SendLoginEmailLinkFailure; export 'src/models/models.dart'; export 'src/user_repository.dart';
news_toolkit/flutter_news_example/packages/user_repository/lib/user_repository.dart/0
{'file_path': 'news_toolkit/flutter_news_example/packages/user_repository/lib/user_repository.dart', 'repo_id': 'news_toolkit', 'token_count': 222}
// ignore_for_file: must_be_immutable, prefer_const_constructors import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:user_repository/user_repository.dart'; class MockUser extends Mock implements User {} void main() { group('AppState', () { late User user; setUp(() { user = MockUser(); when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.none); }); group('unauthenticated', () { test('has correct status', () { final state = AppState.unauthenticated(); expect(state.status, AppStatus.unauthenticated); expect(state.user, User.anonymous); }); }); group('authenticated', () { test('has correct status', () { final state = AppState.authenticated(user); expect(state.status, AppStatus.authenticated); expect(state.user, user); }); }); group('onboardingRequired', () { test('has correct status', () { final state = AppState.onboardingRequired(user); expect(state.status, AppStatus.onboardingRequired); expect(state.user, user); }); }); group('isUserSubscribed', () { test('returns true when userSubscriptionPlan is not null and not none', () { when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.premium); expect( AppState.authenticated(user).isUserSubscribed, isTrue, ); }); test('returns false when userSubscriptionPlan is none', () { expect( AppState.authenticated(user).isUserSubscribed, isFalse, ); }); }); group('AppStatus', () { test( 'authenticated and onboardingRequired are the only statuses ' 'where loggedIn is true', () { expect( AppStatus.values.where((e) => e.isLoggedIn).toList(), equals( [ AppStatus.onboardingRequired, AppStatus.authenticated, ], ), ); }); }); group('copyWith', () { test( 'returns same object ' 'when no properties are passed', () { expect( AppState.unauthenticated().copyWith(), equals(AppState.unauthenticated()), ); }); test( 'returns object with updated status ' 'when status is passed', () { expect( AppState.unauthenticated().copyWith( status: AppStatus.onboardingRequired, ), equals( AppState( status: AppStatus.onboardingRequired, ), ), ); }); test( 'returns object with updated user ' 'when user is passed', () { expect( AppState.unauthenticated().copyWith( user: user, ), equals( AppState( status: AppStatus.unauthenticated, user: user, ), ), ); }); }); }); }
news_toolkit/flutter_news_example/test/app/bloc/app_state_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/app/bloc/app_state_test.dart', 'repo_id': 'news_toolkit', 'token_count': 1463}
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; void main() { group('CategoriesEvent', () { group('CategoriesRequested', () { test('supports value comparisons', () { final event1 = CategoriesRequested(); final event2 = CategoriesRequested(); expect(event1, equals(event2)); }); }); group('CategorySelected', () { test('supports value comparisons', () { final event1 = CategorySelected(category: Category.top); final event2 = CategorySelected(category: Category.top); expect(event1, equals(event2)); }); }); }); }
news_toolkit/flutter_news_example/test/categories/bloc/categories_event_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/categories/bloc/categories_event_test.dart', 'repo_id': 'news_toolkit', 'token_count': 282}
// ignore_for_file: prefer_const_constructors // ignore_for_file: prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:flutter_news_example/feed/feed.dart'; import 'package:flutter_news_example/home/home.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_repository/news_repository.dart'; import '../../helpers/helpers.dart'; class MockNewsRepository extends Mock implements NewsRepository {} void main() { initMockHydratedStorage(); late NewsRepository newsRepository; setUp(() { newsRepository = MockNewsRepository(); when(newsRepository.getCategories).thenAnswer( (_) async => CategoriesResponse( categories: [Category.top], ), ); }); test('has a page', () { expect(HomePage.page(), isA<MaterialPage<void>>()); }); testWidgets('renders a HomeView', (tester) async { await tester.pumpApp(const HomePage()); expect(find.byType(HomeView), findsOneWidget); }); testWidgets('renders FeedView', (tester) async { await tester.pumpApp( const HomePage(), newsRepository: newsRepository, ); expect(find.byType(FeedView), findsOneWidget); }); }
news_toolkit/flutter_news_example/test/home/view/home_page_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/home/view/home_page_test.dart', 'repo_id': 'news_toolkit', 'token_count': 447}
import 'package:flutter_news_example/main/build_number.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('buildNumber', () { test('is not null', () { expect(buildNumber(), isNotNull); }); test('returns 0 when packageVersion is empty', () { expect(buildNumber(''), 0); }); test('returns 0 when packageVersion is missing a build number', () { expect(buildNumber('1.0.0'), 0); }); test('returns 0 when packageVersion has a malformed build number', () { expect(buildNumber('1.0.0+'), 0); }); test('returns 42 when build number is 42', () { expect(buildNumber('1.0.0+42'), 42); }); }); }
news_toolkit/flutter_news_example/test/main/build_number/build_number_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/main/build_number/build_number_test.dart', 'repo_id': 'news_toolkit', 'token_count': 261}
// ignore_for_file: prefer_const_constructors import 'package:flutter_news_example/onboarding/onboarding.dart'; import 'package:test/test.dart'; void main() { group('OnboardingEvent', () { group('EnableAdTrackingRequested', () { test('supports value comparisons', () { final event1 = EnableAdTrackingRequested(); final event2 = EnableAdTrackingRequested(); expect(event1, equals(event2)); }); }); group('EnableNotificationsRequested', () { test('supports value comparisons', () { final event1 = EnableNotificationsRequested(); final event2 = EnableNotificationsRequested(); expect(event1, equals(event2)); }); }); }); }
news_toolkit/flutter_news_example/test/onboarding/bloc/onboarding_event_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/onboarding/bloc/onboarding_event_test.dart', 'repo_id': 'news_toolkit', 'token_count': 262}
import 'dart:async'; import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/subscriptions/subscriptions.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart' hide PurchaseCompleted; import 'package:mockingjay/mockingjay.dart'; import 'package:user_repository/user_repository.dart'; import '../../../helpers/helpers.dart'; void main() { late InAppPurchaseRepository inAppPurchaseRepository; late UserRepository userRepository; const subscription = Subscription( id: 'dd339fda-33e9-49d0-9eb5-0ccb77eb760f', name: SubscriptionPlan.premium, cost: SubscriptionCost( annual: 16200, monthly: 1499, ), benefits: [ 'first', 'second', 'third', ], ); setUp(() { inAppPurchaseRepository = MockInAppPurchaseRepository(); userRepository = MockUserRepository(); when(() => inAppPurchaseRepository.purchaseUpdate).thenAnswer( (_) => const Stream.empty(), ); when(inAppPurchaseRepository.fetchSubscriptions).thenAnswer( (_) async => [], ); when( userRepository.updateSubscriptionPlan, ).thenAnswer((_) async {}); }); group('showPurchaseSubscriptionDialog', () { testWidgets('renders PurchaseSubscriptionDialog', (tester) async { await tester.pumpApp( Builder( builder: (context) { return ElevatedButton( key: const Key('tester_elevatedButton'), child: const Text('test'), onPressed: () => showPurchaseSubscriptionDialog(context: context), ); }, ), inAppPurchaseRepository: inAppPurchaseRepository, ); await tester.tap(find.byKey(const Key('tester_elevatedButton'))); await tester.pump(); expect(find.byType(PurchaseSubscriptionDialog), findsOneWidget); }); }); group('PurchaseSubscriptionDialog', () { testWidgets( 'renders PurchaseSubscriptionDialogView', (WidgetTester tester) async { await tester.pumpApp( const PurchaseSubscriptionDialog(), inAppPurchaseRepository: inAppPurchaseRepository, ); expect(find.byType(PurchaseSubscriptionDialogView), findsOneWidget); }, ); }); group('PurchaseSubscriptionDialogView', () { testWidgets('renders list of SubscriptionCard', (tester) async { const otherSubscription = Subscription( id: 'other_subscription_id', name: SubscriptionPlan.premium, cost: SubscriptionCost( annual: 16200, monthly: 1499, ), benefits: [ 'first', 'second', 'third', ], ); final subscriptions = [ subscription, otherSubscription, ]; when(inAppPurchaseRepository.fetchSubscriptions).thenAnswer( (_) async => subscriptions, ); await tester.pumpApp( const PurchaseSubscriptionDialog(), inAppPurchaseRepository: inAppPurchaseRepository, ); for (final subscription in subscriptions) { expect( find.byWidgetPredicate( (widget) => widget is SubscriptionCard && widget.key == ValueKey(subscription), ), findsOneWidget, ); } }); testWidgets('closes dialog on close button tap', (tester) async { final navigator = MockNavigator(); when(navigator.pop).thenAnswer((_) async => true); await tester.pumpApp( const PurchaseSubscriptionDialog(), inAppPurchaseRepository: inAppPurchaseRepository, navigator: navigator, ); await tester.pump(); await tester.tap( find.byKey( const Key('purchaseSubscriptionDialog_closeIconButton'), ), ); await tester.pump(); verify(navigator.pop).called(1); }); testWidgets( 'shows PurchaseCompleted dialog ' 'and adds UserSubscriptionConversionEvent to AnalyticsBloc ' 'when SubscriptionsBloc emits purchaseStatus.completed', (tester) async { final navigator = MockNavigator(); final analyticsBloc = MockAnalyticsBloc(); when(navigator.maybePop<void>).thenAnswer((_) async => true); when( () => inAppPurchaseRepository.purchaseUpdate, ).thenAnswer( (_) => Stream.fromIterable( [const PurchaseDelivered(subscription: subscription)], ), ); await tester.pumpApp( const PurchaseSubscriptionDialog(), navigator: navigator, inAppPurchaseRepository: inAppPurchaseRepository, analyticsBloc: analyticsBloc, userRepository: userRepository, ); await tester.pump(); expect(find.byType(PurchaseCompletedDialog), findsOneWidget); verify( () => analyticsBloc.add( TrackAnalyticsEvent( UserSubscriptionConversionEvent(), ), ), ).called(1); }); }); group('PurchaseCompletedDialog', () { testWidgets('closes after 3 seconds', (tester) async { const buttonText = 'buttonText'; await tester.pumpApp( Builder( builder: (context) { return AppButton.black( child: const Text('buttonText'), onPressed: () => showAppModal<void>( context: context, builder: (context) => const PurchaseCompletedDialog(), ), ); }, ), inAppPurchaseRepository: inAppPurchaseRepository, ); await tester.tap(find.text(buttonText)); await tester.pump(); expect(find.byType(PurchaseCompletedDialog), findsOneWidget); await tester.pumpAndSettle(const Duration(seconds: 3)); await tester.pump(); expect(find.byType(PurchaseCompletedDialog), findsNothing); }); }); }
news_toolkit/flutter_news_example/test/subscriptions/dialog/view/purchase_subscription_dialog_test.dart/0
{'file_path': 'news_toolkit/flutter_news_example/test/subscriptions/dialog/view/purchase_subscription_dialog_test.dart', 'repo_id': 'news_toolkit', 'token_count': 2548}
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'auth_state.dart'; class AuthCubit extends Cubit<AuthState> { AuthCubit() : super(AuthInitial()) { checkAuth(); } void checkAuth() { emit(AuthLoading()); final bool isAuthenticated = FirebaseAuth.instance.currentUser != null; if (isAuthenticated) { emit(AuthAuthenticated()); } else { emit(AuthUnauthenticated()); } } }
notely/lib/app/cubits/auth/auth_cubit.dart/0
{'file_path': 'notely/lib/app/cubits/auth/auth_cubit.dart', 'repo_id': 'notely', 'token_count': 176}
import 'package:flutter/material.dart'; class NotelyButton extends StatelessWidget { const NotelyButton({ Key? key, required this.text, required this.onPressed, this.loading = false, }) : super(key: key); final String text; final VoidCallback onPressed; final bool loading; @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; final theme = Theme.of(context); return SizedBox( width: size.width, child: ElevatedButton( onPressed: loading ? null : onPressed, style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric( vertical: 24, ), shape: RoundedRectangleBorder( borderRadius: BorderRadiusDirectional.circular(12), ), elevation: 0, backgroundColor: theme.colorScheme.secondary, ), child: loading ? const SizedBox( height: 20, width: 20, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.white), strokeWidth: 2, ), ) : Text( text, style: const TextStyle( fontSize: 20, fontWeight: FontWeight.w900, color: Color(0xFFFFFBFA), ), ), ), ); } }
notely/lib/app/ui/widgets/notely_button.dart/0
{'file_path': 'notely/lib/app/ui/widgets/notely_button.dart', 'repo_id': 'notely', 'token_count': 725}
import 'package:ordered_set/ordered_set.dart'; class _CacheEntry<C, T> { final List<C> data; _CacheEntry({required this.data}); bool check(T t) { return t is C; } } /// This is an implementation of [OrderedSet] that allows you to more /// efficiently [query] the list. /// /// You can [register] a set of queries, i.e., predefined sub-types, whose /// results, i.e., subsets of this set, are then cached. Since the queries /// have to be type checks, and types are runtime constants, this can be /// vastly optimized. /// /// If you find yourself doing a lot of: /// /// ```dart /// orderedSet.whereType<Foo>() /// ``` /// /// On your code, and are concerned you are iterating a very long O(n) list to /// find a handful of elements, specially if this is done every tick, you /// can use this class, that pays a small O(number of registers) cost on [add], /// but lets you find (specific) subsets at O(0). /// /// Note that you can change [strictMode] to allow for querying for unregistered /// types; if you do so, the registration cost is payed on the first query. class QueryableOrderedSet<T> extends OrderedSet<T> { /// Controls whether running an unregistered query throws an error or /// performs just-in-time filtering. final bool strictMode; final Map<Type, _CacheEntry<T, T>> _cache = {}; QueryableOrderedSet({ int Function(T e1, T e2)? comparator, this.strictMode = true, }) : super(comparator); /// Adds a new cache for a subtype [C] of [T], allowing you to call [query]. /// If the cache already exists this operation is a no-op. /// /// If the set is not empty, the current elements will be re-sorted. /// /// It is recommended to [register] all desired types at the beginning of /// your application to avoid recomputing the existing elements upon /// registration. void register<C extends T>() { if (isRegistered<C>()) { return; } _cache[C] = _CacheEntry<C, T>( data: _filter<C>(), ); } /// Allow you to find a subset of this set with all the elements `e` for /// which the condition `e is C` is true. This is equivalent to /// /// ```dart /// orderedSet.whereType<C>() /// ``` /// /// except that it is O(0). /// /// Note: you *must* call [register] for every type [C] you desire to use /// before calling this, or set [strictMode] to false. List<C> query<C extends T>() { final result = _cache[C]; if (result == null) { if (strictMode) { throw 'Cannot query unregistered query $C'; } else { register<C>(); return query<C>(); } } return result.data as List<C>; } /// Whether type [C] is registered as a cache bool isRegistered<C>() => _cache.containsKey(C); @override bool add(T t) { if (super.add(t)) { _cache.forEach((key, value) { if (value.check(t)) { value.data.add(t); } }); return true; } return false; } @override bool remove(T e) { _cache.values.forEach((v) => v.data.remove(e)); return super.remove(e); } @override void clear() { _cache.values.forEach((v) => v.data.clear()); super.clear(); } List<C> _filter<C extends T>() => whereType<C>().toList(); }
ordered_set/lib/queryable_ordered_set.dart/0
{'file_path': 'ordered_set/lib/queryable_ordered_set.dart', 'repo_id': 'ordered_set', 'token_count': 1153}
import 'dart:io'; import 'package:clock/clock.dart'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:meta/meta.dart'; import 'package:ovavue/core.dart'; import 'package:ovavue/domain.dart'; import 'package:rxdart/transformers.dart'; import 'package:uuid/uuid.dart'; part 'daos.dart'; part 'database.g.dart'; part 'mappings.dart'; part 'tables.dart'; @DriftDatabase( tables: <Type>[ Accounts, Users, Budgets, BudgetPlans, BudgetCategories, BudgetAllocations, BudgetMetadataKeys, BudgetMetadataValues, BudgetMetadataAssociations, ], daos: <Type>[ AccountsDao, UsersDao, BudgetsDao, BudgetPlansDao, BudgetCategoriesDao, BudgetAllocationsDao, BudgetMetadataDao, ], ) class Database extends _$Database { Database(String path) : super(LazyDatabase(() => NativeDatabase.createInBackground(File(path)))); Database.memory() : super(NativeDatabase.memory(logStatements: true)); @override int get schemaVersion => 2; @override MigrationStrategy get migration => MigrationStrategy( beforeOpen: (OpeningDetails details) async => customStatement('PRAGMA foreign_keys = ON'), onCreate: (Migrator m) async => m.createAll(), onUpgrade: (Migrator m, int from, int to) async { if (from < 2) { await Future.wait(<Future<void>>[ m.createTable(budgetMetadataKeys), m.createTable(budgetMetadataValues), m.createTable(budgetMetadataAssociations), ]); } }, ); }
ovavue/lib/data/local_database/database.dart/0
{'file_path': 'ovavue/lib/data/local_database/database.dart', 'repo_id': 'ovavue', 'token_count': 645}
import 'dart:async'; import 'package:ovavue/domain.dart'; import 'theme_mode_storage.dart'; class PreferencesLocalImpl implements PreferencesRepository { const PreferencesLocalImpl(this._themeModeStorage); final ThemeModeStorage _themeModeStorage; @override Future<int?> fetchThemeMode() async => _themeModeStorage.get(); @override Future<bool> updateThemeMode(int themeMode) async { await _themeModeStorage.set(themeMode); return true; } }
ovavue/lib/data/repositories/preferences/preferences_local_impl.dart/0
{'file_path': 'ovavue/lib/data/repositories/preferences/preferences_local_impl.dart', 'repo_id': 'ovavue', 'token_count': 145}
import 'reference_entity.dart'; sealed class BudgetMetadataValueOperation {} class BudgetMetadataValueCreationOperation implements BudgetMetadataValueOperation { const BudgetMetadataValueCreationOperation({ required this.title, required this.value, }); final String title; final String value; } class BudgetMetadataValueModificationOperation implements BudgetMetadataValueOperation { const BudgetMetadataValueModificationOperation({ required this.reference, required this.title, required this.value, }); final ReferenceEntity reference; final String title; final String value; } class BudgetMetadataValueRemovalOperation implements BudgetMetadataValueOperation { const BudgetMetadataValueRemovalOperation({ required this.reference, }); final ReferenceEntity reference; }
ovavue/lib/domain/entities/budget_metadata_value_operation.dart/0
{'file_path': 'ovavue/lib/domain/entities/budget_metadata_value_operation.dart', 'repo_id': 'ovavue', 'token_count': 212}
import '../entities/budget_category_entity.dart'; import '../entities/create_budget_category_data.dart'; import '../entities/reference_entity.dart'; import '../entities/update_budget_category_data.dart'; abstract class BudgetCategoriesRepository { Future<String> create(String userId, CreateBudgetCategoryData category); Future<bool> update(UpdateBudgetCategoryData category); Future<bool> delete(ReferenceEntity reference); Stream<BudgetCategoryEntityList> fetchAll(String userId); }
ovavue/lib/domain/repositories/budget_categories.dart/0
{'file_path': 'ovavue/lib/domain/repositories/budget_categories.dart', 'repo_id': 'ovavue', 'token_count': 142}
import '../analytics/analytics.dart'; import '../analytics/analytics_event.dart'; import '../repositories/budget_allocations.dart'; import '../repositories/budget_plans.dart'; class DeleteBudgetPlanUseCase { const DeleteBudgetPlanUseCase({ required BudgetPlansRepository plans, required BudgetAllocationsRepository allocations, required Analytics analytics, }) : _plans = plans, _allocations = allocations, _analytics = analytics; final BudgetPlansRepository _plans; final BudgetAllocationsRepository _allocations; final Analytics _analytics; Future<bool> call({required String userId, required String id, required String path}) { _analytics.log(AnalyticsEvent.deleteBudgetPlan(path)).ignore(); return _allocations.deleteByPlan(userId: userId, planId: id).then((bool successful) { if (successful) { return _plans.delete((id: id, path: path)); } return successful; }); } }
ovavue/lib/domain/use_cases/delete_budget_plan_use_case.dart/0
{'file_path': 'ovavue/lib/domain/use_cases/delete_budget_plan_use_case.dart', 'repo_id': 'ovavue', 'token_count': 320}
import '../analytics/analytics.dart'; import '../analytics/analytics_event.dart'; import '../entities/update_budget_allocation_data.dart'; import '../repositories/budget_allocations.dart'; class UpdateBudgetAllocationUseCase { const UpdateBudgetAllocationUseCase({ required BudgetAllocationsRepository allocations, required Analytics analytics, }) : _allocations = allocations, _analytics = analytics; final BudgetAllocationsRepository _allocations; final Analytics _analytics; Future<bool> call(UpdateBudgetAllocationData allocation) { _analytics.log(AnalyticsEvent.updateBudgetAllocation(allocation.path)).ignore(); return _allocations.update(allocation); } }
ovavue/lib/domain/use_cases/update_budget_allocation_use_case.dart/0
{'file_path': 'ovavue/lib/domain/use_cases/update_budget_allocation_use_case.dart', 'repo_id': 'ovavue', 'token_count': 214}
export 'models/budget_allocation_view_model.dart'; export 'models/budget_category_view_model.dart'; export 'models/budget_metadata_key_view_model.dart'; export 'models/budget_metadata_value_view_model.dart'; export 'models/budget_metadata_view_model.dart'; export 'models/budget_plan_view_model.dart'; export 'models/budget_view_model.dart'; export 'models/selected_budget_category_view_model.dart';
ovavue/lib/presentation/models.dart/0
{'file_path': 'ovavue/lib/presentation/models.dart', 'repo_id': 'ovavue', 'token_count': 133}
import 'package:equatable/equatable.dart'; import '../../../models.dart'; import '../../../utils.dart'; import 'models.dart'; class BudgetCategoryState with EquatableMixin { const BudgetCategoryState({ required this.category, required this.allocation, required this.budget, required this.plans, }); final BudgetCategoryViewModel category; final Money? allocation; final BudgetViewModel? budget; final List<BudgetCategoryPlanViewModel> plans; @override List<Object?> get props => <Object?>[category, allocation, budget, plans]; }
ovavue/lib/presentation/screens/budget_categories/providers/budget_category_state.dart/0
{'file_path': 'ovavue/lib/presentation/screens/budget_categories/providers/budget_category_state.dart', 'repo_id': 'ovavue', 'token_count': 173}
import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../models.dart'; import '../../../state.dart'; import '../../../utils.dart'; import '../../../widgets.dart'; void deleteBudgetPlanAction( BuildContext context, { required WidgetRef ref, required BudgetPlanViewModel plan, required bool dismissOnComplete, }) async { final L10n l10n = context.l10n; final AppSnackBar snackBar = context.snackBar; final NavigatorState navigator = Navigator.of(context); final bool choice = await showErrorChoiceBanner( context, message: l10n.deletePlanAreYouSureAboutThisMessage, ); if (!choice) { return; } final bool successful = await ref.read(budgetPlanProvider).delete( id: plan.id, path: plan.path, ); if (successful) { snackBar.success(l10n.successfulMessage); if (dismissOnComplete) { navigator.pop(); } } else { snackBar.error(l10n.genericErrorMessage); } }
ovavue/lib/presentation/screens/budget_plans/utils/delete_budget_plan_action.dart/0
{'file_path': 'ovavue/lib/presentation/screens/budget_plans/utils/delete_budget_plan_action.dart', 'repo_id': 'ovavue', 'token_count': 361}
export 'state/account_provider.dart'; export 'state/app_version_provider.dart'; export 'state/backup_client_controller_provider.dart'; export 'state/budget_categories_provider.dart'; export 'state/budget_category_provider.dart'; export 'state/budget_metadata_provider.dart'; export 'state/budget_plan_provider.dart'; export 'state/budget_plans_by_metadata_state.dart'; export 'state/budget_plans_provider.dart'; export 'state/budget_state.dart'; export 'state/budgets_provider.dart'; export 'state/preferences_provider.dart'; export 'state/registry_provider.dart'; export 'state/selected_budget_metadata_by_plan_provider.dart'; export 'state/selected_budget_plans_by_metadata_provider.dart'; export 'state/selected_budget_provider.dart'; export 'state/user_provider.dart';
ovavue/lib/presentation/state.dart/0
{'file_path': 'ovavue/lib/presentation/state.dart', 'repo_id': 'ovavue', 'token_count': 269}
import 'package:flutter/material.dart'; import '../theme.dart'; Future<bool> showErrorChoiceBanner( BuildContext context, { required String message, }) async { final ThemeData theme = context.theme; final ScaffoldMessengerState scaffoldMessengerState = ScaffoldMessenger.of(context) ..removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss); final Color backgroundColor = theme.colorScheme.onError; final Future<MaterialBannerClosedReason> result = scaffoldMessengerState .showMaterialBanner( MaterialBanner( backgroundColor: theme.colorScheme.error, content: Text(message), contentTextStyle: theme.textTheme.bodyLarge?.copyWith(color: backgroundColor), actions: <Widget>[ IconButton( onPressed: scaffoldMessengerState.removeCurrentMaterialBanner, icon: const Icon(Icons.check_outlined), color: backgroundColor, ), IconButton( onPressed: scaffoldMessengerState.hideCurrentMaterialBanner, icon: const Icon(Icons.close_outlined), color: backgroundColor, ), ], ), ) .closed; return await result == MaterialBannerClosedReason.remove; }
ovavue/lib/presentation/utils/show_error_choice_banner.dart/0
{'file_path': 'ovavue/lib/presentation/utils/show_error_choice_banner.dart', 'repo_id': 'ovavue', 'token_count': 515}
import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ovavue/data.dart'; import 'package:ovavue/domain.dart'; import '../../utils.dart'; void main() { group('FetchUserUseCase', () { final FetchUserUseCase useCase = FetchUserUseCase(users: mockRepositories.users); final UserEntity dummyUser = UsersMockImpl.user; tearDown(mockRepositories.reset); test('should fetch users', () { when(() => mockRepositories.users.fetch(any())).thenAnswer((_) async => dummyUser); expect(useCase('1'), completion(dummyUser)); }); test('should fail gracefully with null', () { when(() => mockRepositories.users.fetch(any())).thenThrow(Exception('an error')); expect(useCase('1'), completion(isNull)); }); }); }
ovavue/test/domain/use_cases/fetch_user_use_case_test.dart/0
{'file_path': 'ovavue/test/domain/use_cases/fetch_user_use_case_test.dart', 'repo_id': 'ovavue', 'token_count': 291}
blank_issues_enabled: true contact_links: - name: I have some questions about Oxygen. url: https://stackoverflow.com/tags/oxygen about: Ask your questions on StackOverflow! The community is always willing to help out. - name: Join us on Discord! url: https://discord.gg/JUwwvNryDz about: Ask your questions in our community!
oxygen/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'oxygen/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'oxygen', 'token_count': 111}
import 'package:example/utils/color.dart'; import 'package:example/components/color_component.dart'; import 'package:example/components/name_component.dart'; import 'package:example/utils/terminal.dart'; import 'package:example/utils/vector2.dart'; import 'package:oxygen/oxygen.dart'; import '../components/render_component.dart'; import '../components/position_component.dart'; class RenderSystem extends System { late Query query; @override void init() { query = createQuery([ Has<RenderComponent>(), Has<PositionComponent>(), ]); } @override void execute(delta) { query.entities.forEach((entity) { final position = entity.get<PositionComponent>()!; final key = entity.get<RenderComponent>()!.value; final color = entity.get<ColorComponent>()?.value ?? Colors.white; terminal ..save() ..translate(position.x!, position.y!) ..draw(key!, foregroundColor: color); if (entity.has<NameComponent>()) { final name = entity.get<NameComponent>()!.value!; terminal ..translate(-(name.length ~/ 2), 1) ..draw(name); } terminal.restore(); }); terminal.draw('delta: $delta', foregroundColor: Colors.green); terminal.draw( 'entites: ${world!.entities.length}', foregroundColor: Colors.green, position: Vector2(0, 1), ); terminal.draw( ' W A S D | Move Tim\n' ' Space | Shoot', foregroundColor: Colors.green, position: terminal.viewport.bottomLeft.translate(0, -2), ); } }
oxygen/example/lib/systems/render_system.dart/0
{'file_path': 'oxygen/example/lib/systems/render_system.dart', 'repo_id': 'oxygen', 'token_count': 614}