code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'package:flame/cache.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:provider/provider.dart'; class _MockImages extends Mock implements Images {} void main() { group('VictoryChargeBack', () { late Images images; setUp(() { images = _MockImages(); }); testWidgets('renders SpriteAnimationWidget', (tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Provider.value( value: images, child: const VictoryChargeBack( '', assetSize: AssetSize.large, size: GameCardSize.md(), animationColor: Colors.white, ), ), ), ); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/damages/victory_charge_back_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/damages/victory_charge_back_test.dart', 'repo_id': 'io_flip', 'token_count': 443}
import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; void main() { group('SuitIcons', () { test('use their corresponding asset', () { expect( SuitIcon.fire().asset, equals(Assets.images.suits.onboarding.fire), ); expect( SuitIcon.air().asset, equals(Assets.images.suits.onboarding.air), ); expect( SuitIcon.metal().asset, equals(Assets.images.suits.onboarding.metal), ); expect( SuitIcon.earth().asset, equals(Assets.images.suits.onboarding.earth), ); expect( SuitIcon.water().asset, equals(Assets.images.suits.onboarding.water), ); }); testWidgets('renders size correctly', (tester) async { await tester.pumpWidget(SuitIcon.fire(scale: 2)); expect( tester.widget(find.byType(SuitIcon)), isA<SuitIcon>().having((i) => i.size, 'size', 192), ); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/suit_icons_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/suit_icons_test.dart', 'repo_id': 'io_flip', 'token_count': 482}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/draft/draft.dart'; void main() { group('DeckRequested', () { test('can be instantiated', () { expect( DeckRequested(Prompt()), isNotNull, ); }); test('supports equality', () { expect( DeckRequested(Prompt()), equals(DeckRequested(Prompt())), ); }); }); group('PreviousCard', () { test('can be instantiated', () { expect( PreviousCard(), isNotNull, ); }); test('supports equality', () { expect( PreviousCard(), equals(PreviousCard()), ); }); }); group('NextCard', () { test('can be instantiated', () { expect( NextCard(), isNotNull, ); }); test('supports equality', () { expect( NextCard(), equals(NextCard()), ); }); }); group('CardSwiped', () { test('can be instantiated', () { expect( CardSwiped(), isNotNull, ); }); test('supports equality', () { expect( CardSwiped(), equals(CardSwiped()), ); }); }); group('CardSwipeStarted', () { test('can be instantiated', () { expect( CardSwipeStarted(0), isNotNull, ); }); test('supports equality', () { expect( CardSwipeStarted(.8), equals(CardSwipeStarted(.8)), ); expect( CardSwipeStarted(.8), isNot(equals(CardSwipeStarted(.9))), ); }); }); group('SelectCard', () { test('can be instantiated', () { expect( SelectCard(0), isNotNull, ); }); test('supports equality', () { expect( SelectCard(0), equals(SelectCard(0)), ); expect( SelectCard(0), isNot(equals(SelectCard(1))), ); }); }); group('PlayerDeckRequested', () { test('can be instantiated', () { expect( PlayerDeckRequested(const ['id1', 'id2', 'id3']), isNotNull, ); }); test('supports equality', () { expect( PlayerDeckRequested( const ['id1', 'id2', 'id3'], createPrivateMatch: true, privateMatchInviteCode: 'code', ), equals( PlayerDeckRequested( const ['id1', 'id2', 'id3'], createPrivateMatch: true, privateMatchInviteCode: 'code', ), ), ); expect( PlayerDeckRequested( const ['id1', 'id2', 'id3'], createPrivateMatch: true, privateMatchInviteCode: 'code', ), isNot( equals( PlayerDeckRequested( const ['id1', 'id2', 'id4'], createPrivateMatch: true, privateMatchInviteCode: 'code', ), ), ), ); expect( PlayerDeckRequested( const ['id1', 'id2', 'id3'], ), isNot( equals( PlayerDeckRequested( const ['id1', 'id2', 'id3'], createPrivateMatch: true, ), ), ), ); expect( PlayerDeckRequested( const ['id1', 'id2', 'id3'], ), isNot( equals( PlayerDeckRequested( const ['id1', 'id2', 'id3'], privateMatchInviteCode: 'code', ), ), ), ); }); }); }
io_flip/test/draft/bloc/draft_event_test.dart/0
{'file_path': 'io_flip/test/draft/bloc/draft_event_test.dart', 'repo_id': 'io_flip', 'token_count': 1899}
import 'package:api_client/api_client.dart'; import 'package:authentication_repository/authentication_repository.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:config_repository/config_repository.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:equatable/equatable.dart'; import 'package:flame/cache.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/settings/settings.dart'; import 'package:io_flip/style/snack_bar.dart'; import 'package:io_flip/terms_of_use/terms_of_use.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:match_maker_repository/match_maker_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:provider/provider.dart'; import 'helpers.dart'; class _MockSettingsController extends Mock implements SettingsController {} class _MockGameResource extends Mock implements GameResource {} class _MockShareResource extends Mock implements ShareResource {} class _MockPromptResource extends Mock implements PromptResource {} class _MockScriptsResource extends Mock implements ScriptsResource {} class _MockLeaderboardResource extends Mock implements LeaderboardResource {} class _MockMatchMakerRepository extends Mock implements MatchMakerRepository {} class _MockConfigRepository extends Mock implements ConfigRepository {} class _MockConnectionRepository extends Mock implements ConnectionRepository {} class _MockMatchSolver extends Mock implements MatchSolver {} class _MockGameScriptMachine extends Mock implements GameScriptMachine {} class _MockAudioController extends Mock implements AudioController {} class _MockUser extends Mock implements User {} class _MockUISoundAdapter extends Mock implements UISoundAdapter {} class _MockGoRouter extends Mock implements GoRouter {} class _MockImages extends Mock implements Images {} class _MockTermsOfUseCubit extends MockCubit<bool> implements TermsOfUseCubit {} UISoundAdapter _createUISoundAdapter() { final adapter = _MockUISoundAdapter(); when(() => adapter.playButtonSound).thenReturn(() {}); return adapter; } extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { SettingsController? settingsController, GameResource? gameResource, ShareResource? shareResource, ScriptsResource? scriptsResource, PromptResource? promptResource, LeaderboardResource? leaderboardResource, MatchMakerRepository? matchMakerRepository, ConfigRepository? configRepository, AudioController? audioController, ConnectionRepository? connectionRepository, MatchSolver? matchSolver, GameScriptMachine? gameScriptMachine, UISoundAdapter? uiSoundAdapter, User? user, GoRouter? router, Images? images, }) { return pumpWidget( MultiProvider( providers: [ Provider.value( value: settingsController ?? _MockSettingsController(), ), Provider.value( value: gameResource ?? _MockGameResource(), ), Provider.value( value: shareResource ?? _MockShareResource(), ), Provider.value( value: scriptsResource ?? _MockScriptsResource(), ), Provider.value( value: promptResource ?? _MockPromptResource(), ), Provider.value( value: leaderboardResource ?? _MockLeaderboardResource(), ), Provider.value( value: matchMakerRepository ?? _MockMatchMakerRepository(), ), Provider.value( value: configRepository ?? _MockConfigRepository(), ), Provider.value( value: audioController ?? _MockAudioController(), ), Provider.value( value: connectionRepository ?? _MockConnectionRepository(), ), Provider.value( value: matchSolver ?? _MockMatchSolver(), ), Provider.value( value: uiSoundAdapter ?? _createUISoundAdapter(), ), Provider.value( value: gameScriptMachine ?? _MockGameScriptMachine(), ), Provider.value( value: user ?? _MockUser(), ), Provider.value( value: images ?? _MockImages(), ) ], child: MockGoRouterProvider( goRouter: router ?? _MockGoRouter(), child: MaterialApp( scaffoldMessengerKey: scaffoldMessengerKey, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ), ), ); } } extension PumpAppWithRouter on WidgetTester { Future<void> pumpAppWithRouter<T extends Bloc<Equatable, Equatable>>( GoRouter router, { SettingsController? settingsController, GameResource? gameResource, ShareResource? shareResource, ScriptsResource? scriptsResource, PromptResource? promptResource, LeaderboardResource? leaderboardResource, MatchMakerRepository? matchMakerRepository, ConfigRepository? configRepository, AudioController? audioController, ConnectionRepository? connectionRepository, MatchSolver? matchSolver, GameScriptMachine? gameScriptMachine, UISoundAdapter? uiSoundAdapter, User? user, Images? images, T? bloc, TermsOfUseCubit? termsOfUseCubit, }) { return pumpWidget( MultiProvider( providers: [ Provider.value( value: settingsController ?? _MockSettingsController(), ), Provider.value( value: gameResource ?? _MockGameResource(), ), Provider.value( value: shareResource ?? _MockShareResource(), ), Provider.value( value: scriptsResource ?? _MockScriptsResource(), ), Provider.value( value: promptResource ?? _MockPromptResource(), ), Provider.value( value: leaderboardResource ?? _MockLeaderboardResource(), ), Provider.value( value: matchMakerRepository ?? _MockMatchMakerRepository(), ), Provider.value( value: configRepository ?? _MockConfigRepository(), ), Provider.value( value: audioController ?? _MockAudioController(), ), Provider.value( value: connectionRepository ?? _MockConnectionRepository(), ), Provider.value( value: matchSolver ?? _MockMatchSolver(), ), Provider.value( value: uiSoundAdapter ?? _createUISoundAdapter(), ), Provider.value( value: gameScriptMachine ?? _MockGameScriptMachine(), ), Provider.value( value: user ?? _MockUser(), ), Provider.value( value: images ?? _MockImages(), ) ], child: MultiBlocProvider( providers: [ if (bloc != null) BlocProvider<T>.value(value: bloc), BlocProvider<TermsOfUseCubit>.value( value: termsOfUseCubit ?? _MockTermsOfUseCubit(), ), ], child: MaterialApp.router( scaffoldMessengerKey: scaffoldMessengerKey, routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, ), ), ), ); } }
io_flip/test/helpers/pump_app.dart/0
{'file_path': 'io_flip/test/helpers/pump_app.dart', 'repo_id': 'io_flip', 'token_count': 3248}
import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/leaderboard/initials_form/initials_form.dart'; void main() { group('InitialsFormState', () { group('copyWith', () { test('does not update omitted params', () { const state = InitialsFormState(initials: ['A', 'B', 'C']); expect(state.copyWith(), equals(state)); }); }); }); }
io_flip/test/leaderboard/initials_form/bloc/initials_form_state_test.dart/0
{'file_path': 'io_flip/test/leaderboard/initials_form/bloc/initials_form_state_test.dart', 'repo_id': 'io_flip', 'token_count': 153}
import 'package:api_client/api_client.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:mocktail/mocktail.dart'; import 'package:provider/provider.dart'; import '../../helpers/helpers.dart'; class _MockPromptResource extends Mock implements PromptResource {} void main() { late PromptResource promptResource; setUpAll(() { registerFallbackValue(PromptTermType.characterClass); }); setUp(() { promptResource = _MockPromptResource(); when(() => promptResource.getPromptTerms(any())) .thenAnswer((_) => Future.value([''])); }); group('PromptPage', () { testWidgets('renders prompt page', (tester) async { await tester.pumpSubject(promptResource); expect(find.byType(PromptView), findsOneWidget); }); }); } extension PromptPageTest on WidgetTester { Future<void> pumpSubject(PromptResource resource) { return pumpApp( Provider.value( value: resource, child: const PromptPage(), ), ); } }
io_flip/test/prompt/view/prompt_page_test.dart/0
{'file_path': 'io_flip/test/prompt/view/prompt_page_test.dart', 'repo_id': 'io_flip', 'token_count': 405}
import 'package:api_client/api_client.dart'; import 'package:flutter/material.dart' hide Card; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/widgets/widgets.dart'; import 'package:io_flip/info/info.dart'; import 'package:io_flip/settings/settings.dart'; import 'package:io_flip/share/views/views.dart'; import 'package:io_flip/share/widgets/widgets.dart'; import 'package:io_flip/utils/utils.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import '../../helpers/helpers.dart'; class _MockGoRouterState extends Mock implements GoRouterState {} class _MockSettingsController extends Mock implements SettingsController {} class _MockGoRouter extends Mock implements GoRouter {} class _MockShareResource extends Mock implements ShareResource {} class _MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} class _FakeLaunchOptions extends Fake implements LaunchOptions {} const card = Card( id: '', name: 'name', description: 'description', image: '', rarity: false, power: 1, suit: Suit.air, ); const pageData = ShareHandPageData( initials: 'AAA', wins: 0, deck: Deck(id: '', userId: '', cards: []), ); void main() { late GoRouterState goRouterState; late UrlLauncherPlatform urlLauncher; setUp(() { goRouterState = _MockGoRouterState(); when(() => goRouterState.extra).thenReturn(pageData); when(() => goRouterState.queryParams).thenReturn({}); urlLauncher = _MockUrlLauncher(); when( () => urlLauncher.canLaunch(any()), ).thenAnswer((_) async => true); when( () => urlLauncher.launchUrl(any(), any()), ).thenAnswer((_) async => true); UrlLauncherPlatform.instance = urlLauncher; }); setUpAll(() { registerFallbackValue(_FakeLaunchOptions()); }); group('ShareHandPage', () { test('routeBuilder returns a ShareHandPage', () { expect( ShareHandPage.routeBuilder(null, goRouterState), isA<ShareHandPage>() .having((page) => page.deck, 'deck', pageData.deck) .having((page) => page.wins, 'wins', pageData.wins) .having((page) => page.initials, 'initials', pageData.initials), ); }); testWidgets('renders', (tester) async { await tester.pumpSubject(); expect(find.byType(ShareHandPage), findsOneWidget); }); testWidgets('renders a IoFlipLogo widget', (tester) async { await tester.pumpSubject(); expect(find.byType(IoFlipLogo), findsOneWidget); }); testWidgets('renders a CardFan widget', (tester) async { await tester.pumpSubject(); expect(find.byType(CardFan), findsOneWidget); }); testWidgets('renders the users wins and initials', (tester) async { await tester.pumpSubject(); expect(find.text('5 ${tester.l10n.winStreakLabel}'), findsOneWidget); expect(find.text('AAA'), findsOneWidget); }); testWidgets('renders the title', (tester) async { await tester.pumpSubject(); expect(find.text(tester.l10n.shareTeamTitle), findsOneWidget); }); testWidgets('renders a menu button', (tester) async { await tester.pumpSubject(); expect(find.text(tester.l10n.mainMenuButtonLabel), findsOneWidget); }); testWidgets('renders a routes to main menu on button tapped', (tester) async { final goRouter = _MockGoRouter(); when(() => goRouter.go('/')).thenAnswer((_) {}); await tester.pumpSubject( router: goRouter, ); await tester.tap(find.text(tester.l10n.mainMenuButtonLabel)); verify(() => goRouter.go('/')).called(1); }); testWidgets('renders a share button', (tester) async { await tester.pumpSubject(); expect(find.text(tester.l10n.shareButtonLabel), findsOneWidget); }); testWidgets('renders a dialog on share button tapped', (tester) async { final shareResource = _MockShareResource(); when(() => shareResource.facebookShareHandUrl(any())).thenReturn(''); when(() => shareResource.twitterShareHandUrl(any())).thenReturn(''); await tester.pumpSubject( shareResource: shareResource, ); await tester.tap(find.text(tester.l10n.shareButtonLabel)); await tester.pumpAndSettle(); expect(find.byType(ShareHandDialog), findsOneWidget); }); testWidgets('renders a music button', (tester) async { await tester.pumpSubject(); expect(find.byType(AudioToggleButton), findsOneWidget); }); testWidgets('renders a dialog on info button tapped', (tester) async { final shareResource = _MockShareResource(); when(() => shareResource.facebookShareHandUrl(any())).thenReturn(''); when(() => shareResource.twitterShareHandUrl(any())).thenReturn(''); await tester.pumpSubject( shareResource: shareResource, ); await tester.tap(find.byKey(const Key('share_page_info_button'))); await tester.pumpAndSettle(); expect(find.byType(InfoView), findsOneWidget); }); testWidgets('tapping io link opens io', (tester) async { await tester.pumpSubject(); await tester.tap(find.text(tester.l10n.ioLinkLabel)); verify( () => urlLauncher.launchUrl(ExternalLinks.googleIO, any()), ).called(1); }); testWidgets('tapping how its made link opens how its made', (tester) async { await tester.pumpSubject(); await tester.tap(find.text(tester.l10n.howItsMadeLinkLabel)); verify( () => urlLauncher.launchUrl(ExternalLinks.howItsMade, any()), ).called(1); }); }); } extension ShareCardDialogTest on WidgetTester { Future<void> pumpSubject({ ShareResource? shareResource, GoRouter? router, }) async { final SettingsController settingsController = _MockSettingsController(); when(() => settingsController.muted).thenReturn(ValueNotifier(true)); await mockNetworkImages(() { return pumpApp( const ShareHandPage( wins: 5, initials: 'AAA', deck: Deck(id: '', userId: '', cards: [card, card, card]), ), shareResource: shareResource, router: router, settingsController: settingsController, ); }); } }
io_flip/test/share/views/share_hand_page_test.dart/0
{'file_path': 'io_flip/test/share/views/share_hand_page_test.dart', 'repo_id': 'io_flip', 'token_count': 2527}
name: checked_yaml version: 2.0.4-wip description: >- Generate more helpful exceptions when decoding YAML documents using package:json_serializable and package:yaml. repository: https://github.com/google/json_serializable.dart/tree/master/checked_yaml topics: - yaml - json - build-runner - json-serializable - codegen environment: sdk: ^3.0.0 dependencies: json_annotation: ^4.3.0 source_span: ^1.8.0 yaml: ^3.0.0 dev_dependencies: build_runner: ^2.0.0 build_verify: ^3.0.0 dart_flutter_team_lints: ^2.0.0 json_serializable: ^6.0.0 path: ^1.0.0 test: ^1.16.0 test_process: ^2.0.0 #dependency_overrides: # json_annotation: # path: ../json_annotation # json_serializable: # path: ../json_serializable
json_serializable/checked_yaml/pubspec.yaml/0
{'file_path': 'json_serializable/checked_yaml/pubspec.yaml', 'repo_id': 'json_serializable', 'token_count': 310}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'nested_values_example.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** NestedValueExample _$NestedValueExampleFromJson(Map<String, dynamic> json) => NestedValueExample( const _NestedListConverter() .fromJson(json['root_items'] as Map<String, dynamic>), ); Map<String, dynamic> _$NestedValueExampleToJson(NestedValueExample instance) => <String, dynamic>{ 'root_items': const _NestedListConverter().toJson(instance.nestedValues), };
json_serializable/example/lib/nested_values_example.g.dart/0
{'file_path': 'json_serializable/example/lib/nested_values_example.g.dart', 'repo_id': 'json_serializable', 'token_count': 204}
// Copyright (c) 2017, 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. /// Provides annotation classes to use with /// [json_serializable](https://pub.dev/packages/json_serializable). /// /// Also contains helper functions and classes – prefixed with `$` used by /// `json_serializable` when the `use_wrappers` or `checked` options are /// enabled. library json_annotation; export 'src/allowed_keys_helpers.dart'; export 'src/checked_helpers.dart'; export 'src/enum_helpers.dart'; export 'src/json_converter.dart'; export 'src/json_enum.dart'; export 'src/json_key.dart'; export 'src/json_literal.dart'; export 'src/json_serializable.dart'; export 'src/json_value.dart';
json_serializable/json_annotation/lib/json_annotation.dart/0
{'file_path': 'json_serializable/json_annotation/lib/json_annotation.dart', 'repo_id': 'json_serializable', 'token_count': 255}
# Read about `build.yaml` at https://pub.dev/packages/build_config targets: $default: builders: source_gen|combining_builder: options: ignore_for_file: - lines_longer_than_80_chars # Only for the JSON literal output file - text_direction_code_point_in_literal # Too much work in generated code - inference_failure_on_function_invocation # Need to update sourcegen_helper to generate List/Map with the right type params - inference_failure_on_collection_literal json_serializable: generate_for: - example/* - test/default_value/* - test/field_matrix_test.field_matrix.dart - test/generic_files/* - test/integration/* - test/kitchen_sink/* - test/literal/* - test/supported_types/* - tool/readme/* json_serializable|_field_matrix_builder: generate_for: - test/field_matrix_test.dart json_serializable|_test_builder: generate_for: - test/default_value/default_value.dart - test/generic_files/generic_class.dart - test/integration/json_test_example.dart - test/kitchen_sink/kitchen_sink.dart json_serializable|_type_builder: generate_for: - test/supported_types/input.dart json_serializable|_type_test_builder: generate_for: - test/supported_types/type_test.dart builders: _test_builder: import: 'tool/test_builder.dart' builder_factories: ['testBuilder'] build_extensions: .dart: - .factories.dart - .g_any_map.dart - .g_any_map__checked.dart - .g_exclude_null.dart - .g_explicit_to_json.dart build_to: source runs_before: ["json_serializable"] _type_builder: import: 'tool/test_type_builder.dart' builder_factories: ['typeBuilder'] build_extensions: .dart: - .type_bigint.dart - .type_bool.dart - .type_datetime.dart - .type_double.dart - .type_duration.dart - .type_enumtype.dart - .type_int.dart - .type_iterable.dart - .type_list.dart - .type_map.dart - .type_num.dart - .type_object.dart - .type_record.dart - .type_set.dart - .type_string.dart - .type_uri.dart build_to: source runs_before: ["json_serializable"] _type_test_builder: import: 'tool/test_type_builder.dart' builder_factories: ['typeTestBuilder'] build_extensions: .dart: - .bigint_test.dart - .bool_test.dart - .datetime_test.dart - .double_test.dart - .duration_test.dart - .enumtype_test.dart - .int_test.dart - .iterable_test.dart - .list_test.dart - .map_test.dart - .num_test.dart - .object_test.dart - .set_test.dart - .string_test.dart - .uri_test.dart build_to: source runs_before: ["json_serializable"] _field_matrix_builder: import: 'tool/field_matrix_builder.dart' builder_factories: ['builder'] build_extensions: .dart: [.field_matrix.dart] build_to: source runs_before: ["json_serializable"] _readme_builder: import: "tool/readme_builder.dart" builder_factories: ["readmeBuilder"] build_extensions: {"tool/readme/readme_template.md": ["README.md"]} build_to: source auto_apply: root_package required_inputs: ['.dart'] json_serializable: import: "package:json_serializable/builder.dart" builder_factories: ["jsonSerializable"] build_extensions: {".dart": ["json_serializable.g.part"]} auto_apply: dependents build_to: cache applies_builders: ["source_gen|combining_builder"]
json_serializable/json_serializable/build.yaml/0
{'file_path': 'json_serializable/json_serializable/build.yaml', 'repo_id': 'json_serializable', 'token_count': 1728}
// 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:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:build/build.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; import 'json_literal_generator.dart'; import 'shared_checkers.dart'; import 'type_helpers/config_types.dart'; import 'utils.dart'; final _jsonKeyExpando = Expando<Map<ClassConfig, KeyConfig>>(); KeyConfig jsonKeyForField(FieldElement field, ClassConfig classAnnotation) => (_jsonKeyExpando[field] ??= Map.identity())[classAnnotation] ??= _from(field, classAnnotation); KeyConfig _from(FieldElement element, ClassConfig classAnnotation) { // If an annotation exists on `element` the source is a 'real' field. // If the result is `null`, check the getter – it is a property. // TODO: setters: github.com/google/json_serializable.dart/issues/24 final obj = jsonKeyAnnotation(element); final ctorParamDefault = classAnnotation.ctorParamDefaults[element.name]; if (obj.isNull) { return _populateJsonKey( classAnnotation, element, defaultValue: ctorParamDefault, includeFromJson: classAnnotation.ignoreUnannotated ? false : null, includeToJson: classAnnotation.ignoreUnannotated ? false : null, ); } /// Returns a literal value for [dartObject] if possible, otherwise throws /// an [InvalidGenerationSourceError] using [typeInformation] to describe /// the unsupported type. Object? literalForObject( String fieldName, DartObject dartObject, Iterable<String> typeInformation, ) { if (dartObject.isNull) { return null; } final reader = ConstantReader(dartObject); String? badType; if (reader.isSymbol) { badType = 'Symbol'; } else if (reader.isType) { badType = 'Type'; } else if (dartObject.type is FunctionType) { // Function types at the "root" are already handled. If they occur // here, it's because the function is nested instead of a collection // literal, which is NOT supported! badType = 'Function'; } else if (!reader.isLiteral) { badType = dartObject.type!.element?.name; } if (badType != null) { badType = typeInformation.followedBy([badType]).join(' > '); throwUnsupported( element, '`$fieldName` is `$badType`, it must be a literal.', ); } if (reader.isDouble || reader.isInt || reader.isString || reader.isBool) { return reader.literalValue; } if (reader.isList) { return [ for (var e in reader.listValue) literalForObject(fieldName, e, [ ...typeInformation, 'List', ]) ]; } if (reader.isSet) { return { for (var e in reader.setValue) literalForObject(fieldName, e, [ ...typeInformation, 'Set', ]) }; } if (reader.isMap) { final mapTypeInformation = [ ...typeInformation, 'Map', ]; return reader.mapValue.map( (k, v) => MapEntry( literalForObject(fieldName, k!, mapTypeInformation), literalForObject(fieldName, v!, mapTypeInformation), ), ); } badType = typeInformation.followedBy(['$dartObject']).join(' > '); throwUnsupported( element, 'The provided value is not supported: $badType. ' 'This may be an error in package:json_serializable. ' 'Please rerun your build with `--verbose` and file an issue.', ); } /// Returns a literal object representing the value of [fieldName] in [obj]. /// /// If [mustBeEnum] is `true`, throws an [InvalidGenerationSourceError] if /// either the annotated field is not an `enum` or `List` or if the value in /// [fieldName] is not an `enum` value. String? createAnnotationValue(String fieldName, {bool mustBeEnum = false}) { final annotationValue = obj.read(fieldName); if (annotationValue.isNull) { return null; } final objectValue = annotationValue.objectValue; final annotationType = objectValue.type!; if (annotationType is FunctionType) { // TODO: we could be a LOT more careful here, checking the return type // and the number of parameters. BUT! If any of those things are wrong // the generated code will be invalid, so skipping until we're bored // later final functionValue = objectValue.toFunctionValue()!; final invokeConst = functionValue is ConstructorElement && functionValue.isConst ? 'const ' : ''; return '$invokeConst${functionValue.qualifiedName}()'; } final enumFields = iterateEnumFields(annotationType); if (enumFields != null) { if (mustBeEnum) { late DartType targetEnumType; if (element.type.isEnum) { targetEnumType = element.type; } else if (coreIterableTypeChecker.isAssignableFromType(element.type)) { targetEnumType = coreIterableGenericType(element.type); } else { throwUnsupported( element, '`$fieldName` can only be set on fields of type enum or on ' 'Iterable, List, or Set instances of an enum type.', ); } if (_nullAsUnknownChecker.isExactlyType(annotationType)) { return jsonKeyNullForUndefinedEnumValueFieldName; } else if (!_interfaceTypesEqual(annotationType, targetEnumType)) { throwUnsupported( element, '`$fieldName` has type ' '`${targetEnumType.getDisplayString(withNullability: false)}`, but ' 'the provided unknownEnumValue is of type ' '`${annotationType.getDisplayString(withNullability: false)}`.', ); } } if (_nullAsUnknownChecker.isExactlyType(annotationType)) { throw InvalidGenerationSourceError( '`$jsonKeyNullForUndefinedEnumValueFieldName` cannot be used with ' '`JsonKey.defaultValue`.', element: element, ); } final enumValueNames = enumFields.map((p) => p.name).toList(growable: false); final enumValueName = enumValueForDartObject<String>(objectValue, enumValueNames, (n) => n); return '${annotationType.element!.name}.$enumValueName'; } else { final defaultValueLiteral = literalForObject(fieldName, objectValue, []); if (defaultValueLiteral == null) { return null; } if (mustBeEnum) { throwUnsupported( element, 'The value provided for `$fieldName` must be a matching enum.', ); } return jsonLiteralAsDart(defaultValueLiteral); } } final defaultValue = createAnnotationValue('defaultValue'); if (defaultValue != null && ctorParamDefault != null) { if (defaultValue == ctorParamDefault) { log.info( 'The default value `$defaultValue` for `${element.name}` is defined ' 'twice in the constructor and in the `JsonKey.defaultValue`.', ); } else { log.warning( 'The constructor parameter for `${element.name}` has a default value ' '`$ctorParamDefault`, but the `JsonKey.defaultValue` value ' '`$defaultValue` will be used for missing or `null` values in JSON ' 'decoding.', ); } } String? readValueFunctionName; final readValue = obj.read('readValue'); if (!readValue.isNull) { readValueFunctionName = readValue.objectValue.toFunctionValue()!.qualifiedName; } final ignore = obj.read('ignore').literalValue as bool?; var includeFromJson = obj.read('includeFromJson').literalValue as bool?; var includeToJson = obj.read('includeToJson').literalValue as bool?; if (ignore != null) { if (includeFromJson != null) { throwUnsupported( element, 'Cannot use both `ignore` and `includeFromJson` on the same field. ' 'Since `ignore` is deprecated, you should only use `includeFromJson`.', ); } if (includeToJson != null) { throwUnsupported( element, 'Cannot use both `ignore` and `includeToJson` on the same field. ' 'Since `ignore` is deprecated, you should only use `includeToJson`.', ); } assert(includeFromJson == null && includeToJson == null); includeToJson = includeFromJson = !ignore; } return _populateJsonKey( classAnnotation, element, defaultValue: defaultValue ?? ctorParamDefault, disallowNullValue: obj.read('disallowNullValue').literalValue as bool?, includeIfNull: obj.read('includeIfNull').literalValue as bool?, name: obj.read('name').literalValue as String?, readValueFunctionName: readValueFunctionName, required: obj.read('required').literalValue as bool?, unknownEnumValue: createAnnotationValue('unknownEnumValue', mustBeEnum: true), includeToJson: includeToJson, includeFromJson: includeFromJson, ); } KeyConfig _populateJsonKey( ClassConfig classAnnotation, FieldElement element, { required String? defaultValue, bool? disallowNullValue, bool? includeIfNull, String? name, String? readValueFunctionName, bool? required, String? unknownEnumValue, bool? includeToJson, bool? includeFromJson, }) { if (disallowNullValue == true) { if (includeIfNull == true) { throwUnsupported( element, 'Cannot set both `disallowNullValue` and `includeIfNull` to `true`. ' 'This leads to incompatible `toJson` and `fromJson` behavior.'); } } return KeyConfig( defaultValue: defaultValue, disallowNullValue: disallowNullValue ?? false, includeIfNull: _includeIfNull( includeIfNull, disallowNullValue, classAnnotation.includeIfNull), name: name ?? encodedFieldName(classAnnotation.fieldRename, element.name), readValueFunctionName: readValueFunctionName, required: required ?? false, unknownEnumValue: unknownEnumValue, includeFromJson: includeFromJson, includeToJson: includeToJson, ); } bool _includeIfNull( bool? keyIncludeIfNull, bool? keyDisallowNullValue, bool classIncludeIfNull, ) { if (keyDisallowNullValue == true) { assert(keyIncludeIfNull != true); return false; } return keyIncludeIfNull ?? classIncludeIfNull; } bool _interfaceTypesEqual(DartType a, DartType b) { if (a is InterfaceType && b is InterfaceType) { // Handle nullability case. Pretty sure this is fine for enums. return a.element == b.element; } return a == b; } const jsonKeyNullForUndefinedEnumValueFieldName = 'JsonKey.nullForUndefinedEnumValue'; final _nullAsUnknownChecker = TypeChecker.fromRuntime(JsonKey.nullForUndefinedEnumValue.runtimeType);
json_serializable/json_serializable/lib/src/json_key_utils.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/json_key_utils.dart', 'repo_id': 'json_serializable', 'token_count': 4225}
// 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:analyzer/dart/element/type.dart'; import 'package:source_gen/source_gen.dart' show TypeChecker; import 'package:source_helper/source_helper.dart'; import '../constants.dart'; import '../lambda_result.dart'; import '../shared_checkers.dart'; import '../type_helper.dart'; class IterableHelper extends TypeHelper<TypeHelperContextWithConfig> { const IterableHelper(); @override String? serialize( DartType targetType, String expression, TypeHelperContextWithConfig context, ) { if (!coreIterableTypeChecker.isAssignableFromType(targetType)) { return null; } final itemType = coreIterableGenericType(targetType); // This block will yield a regular list, which works fine for JSON // Although it's possible that child elements may be marked unsafe var isList = _coreListChecker.isAssignableFromType(targetType); final subField = context.serialize(itemType, closureArg)!; var optionalQuestion = targetType.isNullableType ? '?' : ''; // In the case of trivial JSON types (int, String, etc), `subField` // will be identical to `substitute` – so no explicit mapping is needed. // If they are not equal, then we to write out the substitution. if (subField != closureArg) { final lambda = LambdaResult.process(subField); expression = '$expression$optionalQuestion.map($lambda)'; // expression now represents an Iterable (even if it started as a List // ...resetting `isList` to `false`. isList = false; // No need to include the optional question below – it was used here! optionalQuestion = ''; } if (!isList) { // If the static type is not a List, generate one. expression += '$optionalQuestion.toList()'; } return expression; } @override String? deserialize( DartType targetType, String expression, TypeHelperContext context, bool defaultProvided, ) { if (!(coreIterableTypeChecker.isExactlyType(targetType) || _coreListChecker.isExactlyType(targetType) || _coreSetChecker.isExactlyType(targetType))) { return null; } final iterableGenericType = coreIterableGenericType(targetType); final itemSubVal = context.deserialize(iterableGenericType, closureArg)!; var output = '$expression as List<dynamic>'; final targetTypeIsNullable = defaultProvided || targetType.isNullableType; if (targetTypeIsNullable) { output += '?'; } // If `itemSubVal` is the same and it's not a Set, then we don't need to do // anything fancy if (closureArg == itemSubVal && !_coreSetChecker.isExactlyType(targetType)) { return output; } output = '($output)'; var optionalQuestion = targetTypeIsNullable ? '?' : ''; if (closureArg != itemSubVal) { final lambda = LambdaResult.process(itemSubVal); output += '$optionalQuestion.map($lambda)'; // No need to include the optional question below – it was used here! optionalQuestion = ''; } if (_coreListChecker.isExactlyType(targetType)) { output += '$optionalQuestion.toList()'; } else if (_coreSetChecker.isExactlyType(targetType)) { output += '$optionalQuestion.toSet()'; } return output; } } const _coreListChecker = TypeChecker.fromUrl('dart:core#List'); const _coreSetChecker = TypeChecker.fromUrl('dart:core#Set');
json_serializable/json_serializable/lib/src/type_helpers/iterable_helper.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/type_helpers/iterable_helper.dart', 'repo_id': 'json_serializable', 'token_count': 1224}
// 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. // ignore_for_file: annotate_overrides import 'package:json_annotation/json_annotation.dart'; import 'default_value_interface.dart' as dvi hide Greek; import 'default_value_interface.dart' show ConstClass, ConstClassConverter, Greek, constClassFromJson, constClassToJson, intDefaultValueFunction; part 'default_value.g.dart'; const _intValue = 42; dvi.DefaultValue fromJson(Map<String, dynamic> json) => _$DefaultValueFromJson(json); @JsonSerializable() class DefaultValue implements dvi.DefaultValue { @JsonKey(defaultValue: true) bool fieldBool; @JsonKey(defaultValue: 'string', includeIfNull: false) String fieldString; @JsonKey(defaultValue: _intValue) int fieldInt; @JsonKey(defaultValue: 3.14) double fieldDouble; @JsonKey(defaultValue: []) List fieldListEmpty; @JsonKey(defaultValue: <int>{}) Set fieldSetEmpty; @JsonKey(defaultValue: {}) Map fieldMapEmpty; @JsonKey(defaultValue: [1, 2, 3]) List<int> fieldListSimple; @JsonKey(defaultValue: {'entry1', 'entry2'}) Set<String> fieldSetSimple; @JsonKey(defaultValue: {'answer': 42}) Map<String, int> fieldMapSimple; @JsonKey(defaultValue: { 'root': ['child'] }) Map<String, List<String>> fieldMapListString; Duration durationField; @JsonKey(defaultValue: Greek.beta) Greek fieldEnum; ConstClass constClass; @ConstClassConverter() ConstClass valueFromConverter; @JsonKey(fromJson: constClassFromJson, toJson: constClassToJson) ConstClass valueFromFunction; @JsonKey(defaultValue: intDefaultValueFunction) int intDefaultValueFromFunction; @JsonKey(defaultValue: ConstClass.new) ConstClass valueFromDefaultValueDefaultConstructor; @JsonKey(defaultValue: ConstClass.easy) ConstClass valueFromDefaultValueNamedConstructor; DefaultValue( this.fieldBool, this.fieldString, this.fieldInt, this.fieldDouble, this.fieldListEmpty, this.fieldSetEmpty, this.fieldMapEmpty, this.fieldListSimple, this.fieldSetSimple, this.fieldMapSimple, this.fieldMapListString, this.fieldEnum, { this.durationField = Duration.zero, this.constClass = const ConstClass('value'), this.valueFromConverter = const ConstClass('value'), this.valueFromFunction = const ConstClass('value'), required this.intDefaultValueFromFunction, required this.valueFromDefaultValueDefaultConstructor, required this.valueFromDefaultValueNamedConstructor, }); factory DefaultValue.fromJson(Map<String, dynamic> json) => _$DefaultValueFromJson(json); Map<String, dynamic> toJson() => _$DefaultValueToJson(this); }
json_serializable/json_serializable/test/default_value/default_value.dart/0
{'file_path': 'json_serializable/json_serializable/test/default_value/default_value.dart', 'repo_id': 'json_serializable', 'token_count': 1003}
// Copyright (c) 2015, 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:test/test.dart'; import '../test_utils.dart'; import 'json_converters.dart'; import 'kitchen_sink.factories.dart'; import 'kitchen_sink_interface.dart'; import 'kitchen_sink_test_shared.dart'; import 'strict_keys_object.dart'; Matcher _isMissingKeyException(String expectedMessage) => isA<MissingRequiredKeysException>() .having((e) => e.message, 'message', expectedMessage); void main() { test('valid values covers all keys', () { expect(invalidValueTypes.keys, orderedEquals(validValues.keys)); }); test('tracking Map/Iterable types correctly', () { for (var entry in validValues.entries) { if (_iterableMapKeys.contains(entry.key) || _encodedAsMapKeys.contains(entry.key)) { expect(entry.value, anyOf(isMap, isList)); } else { expect(entry.value, isNot(anyOf(isMap, isList))); } } }); test('required keys', () { expect( () => StrictKeysObject.fromJson({}), throwsA(_isMissingKeyException( 'Required keys are missing: value, custom_field.'))); }); for (var factory in factories) { group(factory.description, () { if (factory.nullable) { _nullableTests(factory); } else { _nonNullableTests(factory); } _sharedTests(factory); }); } } const _jsonConverterValidValues = { 'duration': 5, 'durationList': [5], 'bigInt': '5', 'bigIntMap': {'value': '5'}, 'numberSilly': 5, 'numberSillySet': [5], 'dateTime': 5, 'trivialString': '', 'nullableNumberSilly': 5, 'nullableBigInt': '42', 'nullableBigIntMap': {'value': '42'}, 'nullableNumberSillySet': [42], }; void _nonNullableTests(KitchenSinkFactory factory) { test('with empty json fails deserialization', () { Matcher matcher; if (factory.checked) { matcher = checkedMatcher('set'); } else { matcher = isTypeError; } expect(() => factory.fromJson(<String, dynamic>{}), throwsA(matcher)); }); test('nullable values are not allowed in non-nullable version', () { final instance = factory.jsonConverterFromJson(_jsonConverterValidValues); final json = instance.toJson(); expect(json, _jsonConverterValidValues); expect(json.values, everyElement(isNotNull)); final instance2 = factory.jsonConverterFromJson(json); expect(instance2.toJson(), json); }); } void _nullableTests(KitchenSinkFactory factory) { void roundTripSink(KitchenSink p) { roundTripObject(p, factory.fromJson); } test('nullable values are allowed in the nullable version', () { final instance = factory.jsonConverterCtor(); final json = instance.toJson(); expect(json, const { 'duration': 0, 'durationList': <dynamic>[], 'bigInt': '0', 'bigIntMap': <String, dynamic>{}, 'nullableBigInt': '0', 'nullableBigIntMap': <String, dynamic>{}, 'numberSilly': 0, 'numberSillySet': <dynamic>[], 'dateTime': 0, 'trivialString': '', 'nullableNumberSilly': 0, 'nullableNumberSillySet': <dynamic>[], }); expect(json.keys, unorderedEquals(_jsonConverterValidValues.keys)); final instance2 = factory.jsonConverterFromJson(json); expect(instance2.toJson(), json); }); test('Fields with `!includeIfNull` should not be included when null', () { final item = factory.ctor(); final encoded = item.toJson(); if (factory.excludeNull) { expect(encoded.keys, orderedEquals(_nonNullableFields)); } else { expect(encoded.keys, orderedEquals(validValues.keys)); for (final key in validValues.keys) { expect( encoded, containsPair( key, _nonNullableFields.contains(key) ? isNotNull : isNull, ), ); } } }); test('list and map of DateTime', () { final now = DateTime.now(); final later = now.add(const Duration(days: 1)); final item = factory.ctor(dateTimeIterable: <DateTime>[now]) ..dateTimeList = <DateTime>[now, later] ..objectDateTimeMap = <Object, DateTime>{'value': now, 'null': later}; roundTripSink(item); }); test('complex nested type', () { final item = factory.ctor() ..crazyComplex = [ null, {}, { 'null': null, 'empty': {}, 'items': { 'null': null, 'empty': [], 'items': [ null, [], [DateTime.now()] ] } } ]; roundTripSink(item); }); } void _sharedTests(KitchenSinkFactory factory) { test('other names', () { final originalName = factory.fromJson(validValues); final aliasName = factory.fromJson( <String, dynamic>{ ...validValues, 'theIterable': validValues['iterable'], 'STRING': validValues[trickyKeyName] } ..remove('iterable') ..remove(trickyKeyName), ); expect(loudEncode(aliasName), loudEncode(originalName)); }); test('empty', () { final item = factory.ctor(); roundTripObject(item, factory.fromJson); }); test('JsonConverters with nullable JSON keys handle `null` JSON values', () { final item = factory.jsonConverterFromJson({ ..._jsonConverterValidValues, 'nullableNumberSilly': null, }); expect( item.nullableNumberSilly, isA<TrivialNumber>().having((e) => e.value, 'value', isNull), ); }); test('list and map of DateTime - not null', () { final now = DateTime.now(); final item = factory.ctor(dateTimeIterable: <DateTime>[now]) ..dateTimeList = <DateTime>[now, now] ..objectDateTimeMap = <Object, DateTime>{'value': now}; roundTripObject(item, factory.fromJson); }); test('complex nested type - not null', () { final item = factory.ctor() ..crazyComplex = [ {}, { 'empty': {}, 'items': { 'empty': [], 'items': [ [], [DateTime.now()] ] } } ]; roundTripObject(item, factory.fromJson); }); test('round trip valid, empty values', () { final values = Map.fromEntries(validValues.entries.map((e) { var value = e.value; if (_iterableMapKeys.contains(e.key)) { if (value is List) { value = []; } else { assert(value is Map); value = <String, dynamic>{}; } } return MapEntry(e.key, value); })); final validInstance = factory.fromJson(values); roundTripObject(validInstance, factory.fromJson); }); test('JSON keys should be defined in field/property order', () { final json = factory.ctor().toJson(); if (factory.excludeNull) { expect(json.keys, _nonNullableFields); } else { expect(json.keys, orderedEquals(validValues.keys)); } }); test('valid values round-trip - json', () { final validInstance = factory.fromJson(validValues); roundTripObject(validInstance, factory.fromJson); }); } const _nonNullableFields = { 'dynamicIterable', 'objectIterable', 'intIterable', 'set', 'dynamicSet', 'objectSet', 'intSet', 'dateTimeSet', 'datetime-iterable', 'list', 'dynamicList', 'objectList', 'intList', 'dateTimeList', 'nullableSimpleObjectList', 'map', 'stringStringMap', 'dynamicIntMap', 'objectDateTimeMap', 'nullableSimpleObjectMap', 'crazyComplex', 'val', 'simpleObject', 'strictKeysObject' }; const _encodedAsMapKeys = { 'simpleObject', 'strictKeysObject', 'recordField', }; const _iterableMapKeys = { 'bigIntMap', 'crazyComplex', 'datetime-iterable', 'dateTimeList', 'dateTimeSet', 'durationList', 'dynamicIntMap', 'dynamicIterable', 'dynamicList', 'dynamicSet', 'intIterable', 'intList', 'intSet', 'iterable', 'nullableSimpleObjectList', 'list', 'map', 'nullableSimpleObjectMap', 'numberSillySet', 'objectDateTimeMap', 'objectIterable', 'objectList', 'objectSet', 'set', 'stringStringMap', generatedLocalVarName, };
json_serializable/json_serializable/test/kitchen_sink/kitchen_sink_test.dart/0
{'file_path': 'json_serializable/json_serializable/test/kitchen_sink/kitchen_sink_test.dart', 'repo_id': 'json_serializable', 'token_count': 3465}
import 'package:json_annotation/json_annotation.dart'; @JsonSerializable() class ConfigurationImplicitDefaults { ConfigurationImplicitDefaults(); ConfigurationImplicitDefaults.something(); int? field; } // #CHANGE WHEN UPDATING json_annotation @JsonSerializable( anyMap: false, checked: false, constructor: '', createFactory: true, createToJson: true, createFieldMap: false, createPerFieldToJson: false, disallowUnrecognizedKeys: false, explicitToJson: false, fieldRename: FieldRename.none, ignoreUnannotated: false, includeIfNull: true, genericArgumentFactories: false, ) class ConfigurationExplicitDefaults { int? field; } @JsonSerializable(createFactory: false) class IncludeIfNullAll { @JsonKey(includeIfNull: true) int? number; String? str; } @JsonSerializable(createToJson: false) class FromJsonOptionalParameters { final ChildWithFromJson child; FromJsonOptionalParameters(this.child); } class ChildWithFromJson { //ignore: avoid_unused_constructor_parameters ChildWithFromJson.fromJson(json, {initValue = false}); } @JsonSerializable() class ParentObject { int? number; String? str; ChildObject? child; } @JsonSerializable() class ChildObject { int? number; String? str; } @JsonSerializable() class ParentObjectWithChildren { int? number; String? str; List<ChildObject>? children; } @JsonSerializable() class ParentObjectWithDynamicChildren { int? number; String? str; late List<dynamic> children; } @JsonSerializable(createFactory: false, explicitToJson: true) class TrivialNestedNullable { TrivialNestedNullable? child; int? otherField; } @JsonSerializable(createFactory: false, explicitToJson: true) class TrivialNestedNonNullable { late TrivialNestedNonNullable child; int? otherField; }
json_serializable/json_serializable/test/test_sources/test_sources.dart/0
{'file_path': 'json_serializable/json_serializable/test/test_sources/test_sources.dart', 'repo_id': 'json_serializable', 'token_count': 596}
import 'dart:math'; import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/extensions.dart'; import 'package:flame/geometry.dart'; import 'package:flutter/animation.dart'; import 'package:lightrunners/game/game.dart'; enum PowerUpType { speed('invertase.png'), shots('flame.png'), drag('melos.png'), weight('widgetbook.png'); const PowerUpType(this.asset); final String asset; } class PowerUp extends SpriteComponent with HasGameReference<LightRunnersGame>, CollisionCallbacks { PowerUp() : type = (PowerUpType.values.toList()..shuffle(_random)).first, super(anchor: Anchor.center); static final Random _random = Random(); final PowerUpType type; @override Future<void> onLoad() async { super.onLoad(); sprite = await game.loadSprite('powerups/${type.asset}'); final sizeRelation = sprite!.image.height / sprite!.image.width; final width = 50 + 50 * _random.nextDouble(); size = Vector2(width, sizeRelation * width); position = Vector2.random(_random) ..multiply(game.playArea.deflate(width * 2).toVector2() / 2) ..multiply( Vector2(_random.nextBool() ? 1 : -1, _random.nextBool() ? 1 : -1), ); add(CircleHitbox()..collisionType = CollisionType.passive); add( ScaleEffect.by( Vector2.all(1.3), EffectController(duration: 1.0, alternate: true, infinite: true), ), ); } @override void onCollisionStart( Set<Vector2> intersectionPoints, PositionComponent other, ) { super.onCollisionStart(intersectionPoints, other); if (other is Ship) { removeAll(children); affectShip(other); addAll( [ ScaleEffect.to(Vector2.all(0), EffectController(duration: 1.0)), RotateEffect.by( tau * 3, EffectController(duration: 1.0, curve: Curves.elasticIn), onComplete: removeFromParent, ), ], ); } } void affectShip(Ship ship) { switch (type) { case PowerUpType.shots: ship.bulletSpeed *= 2; case PowerUpType.speed: ship.engineStrength *= 2; case PowerUpType.weight: ship.weightFactor *= 1.5; ship.size.scale(1.5); case PowerUpType.drag: ship.dragFactor *= 0.7; } } }
lightrunners/lib/game/components/powerup.dart/0
{'file_path': 'lightrunners/lib/game/components/powerup.dart', 'repo_id': 'lightrunners', 'token_count': 980}
export 'crt.dart';
lightrunners/lib/shaders/shaders.dart/0
{'file_path': 'lightrunners/lib/shaders/shaders.dart', 'repo_id': 'lightrunners', 'token_count': 9}
import 'package:flutter/widgets.dart'; import 'package:phased/phased.dart'; class OpacityBlinker extends StatelessWidget { const OpacityBlinker({ required this.child, super.key, }); final Widget child; @override Widget build(BuildContext context) { return _OpacityBlinkerPhased(state: _State(), child: child); } } class _State extends PhasedState<bool> { _State() : super( values: [true, false], initialValue: true, ticker: const Duration(milliseconds: 600), ); } class _OpacityBlinkerPhased extends Phased<bool> { const _OpacityBlinkerPhased({ required super.state, required this.child, }); final Widget child; @override Widget build(BuildContext context) { return Opacity( opacity: state.value ? 1 : 0.4, child: child, ); } }
lightrunners/lib/widgets/opacity_blinker.dart/0
{'file_path': 'lightrunners/lib/widgets/opacity_blinker.dart', 'repo_id': 'lightrunners', 'token_count': 328}
// Copyright (c) 2015, 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. /// Common AST helpers. import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/visitor.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/workspace/workspace.dart'; // ignore: implementation_imports import 'package:path/path.dart' as path; import 'analyzer.dart'; import 'utils.dart'; /// Returns direct children of [parent]. List<Element> getChildren(Element parent, [String? name]) { var children = <Element>[]; visitChildren(parent, (Element element) { if (name == null || element.displayName == name) { children.add(element); } return false; }); return children; } /// Return the compilation unit of a node CompilationUnit? getCompilationUnit(AstNode node) => node.thisOrAncestorOfType<CompilationUnit>(); /// Returns a field identifier with the given [name] in the given [decl]'s /// variable declaration list or `null` if none is found. SimpleIdentifier? getFieldIdentifier(FieldDeclaration decl, String name) { for (var v in decl.fields.variables) { if (v.name.name == name) { return v.name; } } return null; } /// Returns the most specific AST node appropriate for associating errors. AstNode getNodeToAnnotate(Declaration node) { var mostSpecific = _getNodeToAnnotate(node); return mostSpecific ?? node; } /// If the [node] is the finishing identifier of an assignment, return its /// "writeElement", otherwise return its "staticElement", which might be /// thought as the "readElement". Element? getWriteOrReadElement(SimpleIdentifier node) { var writeElement = _getWriteElement(node); if (writeElement != null) { return writeElement; } return node.staticElement; } bool hasConstantError(LinterContext context, Expression node) { var result = context.evaluateConstant(node); return result.errors.isNotEmpty; } /// Returns `true` if this [element] has a `@literal` annotation. bool hasLiteralAnnotation(Element element) { var metadata = element.metadata; for (var i = 0; i < metadata.length; i++) { if (metadata[i].isLiteral) { return true; } } return false; } /// Returns `true` if this [element] has an `@override` annotation. bool hasOverrideAnnotation(Element element) { var metadata = element.metadata; for (var i = 0; i < metadata.length; i++) { if (metadata[i].isOverride) { return true; } } return false; } /// Returns `true` if this [node] is the child of a private compilation unit /// member. bool inPrivateMember(AstNode node) { var parent = node.parent; if (parent is NamedCompilationUnitMember) { return isPrivate(parent.name); } if (parent is ExtensionDeclaration) { return parent.name == null || isPrivate(parent.name); } return false; } /// Returns `true` if the given [declaration] is annotated `@deprecated`. bool isDeprecated(Declaration declaration) { var declaredElement = declaration.declaredElement; return declaredElement != null && declaredElement.hasDeprecated; } /// Returns `true` if this element is the `==` method declaration. bool isEquals(ClassMember element) => element is MethodDeclaration && element.name.name == '=='; /// Returns `true` if the keyword associated with this token is `final` or /// `const`. bool isFinalOrConst(Token token) => isKeyword(token, Keyword.FINAL) || isKeyword(token, Keyword.CONST); /// Returns `true` if this element is a `hashCode` method or field declaration. bool isHashCode(ClassMember element) => (element is MethodDeclaration && element.name.name == 'hashCode') || (element is FieldDeclaration && getFieldIdentifier(element, 'hashCode') != null); /// Return true if this compilation unit [node] is declared within the given /// [package]'s `lib/` directory tree. bool isInLibDir(CompilationUnit node, WorkspacePackage? package) { if (package == null) return false; var cuPath = node.declaredElement?.library.source.fullName; if (cuPath == null) return false; var libDir = path.join(package.root, 'lib'); return path.isWithin(libDir, cuPath); } /// Returns `true` if the keyword associated with the given [token] matches /// [keyword]. bool isKeyword(Token token, Keyword keyword) => token is KeywordToken && token.keyword == keyword; /// Returns `true` if the given [id] is a Dart keyword. bool isKeyWord(String id) => Keyword.keywords.keys.contains(id); /// Returns `true` if the given [ClassMember] is a method. bool isMethod(ClassMember m) => m is MethodDeclaration; /// Check if the given identifier has a private name. bool isPrivate(SimpleIdentifier? identifier) => identifier != null ? Identifier.isPrivateName(identifier.name) : false; /// Returns `true` if the given [declaration] is annotated `@protected`. bool isProtected(Declaration declaration) => declaration.metadata.any((Annotation a) => a.name.name == 'protected'); /// Returns `true` if the given [ClassMember] is a public method. bool isPublicMethod(ClassMember m) { var declaredElement = m.declaredElement; return declaredElement != null && isMethod(m) && declaredElement.isPublic; } /// Returns `true` if the given method [declaration] is a "simple getter". /// /// A simple getter takes one of these basic forms: /// /// get x => _simpleIdentifier; /// or /// get x { /// return _simpleIdentifier; /// } bool isSimpleGetter(MethodDeclaration declaration) { if (!declaration.isGetter) { return false; } var body = declaration.body; if (body is ExpressionFunctionBody) { return _checkForSimpleGetter(declaration, body.expression); } else if (body is BlockFunctionBody) { var block = body.block; if (block.statements.length == 1) { var statement = block.statements[0]; if (statement is ReturnStatement) { return _checkForSimpleGetter(declaration, statement.expression); } } } return false; } /// Returns `true` if the given [setter] is a "simple setter". /// /// A simple setter takes this basic form: /// /// var _x; /// set(x) { /// _x = x; /// } /// /// or: /// /// set(x) => _x = x; /// /// where the static type of the left and right hand sides must be the same. bool isSimpleSetter(MethodDeclaration setter) { var body = setter.body; if (body is ExpressionFunctionBody) { return _checkForSimpleSetter(setter, body.expression); } else if (body is BlockFunctionBody) { var block = body.block; if (block.statements.length == 1) { var statement = block.statements[0]; if (statement is ExpressionStatement) { return _checkForSimpleSetter(setter, statement.expression); } } } return false; } /// Returns `true` if the given [id] is a valid Dart identifier. bool isValidDartIdentifier(String id) => !isKeyWord(id) && isIdentifier(id); /// Returns `true` if the keyword associated with this token is `var`. bool isVar(Token token) => isKeyword(token, Keyword.VAR); /// Return the nearest enclosing pubspec file. File? locatePubspecFile(CompilationUnit compilationUnit) { var fullName = compilationUnit.declaredElement?.source.fullName; if (fullName == null) { return null; } var resourceProvider = compilationUnit.declaredElement?.session.resourceProvider; if (resourceProvider == null) { return null; } var file = resourceProvider.getFile(fullName); // Look for a pubspec.yaml file. for (var folder in file.parent2.withAncestors) { var pubspecFile = folder.getChildAssumingFile('pubspec.yaml'); if (pubspecFile.exists) { return pubspecFile; } } return null; } /// Uses [processor] to visit all of the children of [element]. /// If [processor] returns `true`, then children of a child are visited too. void visitChildren(Element element, ElementProcessor processor) { element.visitChildren(_ElementVisitorAdapter(processor)); } bool _checkForSimpleGetter(MethodDeclaration getter, Expression? expression) { if (expression is SimpleIdentifier) { var staticElement = expression.staticElement; if (staticElement is PropertyAccessorElement) { var enclosingElement = getter.declaredElement?.enclosingElement; // Skipping library level getters, test that the enclosing element is // the same if (staticElement.enclosingElement == enclosingElement) { return staticElement.isSynthetic && staticElement.variable.isPrivate; } } } return false; } bool _checkForSimpleSetter(MethodDeclaration setter, Expression expression) { if (expression is! AssignmentExpression) { return false; } var assignment = expression; var leftHandSide = assignment.leftHandSide; var rightHandSide = assignment.rightHandSide; if (leftHandSide is SimpleIdentifier && rightHandSide is SimpleIdentifier) { var leftElement = assignment.writeElement; if (leftElement is! PropertyAccessorElement || !leftElement.isSynthetic) { return false; } // To guard against setters used as type constraints if (assignment.writeType != rightHandSide.staticType) { return false; } var rightElement = rightHandSide.staticElement; if (rightElement is! ParameterElement) { return false; } var parameters = setter.parameters?.parameters; if (parameters != null && parameters.length == 1) { return rightElement == parameters[0].declaredElement; } } return false; } AstNode? _getNodeToAnnotate(Declaration node) { if (node is MethodDeclaration) { return node.name; } if (node is ConstructorDeclaration) { return node.name; } if (node is FieldDeclaration) { return node.fields; } if (node is ClassTypeAlias) { return node.name; } if (node is FunctionTypeAlias) { return node.name; } if (node is ClassDeclaration) { return node.name; } if (node is EnumDeclaration) { return node.name; } if (node is FunctionDeclaration) { return node.name; } if (node is TopLevelVariableDeclaration) { return node.variables; } if (node is EnumConstantDeclaration) { return node.name; } if (node is TypeParameter) { return node.name; } if (node is VariableDeclaration) { return node.name; } return null; } /// If the [node] is the target of a [CompoundAssignmentExpression], /// return the corresponding "writeElement", which is the local variable, /// the setter referenced with a [SimpleIdentifier] or a [PropertyAccess], /// or the `[]=` operator. Element? _getWriteElement(AstNode node) { var parent = node.parent; if (parent is AssignmentExpression && parent.leftHandSide == node) { return parent.writeElement; } if (parent is PostfixExpression) { return parent.writeElement; } if (parent is PrefixExpression) { return parent.writeElement; } if (parent is PrefixedIdentifier && parent.identifier == node) { return _getWriteElement(parent); } if (parent is PropertyAccess && parent.propertyName == node) { return _getWriteElement(parent); } return null; } /// An [Element] processor function type. /// If `true` is returned, children of [element] will be visited. typedef ElementProcessor = bool Function(Element element); /// A [GeneralizingElementVisitor] adapter for [ElementProcessor]. class _ElementVisitorAdapter extends GeneralizingElementVisitor { final ElementProcessor processor; _ElementVisitorAdapter(this.processor); @override void visitElement(Element element) { var visitChildren = processor(element); if (visitChildren == true) { element.visitChildren(this); } } }
linter/lib/src/ast.dart/0
{'file_path': 'linter/lib/src/ast.dart', 'repo_id': 'linter', 'token_count': 3793}
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; const _desc = r'Avoid defining a class that contains only static members.'; const _details = r''' **AVOID** defining a class that contains only static members. Creating classes with the sole purpose of providing utility or otherwise static methods is discouraged. Dart allows functions to exist outside of classes for this very reason. **BAD:** ```dart class DateUtils { static DateTime mostRecent(List<DateTime> dates) { return dates.reduce((a, b) => a.isAfter(b) ? a : b); } } class _Favorites { static const mammal = 'weasel'; } ``` **GOOD:** ```dart DateTime mostRecent(List<DateTime> dates) { return dates.reduce((a, b) => a.isAfter(b) ? a : b); } const _favoriteMammal = 'weasel'; ``` '''; bool _isNonConst(FieldElement element) => !element.isConst; bool _isStaticMember(ClassMember classMember) { if (classMember is MethodDeclaration) { return classMember.isStatic; } if (classMember is FieldDeclaration) { return classMember.isStatic; } return false; } class AvoidClassesWithOnlyStaticMembers extends LintRule implements NodeLintRule { AvoidClassesWithOnlyStaticMembers() : super( name: 'avoid_classes_with_only_static_members', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitClassDeclaration(ClassDeclaration node) { var declaredElement = node.declaredElement; if (declaredElement != null && node.members.isNotEmpty && node.members.every(_isStaticMember) && declaredElement.fields.any(_isNonConst)) { rule.reportLint(node); } } }
linter/lib/src/rules/avoid_classes_with_only_static_members.dart/0
{'file_path': 'linter/lib/src/rules/avoid_classes_with_only_static_members.dart', 'repo_id': 'linter', 'token_count': 798}
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Avoid redundant argument values.'; const _details = r'''Avoid redundant argument values. **DON'T** declare arguments with values that match the defaults for the corresponding parameter. **BAD:** ```dart void f({bool valWithDefault = true, bool val}) { ... } void main() { f(valWithDefault: true); } ``` **GOOD:** ```dart void f({bool valWithDefault = true, bool val}) { ... } void main() { f(valWithDefault: false); f(); } ``` '''; class AvoidRedundantArgumentValues extends LintRule implements NodeLintRule { AvoidRedundantArgumentValues() : super( name: 'avoid_redundant_argument_values', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this, context); registry.addInstanceCreationExpression(this, visitor); registry.addMethodInvocation(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; final LinterContext context; _Visitor(this.rule, this.context); void check(ArgumentList argumentList) { var arguments = argumentList.arguments; if (arguments.isEmpty) { return; } for (var i = arguments.length - 1; i >= 0; --i) { var arg = arguments[i]; var param = arg.staticParameterElement; if (param == null || param.hasRequired || param.isRequiredNamed) { continue; } else if (param.isRequiredPositional) { break; } var value = param.computeConstantValue(); if (value != null) { if (arg is NamedExpression) { arg = arg.expression; } var expressionValue = context.evaluateConstant(arg); if (expressionValue.value == value) { rule.reportLint(arg); } } if (param.isOptionalPositional) { break; } } } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { check(node.argumentList); } @override void visitMethodInvocation(MethodInvocation node) { check(node.argumentList); } }
linter/lib/src/rules/avoid_redundant_argument_values.dart/0
{'file_path': 'linter/lib/src/rules/avoid_redundant_argument_values.dart', 'repo_id': 'linter', 'token_count': 938}
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; import '../utils.dart'; const _desc = r'Avoid defining unused parameters in constructors.'; const _details = r''' **AVOID** defining unused parameters in constructors. **BAD:** ```dart class BadOne { BadOne(int unusedParameter, [String unusedPositional]); } class BadTwo { int c; BadTwo(int a, int b, int x) { c = a + b; } } ``` '''; class AvoidUnusedConstructorParameters extends LintRule implements NodeLintRule { AvoidUnusedConstructorParameters() : super( name: 'avoid_unused_constructor_parameters', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); } } class _ConstructorVisitor extends RecursiveAstVisitor { final LintRule rule; final ConstructorDeclaration element; final Set<FormalParameter> unusedParameters; _ConstructorVisitor(this.rule, this.element) : unusedParameters = element.parameters.parameters.where((p) { var element = p.declaredElement; return element != null && element is! FieldFormalParameterElement && !element.hasDeprecated && !isJustUnderscores(element.name); }).toSet(); @override void visitSimpleIdentifier(SimpleIdentifier node) { unusedParameters .removeWhere((p) => node.staticElement == p.declaredElement); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitConstructorDeclaration(ConstructorDeclaration node) { if (node.redirectedConstructor != null) return; if (node.externalKeyword != null) return; var _constructorVisitor = _ConstructorVisitor(rule, node); node.body.visitChildren(_constructorVisitor); node.initializers.forEach((i) => i.visitChildren(_constructorVisitor)); _constructorVisitor.unusedParameters.forEach(rule.reportLint); } }
linter/lib/src/rules/avoid_unused_constructor_parameters.dart/0
{'file_path': 'linter/lib/src/rules/avoid_unused_constructor_parameters.dart', 'repo_id': 'linter', 'token_count': 873}
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Adhere to Effective Dart Guide directives sorting conventions.'; const _details = r''' **DO** follow the conventions in the [Effective Dart Guide](https://dart.dev/guides/language/effective-dart/style#ordering) **DO** place “dart:” imports before other imports. **BAD:** ```dart import 'package:bar/bar.dart'; import 'package:foo/foo.dart'; import 'dart:async'; // LINT import 'dart:html'; // LINT ``` **BAD:** ```dart import 'dart:html'; // OK import 'package:bar/bar.dart'; import 'dart:async'; // LINT import 'package:foo/foo.dart'; ``` **GOOD:** ```dart import 'dart:async'; // OK import 'dart:html'; // OK import 'package:bar/bar.dart'; import 'package:foo/foo.dart'; ``` **DO** place “package:” imports before relative imports. **BAD:** ```dart import 'a.dart'; import 'b.dart'; import 'package:bar/bar.dart'; // LINT import 'package:foo/foo.dart'; // LINT ``` **BAD:** ```dart import 'package:bar/bar.dart'; // OK import 'a.dart'; import 'package:foo/foo.dart'; // LINT import 'b.dart'; ``` **GOOD:** ```dart import 'package:bar/bar.dart'; // OK import 'package:foo/foo.dart'; // OK import 'a.dart'; import 'b.dart'; ``` **DO** specify exports in a separate section after all imports. **BAD:** ```dart import 'src/error.dart'; export 'src/error.dart'; // LINT import 'src/string_source.dart'; ``` **GOOD:** ```dart import 'src/error.dart'; import 'src/string_source.dart'; export 'src/error.dart'; // OK ``` **DO** sort sections alphabetically. **BAD:** ```dart import 'package:foo/bar.dart'; // OK import 'package:bar/bar.dart'; // LINT import 'a/b.dart'; // OK import 'a.dart'; // LINT ``` **GOOD:** ```dart import 'package:bar/bar.dart'; // OK import 'package:foo/bar.dart'; // OK import 'a.dart'; // OK import 'a/b.dart'; // OK '''; const _directiveSectionOrderedAlphabetically = 'Sort directive sections alphabetically.'; const _exportDirectiveAfterImportDirectives = 'Specify exports in a separate section after all imports.'; const _exportKeyword = 'export'; const _importKeyword = 'import'; String _dartDirectiveGoFirst(String type) => "Place 'dart:' ${type}s before other ${type}s."; bool _isAbsoluteDirective(NamespaceDirective node) { var uriContent = node.uriContent; return uriContent != null && uriContent.contains(':'); } bool _isDartDirective(NamespaceDirective node) { var uriContent = node.uriContent; return uriContent != null && uriContent.startsWith('dart:'); } bool _isExportDirective(Directive node) => node is ExportDirective; bool _isNotDartDirective(NamespaceDirective node) => !_isDartDirective(node); bool _isPackageDirective(NamespaceDirective node) { var uriContent = node.uriContent; return uriContent != null && uriContent.startsWith('package:'); } bool _isPartDirective(Directive node) => node is PartDirective; bool _isRelativeDirective(NamespaceDirective node) => !_isAbsoluteDirective(node); String _packageDirectiveBeforeRelative(String type) => "Place 'package:' ${type}s before relative ${type}s."; class DirectivesOrdering extends LintRule implements ProjectVisitor, NodeLintRule { DartProject? project; DirectivesOrdering() : super( name: 'directives_ordering', description: _desc, details: _details, group: Group.style); @override ProjectVisitor getProjectVisitor() => this; @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } @override void visit(DartProject project) { this.project = project; } void _reportLintWithDartDirectiveGoFirstMessage(AstNode node, String type) { _reportLintWithDescription(node, _dartDirectiveGoFirst(type)); } void _reportLintWithDescription(AstNode node, String description) { reporter.reportErrorForNode(LintCode(name, description), node, []); } void _reportLintWithDirectiveSectionOrderedAlphabeticallyMessage( AstNode node) { _reportLintWithDescription(node, _directiveSectionOrderedAlphabetically); } void _reportLintWithExportDirectiveAfterImportDirectiveMessage(AstNode node) { _reportLintWithDescription(node, _exportDirectiveAfterImportDirectives); } void _reportLintWithPackageDirectiveBeforeRelativeMessage( AstNode node, String type) { _reportLintWithDescription(node, _packageDirectiveBeforeRelative(type)); } } class _PackageBox { final String _packageName; _PackageBox(this._packageName); bool _isNotOwnPackageDirective(NamespaceDirective node) => _isPackageDirective(node) && !_isOwnPackageDirective(node); bool _isOwnPackageDirective(NamespaceDirective node) { var uriContent = node.uriContent; return uriContent != null && uriContent.startsWith('package:$_packageName/'); } } class _Visitor extends SimpleAstVisitor<void> { final DirectivesOrdering rule; _Visitor(this.rule); DartProject? get project => rule.project; @override void visitCompilationUnit(CompilationUnit node) { var lintedNodes = <AstNode>{}; _checkDartDirectiveGoFirst(lintedNodes, node); _checkPackageDirectiveBeforeRelative(lintedNodes, node); _checkExportDirectiveAfterImportDirective(lintedNodes, node); _checkDirectiveSectionOrderedAlphabetically(lintedNodes, node); } void _checkDartDirectiveGoFirst( Set<AstNode> lintedNodes, CompilationUnit node) { void reportImport(NamespaceDirective directive) { if (lintedNodes.add(directive)) { rule._reportLintWithDartDirectiveGoFirstMessage( directive, _importKeyword); } } void reportExport(NamespaceDirective directive) { if (lintedNodes.add(directive)) { rule._reportLintWithDartDirectiveGoFirstMessage( directive, _exportKeyword); } } Iterable<NamespaceDirective> getNodesToLint( Iterable<NamespaceDirective> directives) => directives.skipWhile(_isDartDirective).where(_isDartDirective); getNodesToLint(_getImportDirectives(node)).forEach(reportImport); getNodesToLint(_getExportDirectives(node)).forEach(reportExport); } void _checkDirectiveSectionOrderedAlphabetically( Set<AstNode> lintedNodes, CompilationUnit node) { var importDirectives = _getImportDirectives(node); var exportDirectives = _getExportDirectives(node); var dartImports = importDirectives.where(_isDartDirective); var dartExports = exportDirectives.where(_isDartDirective); var relativeImports = importDirectives.where(_isRelativeDirective); var relativeExports = exportDirectives.where(_isRelativeDirective); _checkSectionInOrder(lintedNodes, dartImports); _checkSectionInOrder(lintedNodes, dartExports); _checkSectionInOrder(lintedNodes, relativeImports); _checkSectionInOrder(lintedNodes, relativeExports); var projectName = project?.name; if (projectName != null) { var packageBox = _PackageBox(projectName); var thirdPartyPackageImports = importDirectives.where(packageBox._isNotOwnPackageDirective); var thirdPartyPackageExports = exportDirectives.where(packageBox._isNotOwnPackageDirective); var ownPackageImports = importDirectives.where(packageBox._isOwnPackageDirective); var ownPackageExports = exportDirectives.where(packageBox._isOwnPackageDirective); _checkSectionInOrder(lintedNodes, thirdPartyPackageImports); _checkSectionInOrder(lintedNodes, thirdPartyPackageExports); _checkSectionInOrder(lintedNodes, ownPackageImports); _checkSectionInOrder(lintedNodes, ownPackageExports); } } void _checkExportDirectiveAfterImportDirective( Set<AstNode> lintedNodes, CompilationUnit node) { void reportDirective(Directive directive) { if (lintedNodes.add(directive)) { rule._reportLintWithExportDirectiveAfterImportDirectiveMessage( directive); } } node.directives.reversed .skipWhile(_isPartDirective) .skipWhile(_isExportDirective) .where(_isExportDirective) .forEach(reportDirective); } void _checkPackageDirectiveBeforeRelative( Set<AstNode> lintedNodes, CompilationUnit node) { void reportImport(NamespaceDirective directive) { if (lintedNodes.add(directive)) { rule._reportLintWithPackageDirectiveBeforeRelativeMessage( directive, _importKeyword); } } void reportExport(NamespaceDirective directive) { if (lintedNodes.add(directive)) { rule._reportLintWithPackageDirectiveBeforeRelativeMessage( directive, _exportKeyword); } } Iterable<NamespaceDirective> getNodesToLint( Iterable<NamespaceDirective> directives) => directives .where(_isNotDartDirective) .skipWhile(_isAbsoluteDirective) .where(_isPackageDirective); getNodesToLint(_getImportDirectives(node)).forEach(reportImport); getNodesToLint(_getExportDirectives(node)).forEach(reportExport); } void _checkSectionInOrder( Set<AstNode> lintedNodes, Iterable<NamespaceDirective> nodes) { void reportDirective(NamespaceDirective directive) { if (lintedNodes.add(directive)) { rule._reportLintWithDirectiveSectionOrderedAlphabeticallyMessage( directive); } } NamespaceDirective? previousDirective; for (var directive in nodes) { if (previousDirective != null) { var previousUri = previousDirective.uriContent; var directiveUri = directive.uriContent; if (previousUri != null && directiveUri != null && previousUri.compareTo(directiveUri) > 0) { reportDirective(directive); } } previousDirective = directive; } } Iterable<ExportDirective> _getExportDirectives(CompilationUnit node) => node.directives.whereType<ExportDirective>(); Iterable<ImportDirective> _getImportDirectives(CompilationUnit node) => node.directives.whereType<ImportDirective>(); }
linter/lib/src/rules/directives_ordering.dart/0
{'file_path': 'linter/lib/src/rules/directives_ordering.dart', 'repo_id': 'linter', 'token_count': 3878}
// Copyright (c) 2021, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; const _desc = r'Avoid using private types in public APIs.'; const _details = r''' **AVOID** using library private types in public APIs. For the purposes of this lint, a public API is considered to be any top-level or member declaration unless the declaration is library private or contained in a declarartion that's library private. The following uses of types are checked: - the return type of a function or method, - the type of any parameter of a function or method, - the bound of a type parameter to any function, method, class, mixin, extension's extended type, or type alias, - the type of any top level variable or field, - any type used in the declaration of a type alias (for example `typedef F = _Private Function();`), or - any type used in the `on` clause of an extension or a mixin **GOOD:** ``` f(String s) { ... } ``` **BAD:** ``` f(_Private p) { ... } class _Private {} ``` '''; class LibraryPrivateTypesInPublicAPI extends LintRule implements NodeLintRule { LibraryPrivateTypesInPublicAPI() : super( name: 'library_private_types_in_public_api', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = Visitor(this); registry.addCompilationUnit(this, visitor); } } class Validator extends SimpleAstVisitor<void> { LintRule rule; Validator(this.rule); @override void visitClassDeclaration(ClassDeclaration node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.typeParameters?.accept(this); node.members.accept(this); } @override void visitClassTypeAlias(ClassTypeAlias node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.superclass.accept(this); node.typeParameters?.accept(this); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { var name = node.name; if (name != null && Identifier.isPrivateName(name.name)) { return; } node.parameters.accept(this); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { node.parameter.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { var name = node.name; if (name == null || Identifier.isPrivateName(name.name)) { return; } node.extendedType.accept(this); node.typeParameters?.accept(this); node.members.accept(this); } @override void visitFieldDeclaration(FieldDeclaration node) { if (node.fields.variables .any((field) => !Identifier.isPrivateName(field.name.name))) { node.fields.type?.accept(this); } } @override void visitFieldFormalParameter(FieldFormalParameter node) { if (node.isNamed && Identifier.isPrivateName(node.identifier.name)) { return; } node.type?.accept(this); } @override void visitFormalParameterList(FormalParameterList node) { node.parameters.accept(this); } @override void visitFunctionDeclaration(FunctionDeclaration node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.returnType?.accept(this); node.functionExpression.typeParameters?.accept(this); node.functionExpression.parameters?.accept(this); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { if (node.isNamed && Identifier.isPrivateName(node.identifier.name)) { return; } node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericFunctionType(GenericFunctionType node) { node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericTypeAlias(GenericTypeAlias node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.typeParameters?.accept(this); node.functionType?.accept(this); } @override void visitMethodDeclaration(MethodDeclaration node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitMixinDeclaration(MixinDeclaration node) { if (Identifier.isPrivateName(node.name.name)) { return; } node.onClause?.superclassConstraints.accept(this); node.typeParameters?.accept(this); node.members.accept(this); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { var name = node.identifier; if (name != null && node.isNamed && Identifier.isPrivateName(name.name)) { return; } node.type?.accept(this); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { if (node.variables.variables .any((field) => !Identifier.isPrivateName(field.name.name))) { node.variables.type?.accept(this); } } @override void visitTypeArgumentList(TypeArgumentList node) { node.arguments.accept(this); } @override void visitTypeName(TypeName node) { var element = node.name.staticElement; if (element != null && isPrivate(element)) { rule.reportLint(node.name); } node.typeArguments?.accept(this); } @override void visitTypeParameter(TypeParameter node) { node.bound?.accept(this); } @override void visitTypeParameterList(TypeParameterList node) { node.typeParameters.accept(this); } /// Return `true` if the given [element] is private or is defined in a private /// library. static bool isPrivate(Element element) { var name = element.name; return name != null && Identifier.isPrivateName(name); } } class Visitor extends SimpleAstVisitor { LintRule rule; Visitor(this.rule); @override void visitCompilationUnit(CompilationUnit node) { var element = node.declaredElement; if (element != null && !Validator.isPrivate(element)) { var validator = Validator(rule); node.declarations.accept(validator); } } }
linter/lib/src/rules/library_private_types_in_public_api.dart/0
{'file_path': 'linter/lib/src/rules/library_private_types_in_public_api.dart', 'repo_id': 'linter', 'token_count': 2405}
// Copyright (c) 2016, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:collection/collection.dart' show IterableExtension; import '../analyzer.dart'; const _desc = r"Don't override fields."; const _details = r''' **DON'T** override fields. Overriding fields is almost always done unintentionally. Regardless, it is a bad practice to do so. **BAD:** ```dart class Base { Object field = 'lorem'; Object something = 'change'; } class Bad1 extends Base { @override final field = 'ipsum'; // LINT } class Bad2 extends Base { @override Object something = 'done'; // LINT } ``` **GOOD:** ```dart class Base { Object field = 'lorem'; Object something = 'change'; } class Ok extends Base { Object newField; // OK final Object newFinal = 'ignore'; // OK } ``` **GOOD:** ```dart abstract class BaseLoggingHandler { Base transformer; } class LogPrintHandler implements BaseLoggingHandler { @override Derived transformer; // OK } ``` '''; Iterable<InterfaceType> _findAllSupertypesAndMixins( InterfaceType? interface, List<InterfaceType> accumulator) { if (interface == null || interface.isDartCoreObject || accumulator.contains(interface)) { return accumulator; } accumulator.add(interface); var superclass = interface.superclass; var interfaces = <InterfaceType>[]; if (superclass != null) { interfaces.add(superclass); } interfaces ..addAll(interface.element.mixins) ..addAll(_findAllSupertypesAndMixins(superclass, accumulator)); return interfaces.where((i) => i != interface); } Iterable<InterfaceType> _findAllSupertypesInMixin(ClassElement classElement) { var supertypes = <InterfaceType>[]; var accumulator = <InterfaceType>[]; for (var type in classElement.superclassConstraints) { supertypes.add(type); supertypes.addAll(_findAllSupertypesAndMixins(type, accumulator)); } return supertypes; } class OverriddenFields extends LintRule implements NodeLintRule { OverriddenFields() : super( name: 'overridden_fields', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitFieldDeclaration(FieldDeclaration node) { if (node.isStatic) { return; } node.fields.variables.forEach((VariableDeclaration variable) { var declaredElement = variable.declaredElement; if (declaredElement != null) { var field = _getOverriddenMember(declaredElement); if (field != null && !field.isAbstract) { rule.reportLint(variable.name); } } }); } PropertyAccessorElement? _getOverriddenMember(Element member) { var memberName = member.name; var library = member.library; bool isOverriddenMember(PropertyAccessorElement a) { if (memberName != null && a.isSynthetic && a.name == memberName) { // Ensure that private members are overriding a member of the same library. if (Identifier.isPrivateName(memberName)) { return library == a.library; } return true; } return false; } bool containsOverriddenMember(InterfaceType i) => i.accessors.any(isOverriddenMember); var enclosingElement = member.enclosingElement; if (enclosingElement is! ClassElement) { return null; } var classElement = enclosingElement; Iterable<InterfaceType> interfaces; if (classElement.isMixin) { interfaces = _findAllSupertypesInMixin(classElement); } else { interfaces = _findAllSupertypesAndMixins(classElement.thisType, <InterfaceType>[]); } var interface = interfaces.firstWhereOrNull(containsOverriddenMember); return interface?.accessors.firstWhere(isOverriddenMember); } }
linter/lib/src/rules/overridden_fields.dart/0
{'file_path': 'linter/lib/src/rules/overridden_fields.dart', 'repo_id': 'linter', 'token_count': 1545}
// Copyright (c) 2019, 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 '../analyzer.dart'; import '../rules/prefer_single_quotes.dart'; const _desc = r"Prefer double quotes where they won't require escape sequences."; const _details = ''' **DO** use double quotes where they wouldn't require additional escapes. That means strings with a double quote may use apostrophes so that the double quote isn't escaped (note: we don't lint the other way around, ie, a double quoted string with an escaped double quote is not flagged). It's also rare, but possible, to have strings within string interpolations. In this case, its much more readable to use a single quote somewhere. So single quotes are allowed either within, or containing, an interpolated string literal. Arguably strings within string interpolations should be its own type of lint. **BAD:** ```dart useStrings( 'should be double quote', r'should be double quote', r\'''should be double quotes\''') ``` **GOOD:** ```dart useStrings( "should be double quote", r"should be double quote", r"""should be double quotes""", 'ok with " inside', 'nested \${a ? "strings" : "can"} be wrapped by a double quote', "and nested \${a ? 'strings' : 'can be double quoted themselves'}"); ``` '''; class PreferDoubleQuotes extends LintRule implements NodeLintRule { PreferDoubleQuotes() : super( name: 'prefer_double_quotes', description: _desc, details: _details, group: Group.style); @override List<String> get incompatibleRules => const ['prefer_single_quotes']; @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = QuoteVisitor(this, useSingle: false); registry.addSimpleStringLiteral(this, visitor); registry.addStringInterpolation(this, visitor); } }
linter/lib/src/rules/prefer_double_quotes.dart/0
{'file_path': 'linter/lib/src/rules/prefer_double_quotes.dart', 'repo_id': 'linter', 'token_count': 652}
// Copyright (c) 2016, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/type.dart'; import '../analyzer.dart'; import '../util/dart_type_utilities.dart'; const alwaysFalse = 'Always false because length is always greater or equal 0.'; const alwaysTrue = 'Always true because length is always greater or equal 0.'; const useIsEmpty = 'Use isEmpty instead of length'; const useIsNotEmpty = 'Use isNotEmpty instead of length'; const _desc = r'Use `isEmpty` for Iterables and Maps.'; const _details = r''' **DON'T** use `length` to see if a collection is empty. The `Iterable` contract does not require that a collection know its length or be able to provide it in constant time. Calling `length` just to see if the collection contains anything can be painfully slow. Instead, there are faster and more readable getters: `isEmpty` and `isNotEmpty`. Use the one that doesn't require you to negate the result. **GOOD:** ```dart if (lunchBox.isEmpty) return 'so hungry...'; if (words.isNotEmpty) return words.join(' '); ``` **BAD:** ```dart if (lunchBox.length == 0) return 'so hungry...'; if (words.length != 0) return words.join(' '); ``` '''; class PreferIsEmpty extends LintRule implements NodeLintRule { PreferIsEmpty() : super( name: 'prefer_is_empty', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this, context); registry.addSimpleIdentifier(this, visitor); } void reportLintWithDescription(AstNode? node, String description) { if (node != null) { reporter.reportErrorForNode(_LintCode(name, description), node, []); } } } class _LintCode extends LintCode { static final registry = <String, _LintCode>{}; factory _LintCode(String name, String message) => registry.putIfAbsent(name + message, () => _LintCode._(name, message)); _LintCode._(String name, String message) : super(name, message); } class _Visitor extends SimpleAstVisitor<void> { final PreferIsEmpty rule; final LinterContext context; _Visitor(this.rule, this.context); @override void visitSimpleIdentifier(SimpleIdentifier identifier) { // Should be "length". var propertyElement = identifier.staticElement; if (propertyElement?.name != 'length') { return; } AstNode? lengthAccess; InterfaceType? type; var parent = identifier.parent; if (parent is PropertyAccess && identifier == parent.propertyName) { lengthAccess = parent; var parentType = parent.target?.staticType; if (parentType is InterfaceType) { type = parentType; } } else if (parent is PrefixedIdentifier && identifier == parent.identifier) { lengthAccess = parent; var parentType = parent.prefix.staticType; if (parentType is InterfaceType) { type = parentType; } } if (type == null) { return; } // Should be subtype of Iterable, Map or String. if (!DartTypeUtilities.implementsInterface(type, 'Iterable', 'dart.core') && !DartTypeUtilities.implementsInterface(type, 'Map', 'dart.core') && !type.isDartCoreString) { return; } var search = lengthAccess; while ( search != null && search is Expression && search is! BinaryExpression) { search = search.parent; } if (search is! BinaryExpression) { return; } var binaryExpression = search; // Don't lint if we're in a const constructor initializer. var constructorInitializer = search.thisOrAncestorOfType<ConstructorInitializer>(); if (constructorInitializer != null) { var constructorDecl = constructorInitializer.parent; if (constructorDecl is! ConstructorDeclaration || constructorDecl.constKeyword != null) { return; } } // Or in a const context. // See: https://github.com/dart-lang/linter/issues/1719 if (binaryExpression.inConstantContext) { return; } var operator = binaryExpression.operator; // Comparing constants with length. var value = _getIntValue(binaryExpression.rightOperand); if (value != null) { // Constant is on right side of comparison operator. if (value == 0) { if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.LT_EQ) { rule.reportLintWithDescription(binaryExpression, useIsEmpty); } else if (operator.type == TokenType.GT || operator.type == TokenType.BANG_EQ) { rule.reportLintWithDescription(binaryExpression, useIsNotEmpty); } else if (operator.type == TokenType.LT) { rule.reportLintWithDescription(binaryExpression, alwaysFalse); } else if (operator.type == TokenType.GT_EQ) { rule.reportLintWithDescription(binaryExpression, alwaysTrue); } } else if (value == 1) { // 'length >= 1' is same as 'isNotEmpty', // and 'length < 1' is same as 'isEmpty' if (operator.type == TokenType.GT_EQ) { rule.reportLintWithDescription(binaryExpression, useIsNotEmpty); } else if (operator.type == TokenType.LT) { rule.reportLintWithDescription(binaryExpression, useIsEmpty); } } else if (value < 0) { // 'length' is always >= 0, so comparing with negative makes no sense. if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.LT_EQ || operator.type == TokenType.LT) { rule.reportLintWithDescription(binaryExpression, alwaysFalse); } else if (operator.type == TokenType.BANG_EQ || operator.type == TokenType.GT_EQ || operator.type == TokenType.GT) { rule.reportLintWithDescription(binaryExpression, alwaysTrue); } } return; } value = _getIntValue(binaryExpression.leftOperand); // ignore: invariant_booleans if (value != null) { // Constant is on left side of comparison operator. if (value == 0) { if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.GT_EQ) { rule.reportLintWithDescription(binaryExpression, useIsEmpty); } else if (operator.type == TokenType.LT || operator.type == TokenType.BANG_EQ) { rule.reportLintWithDescription(binaryExpression, useIsNotEmpty); } else if (operator.type == TokenType.GT) { rule.reportLintWithDescription(binaryExpression, alwaysFalse); } else if (operator.type == TokenType.LT_EQ) { rule.reportLintWithDescription(binaryExpression, alwaysTrue); } } else if (value == 1) { // '1 <= length' is same as 'isNotEmpty', // and '1 > length' is same as 'isEmpty' if (operator.type == TokenType.LT_EQ) { rule.reportLintWithDescription(binaryExpression, useIsNotEmpty); } else if (operator.type == TokenType.GT) { rule.reportLintWithDescription(binaryExpression, useIsEmpty); } } else if (value < 0) { // 'length' is always >= 0, so comparing with negative makes no sense. if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.GT_EQ || operator.type == TokenType.GT) { rule.reportLintWithDescription(binaryExpression, alwaysFalse); } else if (operator.type == TokenType.BANG_EQ || operator.type == TokenType.LT_EQ || operator.type == TokenType.LT) { rule.reportLintWithDescription(binaryExpression, alwaysTrue); } } } } /// Returns the value of an [IntegerLiteral] or [PrefixExpression] with a /// minus and then an [IntegerLiteral]. For anything else, returns `null`. int? _getIntValue(Expression expressions) { if (expressions is IntegerLiteral) { return expressions.value; } else if (expressions is PrefixExpression) { var operand = expressions.operand; if (expressions.operator.type == TokenType.MINUS && operand is IntegerLiteral) { var value = operand.value; if (value != null) { return -value; } } } // ignore: avoid_returning_null return null; } }
linter/lib/src/rules/prefer_is_empty.dart/0
{'file_path': 'linter/lib/src/rules/prefer_is_empty.dart', 'repo_id': 'linter', 'token_count': 3307}
// Copyright (c) 2016, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; import '../util/dart_type_utilities.dart'; const _desc = r'Property getter recursively returns itself.'; const _details = r''' **DON'T** create recursive getters. Recursive getters are getters which return themselves as a value. This is usually a typo. **BAD:** ```dart int get field => field; // LINT ``` **BAD:** ```dart int get otherField { return otherField; // LINT } ``` **GOOD:** ```dart int get field => _field; ``` '''; class RecursiveGetters extends LintRule implements NodeLintRule { RecursiveGetters() : super( name: 'recursive_getters', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addFunctionDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); } } /// Tests if a simple identifier is a recursive getter by looking at its parent. class _RecursiveGetterParentVisitor extends SimpleAstVisitor<bool> { @override bool visitPropertyAccess(PropertyAccess node) => node.target is ThisExpression; @override bool? visitSimpleIdentifier(SimpleIdentifier node) { var parent = node.parent; if (parent is ArgumentList || parent is ConditionalExpression || parent is ExpressionFunctionBody || parent is ReturnStatement) { return true; } if (parent is PropertyAccess) { return parent.accept(this); } return false; } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; final visitor = _RecursiveGetterParentVisitor(); _Visitor(this.rule); @override void visitFunctionDeclaration(FunctionDeclaration node) { // getters have null arguments, methods have parameters, could be empty. if (node.functionExpression.parameters != null) { return; } var element = node.declaredElement; _verifyElement(node.functionExpression, element); } @override void visitMethodDeclaration(MethodDeclaration node) { // getters have null arguments, methods have parameters, could be empty. if (node.parameters != null) { return; } var element = node.declaredElement; _verifyElement(node.body, element); } void _verifyElement(AstNode node, ExecutableElement? element) { var nodes = DartTypeUtilities.traverseNodesInDFS(node); nodes .where((n) => n is SimpleIdentifier && element == n.staticElement && (n.accept(visitor) ?? false)) .forEach(rule.reportLint); } }
linter/lib/src/rules/recursive_getters.dart/0
{'file_path': 'linter/lib/src/rules/recursive_getters.dart', 'repo_id': 'linter', 'token_count': 1069}
// 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Avoid const keyword.'; const _details = r''' **AVOID** repeating const keyword in a const context. **BAD:** ```dart class A { const A(); } m(){ const a = const A(); final b = const [const A()]; } ``` **GOOD:** ```dart class A { const A(); } m(){ const a = A(); final b = const [A()]; } ``` '''; class UnnecessaryConst extends LintRule implements NodeLintRule { UnnecessaryConst() : super( name: 'unnecessary_const', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); registry.addListLiteral(this, visitor); registry.addSetOrMapLiteral(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule); @override void visitInstanceCreationExpression(InstanceCreationExpression node) { if (node.keyword?.type != Keyword.CONST) return; if (node.inConstantContext) { rule.reportLint(node); } } @override void visitListLiteral(ListLiteral node) => _visitTypedLiteral(node); @override void visitSetOrMapLiteral(SetOrMapLiteral node) { _visitTypedLiteral(node); } void _visitTypedLiteral(TypedLiteral node) { if (node.constKeyword?.type != Keyword.CONST) return; if (node.inConstantContext) { rule.reportLint(node); } } }
linter/lib/src/rules/unnecessary_const.dart/0
{'file_path': 'linter/lib/src/rules/unnecessary_const.dart', 'repo_id': 'linter', 'token_count': 725}
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; import '../ast.dart'; const _desc = r"Don't access members with `this` unless avoiding shadowing."; const _details = r''' From the [style guide](https://dart.dev/guides/language/effective-dart/style/): **DON'T** use `this` when not needed to avoid shadowing. **BAD:** ```dart class Box { var value; void update(new_value) { this.value = new_value; } } ``` **GOOD:** ```dart class Box { var value; void update(new_value) { value = new_value; } } ``` **GOOD:** ```dart class Box { var value; void update(value) { this.value = value; } } ``` '''; class UnnecessaryThis extends LintRule implements NodeLintRule { UnnecessaryThis() : super( name: 'unnecessary_this', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this, context); registry.addConstructorFieldInitializer(this, visitor); registry.addThisExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; final LinterContext context; _Visitor(this.rule, this.context); @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { if (node.thisKeyword != null) { rule.reportLintForToken(node.thisKeyword); } } @override void visitThisExpression(ThisExpression node) { var parent = node.parent; Element? element; if (parent is PropertyAccess && !parent.isNullAware) { element = getWriteOrReadElement(parent.propertyName); } else if (parent is MethodInvocation && !parent.isNullAware) { element = parent.methodName.staticElement; } else { return; } if (_canReferenceElementWithoutThisPrefix(element, node)) { rule.reportLint(parent); } } bool _canReferenceElementWithoutThisPrefix(Element? element, AstNode node) { if (element == null) { return false; } var id = element.displayName; var isSetter = element is PropertyAccessorElement && element.isSetter; var result = context.resolveNameInScope(id, isSetter, node); // No result, definitely no shadowing. // The requested element is inherited, or from an extension. if (result.isNone) { return true; } // The result has the matching name, might be shadowing. // Check that the element is the same. if (result.isRequestedName) { return result.element == element; } // The result has the same basename, but not the same name. // Must be an instance member, so that: // - not shadowed by a local declaration; // - prevents us from going up to the library scope; // - the requested element must be inherited, or from an extension. if (result.isDifferentName) { var enclosing = result.element?.enclosingElement; return enclosing is ClassElement; } // Should not happen. return false; } }
linter/lib/src/rules/unnecessary_this.dart/0
{'file_path': 'linter/lib/src/rules/unnecessary_this.dart', 'repo_id': 'linter', 'token_count': 1210}
// Copyright (c) 2016, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Use valid regular expression syntax.'; const _details = r''' **DO** use valid regular expression syntax when creating regular expression instances. Regular expressions created with invalid syntax will throw a `FormatException` at runtime so should be avoided. **BAD:** ```dart print(RegExp(r'(').hasMatch('foo()')); ``` **GOOD:** ```dart print(RegExp(r'\(').hasMatch('foo()')); ``` '''; class ValidRegExps extends LintRule implements NodeLintRule { ValidRegExps() : super( name: 'valid_regexps', description: _desc, details: _details, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitInstanceCreationExpression(InstanceCreationExpression node) { var element = node.constructorName.staticElement?.enclosingElement; if (element?.name == 'RegExp' && element?.library.name == 'dart.core') { var args = node.argumentList.arguments; if (args.isEmpty) { return; } var sourceExpression = args.first; if (sourceExpression is StringLiteral) { var source = sourceExpression.stringValue; if (source != null) { try { RegExp(source); } on FormatException { rule.reportLint(sourceExpression); } } } } } }
linter/lib/src/rules/valid_regexps.dart/0
{'file_path': 'linter/lib/src/rules/valid_regexps.dart', 'repo_id': 'linter', 'token_count': 735}
// Copyright (c) 2020, 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. // @dart=2.9 import 'package:meta/meta.dart'; class A { var a; A.c({ @required a, // OK b, // LINT @required c, // OK }) : assert(a != null), assert(b != null); }
linter/test/_data/always_require_non_null_named_parameters/lib.dart/0
{'file_path': 'linter/test/_data/always_require_non_null_named_parameters/lib.dart', 'repo_id': 'linter', 'token_count': 154}
/// Class c. class c {}
linter/test/_data/p2/src/ignored/c.dart/0
{'file_path': 'linter/test/_data/p2/src/ignored/c.dart', 'repo_id': 'linter', 'token_count': 9}
import 'package:sample_project/dummy.dart'; // OK
linter/test/_data/prefer_relative_imports/bin/bin.dart/0
{'file_path': 'linter/test/_data/prefer_relative_imports/bin/bin.dart', 'repo_id': 'linter', 'token_count': 17}
// Copyright (c) 2019, 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:linter/src/util/ascii_utils.dart'; import 'package:test/test.dart'; void main() { group('fileNames', () { group('good', () { for (var name in goodFileNames) { test(name, () { expect(isValidDartFileName(name), isTrue); }); } }); group('bad', () { for (var name in badFileNames) { test(name, () { expect(isValidDartFileName(name), isFalse); }); } }); }); } final badFileNames = [ 'Foo.dart', 'fooBar.dart', '.foo_Bar.dart', 'F_B.dart', 'JS.dart', 'JSON.dart', ]; final goodFileNames = [ // Generated files. 'file-system.g.dart', 'SliderMenu.css.dart', '_file.dart', '_file.g.dart', // Non-strict Dart. 'bwu_server.shared.datastore.some_file', 'foo_bar.baz', 'foo_bar.dart', 'foo_bar.g.dart', 'foo_bar', 'foo.bar', 'foo_bar_baz', 'foo', 'foo_', 'foo.bar_baz.bang', //See: https://github.com/flutter/flutter/pull/1996 'pointycastle.impl.ec_domain_parameters.gostr3410_2001_cryptopro_a', 'a.b', 'a.b.c', 'p2.src.acme', //See: https://github.com/dart-lang/linter/issues/1803 '_', '_f', '__f', '___f', 'Foo', 'fooBar.', '.foo_Bar', '_.', '.', 'F_B', 'JS', 'JSON', ];
linter/test/ascii_utils_test.dart/0
{'file_path': 'linter/test/ascii_utils_test.dart', 'repo_id': 'linter', 'token_count': 680}
// Copyright (c) 2015, 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. // test w/ `dart test -N always_declare_return_types` main() { } //LINT bar() => new _Foo(); //LINT class _Foo { _foo() => 42; //LINT } typedef bad(int x); //LINT typedef bool predicate(Object o); void main2() { } _Foo bar2() => new _Foo(); class _Foo2 { int _foo() => 42; } set speed(int ms) {} //OK class Car { static set make(String name) {} // OK set speed(int ms) {} //OK } abstract class MyList<E> extends List<E> { @override operator []=(int index, E value) //OK: #300 { // ignored. } } class A { } extension Foo on A { foo() { } // LINT }
linter/test/rules/always_declare_return_types.dart/0
{'file_path': 'linter/test/rules/always_declare_return_types.dart', 'repo_id': 'linter', 'token_count': 300}
// 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. // test w/ `dart test -N avoid_field_initializers_in_const_classes` class A { final a = const []; // LINT const A(); } class B { final a; const B() // : a = const []; // LINT } class C { final a; const C(this.a); // OK } class D { final a; const D(b) // : a = b; // OK } // no lint if several constructors class E { final a; const E.c1() // : a = const []; // OK const E.c2() // : a = const {}; // OK } class F { final a; const F(int a) : this.a = 0; // LINT } class G { final g; const G(int length) : g = 'xyzzy'.length; // LINT } mixin M { final a = const []; // OK }
linter/test/rules/avoid_field_initializers_in_const_classes.dart/0
{'file_path': 'linter/test/rules/avoid_field_initializers_in_const_classes.dart', 'repo_id': 'linter', 'token_count': 334}
// Copyright (c) 2017, 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. // test w/ `dart test -N avoid_returning_this` class A { int x; A badAddOne() { // LINT x++; return this; } Object goodAddOne1() { // OK it is ok because it does not return an A type. x++; return this; } int goodAddOne2() { // OK x++; return this.x; } A getThing() { // LINT return this; } B doSomething() { // OK it is ok because it does not return an A type. x++; return this; } A operator +(int n) { // OK it is ok because it is an operator. x += n; return this; } } class B extends A{ @override A badAddOne() { // OK it is ok because it is an inherited method. x++; return this; } @override B doSomething() { // OK it is ok because it is an inherited method. x++; return this; } B badAddOne2() { // LINT x++; return this; } B badOne3() { // LINT int a() { return 1; } x = a(); return this; } B badOne4() { // LINT int a() => 1; x = a(); return this; } B badOne5() { // LINT final a = () { return 1; }; x = a(); return this; } } abstract class C<T> { T m(); T get g; } class D implements C<D> { @override D m() { // OK defined in interface return this; } @override D get g { // OK defined in interface return this; } D _m() { // LINT return this; } } class E implements C<E> { @override E m() => this; // OK defined in interface @override E get g => this; // OK defined in interface E _m() => this; // LINT } extension Ext on A { A ext() => this; // OK }
linter/test/rules/avoid_returning_this.dart/0
{'file_path': 'linter/test/rules/avoid_returning_this.dart', 'repo_id': 'linter', 'token_count': 723}
// Copyright (c) 2015, 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. // test w/ `dart test -N constant_identifier_names` const DEFAULT_TIMEOUT = 1000; //LINT const PI = 3.14; //LINT class Z { static const DEBUG = false; //LINT } enum Foo { bar, Baz, //LINT }
linter/test/rules/constant_identifier_names.dart/0
{'file_path': 'linter/test/rules/constant_identifier_names.dart', 'repo_id': 'linter', 'token_count': 134}
// 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. // test w/ `dart test -N null_closures` import 'dart:async'; import 'dart:core'; class A extends B { A(int x); } class B extends A {} //https://github.com/dart-lang/linter/issues/1414 void test_cycle() { new A(null); } void list_firstWhere() { // firstWhere has a _named_ closure argument. <int>[2, 4, 6].firstWhere((e) => e.isEven, orElse: null); // LINT <int>[2, 4, 6].firstWhere((e) => e.isEven, orElse: () => null); // OK <int>[2, 4, 6].where(null); // LINT <int>[2, 4, 6].where((e) => e.isEven); // OK } void map_putIfAbsent() { // putIfAbsent has a _required_ closure argument. var map = <int, int>{}; map.putIfAbsent(7, null); // LINT map.putIfAbsent(7, () => null); // OK } void future_wait() { // Future.wait is a _static_ function with a _named_ argument. Future.wait([], cleanUp: null); // LINT Future.wait([], cleanUp: (_) => print('clean')); // OK } void list_generate() { // todo (pq): look at migrated SDK and see if generators can be null. // List.generate is a _constructor_ with a _positional_ argument. new List.generate(3, null); // LINT new List.generate(3, (_) => null); // OK } void map_otherMethods() { // These methods have nothing we are concerned with. new Map().keys; // OK new Map().addAll({}); // OK }
linter/test/rules/experiments/nnbd/rules/null_closures.dart/0
{'file_path': 'linter/test/rules/experiments/nnbd/rules/null_closures.dart', 'repo_id': 'linter', 'token_count': 539}
// Copyright (c) 2016, 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. // test w/ `dart test -N hash_and_equals` class Bad { final int value; Bad(this.value); @override bool operator ==(Object other) => other is Bad && other.value == value; //LINT } class Bad2 { final int value; Bad2(this.value); @override int get hashCode => value.hashCode; //LINT } class Better //OK! { final int value; Better(this.value); @override bool operator ==(Object other) => other is Better && other.value == value; @override int get hashCode => value.hashCode; } class OK {} class AlsoOk { @override final int hashCode; AlsoOk(this.hashCode); @override bool operator ==(Object other) => other is AlsoOk && other.hashCode == hashCode; //OK } class NotOk { @override final int hashCode; //LINT NotOk(this.hashCode); }
linter/test/rules/hash_and_equals.dart/0
{'file_path': 'linter/test/rules/hash_and_equals.dart', 'repo_id': 'linter', 'token_count': 330}
// Copyright (c) 2020, 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. // test w/ `dart test -N no_runtimeType_toString` var o; class A { var field; String f() { final s1 = '$runtimeType'; // LINT final s2 = runtimeType.toString(); // LINT final s3 = this.runtimeType.toString(); // LINT final s4 = '${runtimeType}'; // LINT final s5 = '${o.runtimeType}'; // OK final s6 = o.runtimeType.toString(); // OK final s7 = runtimeType == runtimeType; // OK final s8 = field?.runtimeType?.toString(); // OK try { final s9 = '${runtimeType}'; // LINT } catch (e) { final s10 = '${runtimeType}'; // OK } final s11 = super.runtimeType.toString(); // LINT throw '${runtimeType}'; // OK } } abstract class B { void f() { final s1 = '$runtimeType'; // OK } } mixin C { void f() { final s1 = '$runtimeType'; // OK } } class D { void f() { var runtimeType = 'C'; print('$runtimeType'); // OK } } extension on A { String f() => '$runtimeType'; // LINT } extension on B { String f() => '$runtimeType'; // OK }
linter/test/rules/no_runtimeType_toString.dart/0
{'file_path': 'linter/test/rules/no_runtimeType_toString.dart', 'repo_id': 'linter', 'token_count': 479}
// Copyright (c) 2019, 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. // test w/ `dart test -N prefer_if_null_operators` var v; m(p) { var a, b; a == null ? b : a; // LINT null == a ? b : a; // LINT a != null ? a : b; // LINT null != a ? a : b; // LINT a.b != null ? a.b : b; // LINT v == null ? b : v; // LINT p == null ? b : p; // LINT }
linter/test/rules/prefer_if_null_operators.dart/0
{'file_path': 'linter/test/rules/prefer_if_null_operators.dart', 'repo_id': 'linter', 'token_count': 191}
// Copyright (c) 2015, 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. // test w/ `dart test -N unnecessary_brace_in_string_interps` main(args) { print('hello'); print('hello $args'); print('hello $args!'); print('hello ${args}1'); print('hello ${args}'); //LINT [16:7] print('hello ${args}!'); //LINT print('hello ${args.length}'); print('hello _${args}_'); var $someString = 'Some Value'; print('Value is: ${$someString}'); //OK }
linter/test/rules/unnecessary_brace_in_string_interps.dart/0
{'file_path': 'linter/test/rules/unnecessary_brace_in_string_interps.dart', 'repo_id': 'linter', 'token_count': 197}
// Copyright (c) 2017, 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. // test w/ `dart test -N unnecessary_this` extension E on int { String f() => this?.toString(); //OK int get h => this?.hashCode; //OK } void bar() {} int x; class Parent { int x, y; void bar() {} void foo() {} } class Child extends Parent { void SuperclassMethodWithTopLevelFunction() { this.bar(); // OK } void SuperclassMethodWithoutTopLevelFunction() { this.foo(); // LINT } void SuperclassVariableWithTopLevelVariable(int a) { this.x = a; // OK } void SuperclassVariableWithoutTopLevelVariable(int a) { this.y = a; // LINT } } void duplicate() {} class A { num x, y; A(num x, num y) { this.x = x; // OK this.y = y; // OK } A.c1(num x, num y) : x = x, // OK this.y = y; // LINT A.bar(this.x, this.y); A.foo(num a, num b) { this.x = a; // LINT this.y = b; // LINT this.fooMethod(); // LINT } void bar2(int a) { print(a.toString()); } void barMethod() { if (x == y) { // ignore: unused_element void fooMethod() { // local function } this.fooMethod(); // OK } this.fooMethod(); // LINT } void duplicate() {} void fooMethod() { [].forEach((e) { this.bar2(e); // LINT this.duplicate(); // LINT }); } }
linter/test/rules/unnecessary_this.dart/0
{'file_path': 'linter/test/rules/unnecessary_this.dart', 'repo_id': 'linter', 'token_count': 615}
// 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. // test w/ `dart test -N void_checks` // @dart=2.9 import 'dart:async'; var x; get g => null; set s(v) {} m() {} class A<T> { T value; A(); A.c(this.value); void m1(T arg) {} void m2(i, [T v]) {} void m3(i, {T v}) {} void m4(void arg) {} T m5(e) => null; } void call_constructor_with_void_positional_parameter() { new A<void>.c(x); // LINT } void call_method_with_void_positional_parameter() { final a = new A<void>(); a.m1(x); // LINT } void call_method_with_void_optional_positional_parameter() { final a = new A<void>(); a.m2( null, x, // LINT ); } void call_method_with_void_optional_named_parameter() { final a = new A<void>(); a.m3( null, v: x, // LINT ); } void use_setter_with_void_parameter() { final a = new A<void>(); a.value = x; // LINT } void call_method_with_futureOr_void_parameter() { final a = new A<FutureOr<void>>(); // it's OK to pass Future or FutureOr to m1 a.m1(new Future.value()); // OK FutureOr<void> fo; a.m1(fo); // OK a.m1(x); // OK a.m1(null); // OK a.m1(1); // LINT } void use_setter_with_futureOr_void_parameter() { final a = new A<FutureOr<void>>(); // it's OK to pass Future or FutureOr to set value a.value = new Future.value(); //OK FutureOr<void> fo; a.value = fo; // OK a.value = x; // OK a.value = null; // OK a.value = 1; // LINT } void return_inside_block_function_body() { return x; // LINT } void simple_return_inside_block_function_body() { return; // OK } void return_from_expression_function_body() => x; // OK FutureOr<void> return_value_for_futureOr() { return 1; // LINT } FutureOr<void> return_future_for_futureOr() { return new Future.value(); // OK } FutureOr<void> return_futureOr_for_futureOr() { return x; // OK } void assert_is_void_function_is_ok() { assert(() { return true; // OK }()); } async_function() { void f(Function f) {} f(() //OK async { return 1; // OK }); } inference() { f(void Function() f) {} f(() // LINT { return 1; // OK }); } generics_with_function() { f<T>(T Function() f) => f(); f(() // OK { return 1; }); f<void>(() // LINT { return 1; }); } /// function ref are similar to expression function body with void return type function_ref_are_ok() { fA(void Function(dynamic) f) {} fB({void Function(dynamic) f}) {} void Function(String e) f1 = (e) {}; fA(f1); // OK final f2 = (e) {}; fA(f2); // OK final f3 = (e) => 1; fA(f3); // OK final a1 = new A(); fA(a1.m5); // OK fB(f: a1.m5); // OK final a2 = new A<void>(); fA(a2.m5); // OK } allow_functionWithReturnType_forFunctionWithout() { takeVoidFn(void Function() f) {} void Function() voidFn; int nonVoidFn() => 1; takeVoidFn(nonVoidFn); // OK voidFn = nonVoidFn; // OK void Function() returnsVoidFn() { return nonVoidFn; // OK } } allow_functionWithReturnType_forFunctionWithout_asComplexExpr() { takeVoidFn(void Function() f) {} void Function() voidFn; List<int Function()> listNonVoidFn; takeVoidFn(listNonVoidFn[0]); // OK voidFn = listNonVoidFn[0]; // OK void Function() returnsVoidFn() { return listNonVoidFn[0]; // OK } } allow_Null_for_void() { forget(void Function() f) {} forget(() {}); // OK void Function() f; f = () {}; // OK } allow_Future_void_for_void() { forget(void Function() f) {} forget(() async {}); // OK void Function() f; f = () async {}; // OK } allow_expression_function_body() { forget(void Function() f) {} int i; forget(() => i); // OK forget(() => i++); // OK void Function() f; f = () => i; // OK f = () => i++; // OK } missing_parameter_for_argument() { void foo() {} foo(0); } void emptyFunctionExpressionReturningFutureOrVoid(FutureOr<void> Function() f) { f = () {}; // OK }
linter/test/rules/void_checks.dart/0
{'file_path': 'linter/test/rules/void_checks.dart', 'repo_id': 'linter', 'token_count': 1676}
// Copyright (c) 2019, 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 'dart:async'; import 'dart:io'; import 'package:pub_semver/pub_semver.dart'; import 'package:yaml/yaml.dart'; import 'crawl.dart'; void main() async { // Uncomment to (re)generate since/linter.yaml contents. // for (var lint in registeredLints) { // var since = await findSinceLinter(lint.name); // if (since != null) { // print('${lint.name}: $since'); // } // } // Uncomment to (re)generate since/dart_sdk.yaml contents. // var tags = await sdkTags; // for (var tag in sdkTags)) { // var version = await fetchLinterForVersion(tag); // if (version.startsWith('@')) { // version = version.substring(1); // } // print('$tag: $version'); // } await sinceMap.then((m) => m.entries.forEach(print)); } Map<String, SinceInfo>? _sinceMap; Future<Map<String, SinceInfo>> get sinceMap async => _sinceMap ??= await _getSinceInfo(); Future<Map<String, SinceInfo>> _getSinceInfo() async { var linterCache = File('tool/since/linter.yaml').readAsStringSync(); var linterVersionCache = loadYamlNode(linterCache) as YamlMap; var sinceMap = <String, SinceInfo>{}; for (var lint in registeredLints.map((l) => l.name)) { var linterVersion = linterVersionCache[lint] as String?; if (linterVersion == null) { linterVersion = await findSinceLinter(lint); if (linterVersion != null) { print('fetched...'); print('$lint : $linterVersion'); print('(consider caching in tool/since/linter.yaml)'); } } sinceMap[lint] = SinceInfo( sinceLinter: linterVersion ?? await findSinceLinter(lint), sinceDartSdk: await _sinceSdkForLinter(linterVersion)); } return sinceMap; } Map<String, String>? _dartSdkMap; Future<Map<String, String>?> get dartSdkMap async { if (_dartSdkMap == null) { var dartSdkCache = await File('tool/since/dart_sdk.yaml').readAsString(); var yamlMap = loadYamlNode(dartSdkCache) as YamlMap; _dartSdkMap = yamlMap.map((k, v) => MapEntry(k.toString(), v.toString())); var sdks = await sdkTags; for (var sdk in sdks) { if (!_dartSdkMap!.containsKey(sdk)) { var linterVersion = await linterForDartSdk(sdk); if (linterVersion != null) { _dartSdkMap![sdk] = linterVersion; print('fetched...'); print('$sdk : $linterVersion'); print('(consider caching in tool/since/dart_sdk.yaml)'); } } } } return _dartSdkMap; } Version earliestLinterInDart2 = Version.parse('0.1.58'); Future<String?> _sinceSdkForLinter(String? linterVersionString) async { if (linterVersionString == null) { return null; } var linterVersion = Version.parse(linterVersionString); if (linterVersion.compareTo(earliestLinterInDart2) < 0) { return bottomDartSdk.toString(); } var sdkVersions = <String>[]; var sdkCache = await dartSdkMap; if (sdkCache != null) { for (var sdkEntry in sdkCache.entries) { if (Version.parse(sdkEntry.value) == linterVersion) { sdkVersions.add(sdkEntry.key); } } } if (sdkVersions.isEmpty) { var nextLinter = await _nextLinterVersion(linterVersion); return _sinceSdkForLinter(nextLinter); } sdkVersions.sort(); return sdkVersions.first; } Future<String?> _nextLinterVersion(Version linterVersion) async { var versions = await linterVersions; if (versions != null) { for (var version in versions) { if (Version.parse(version).compareTo(linterVersion) > 0) { return version; } } } return null; } List<String>? _linterVersions; Future<List<String>?> get linterVersions async { if (_linterVersions == null) { _linterVersions = <String>[]; for (var minor = 0; minor <= await latestMinor; ++minor) { _linterVersions!.add('0.1.$minor'); } } return _linterVersions; } class SinceInfo { final String? sinceLinter; final String? sinceDartSdk; SinceInfo({this.sinceLinter, this.sinceDartSdk}); @override String toString() => 'linter: $sinceLinter | sdk: $sinceDartSdk'; }
linter/tool/since.dart/0
{'file_path': 'linter/tool/since.dart', 'repo_id': 'linter', 'token_count': 1683}
name: Flutter Test on: [push, pull_request] jobs: test: runs-on: macos-latest env: ACTIONS_ALLOW_UNSECURE_COMMANDS: 'true' steps: - uses: actions/checkout@v1 - name: Install Flutter uses: subosito/flutter-action@v1.3.2 - name: Install app dependencies run: flutter pub get - name: Test app run: flutter test --coverage - name: Upload coverage to Codecov uses: codecov/codecov-action@v1 with: token: ${{ secrets.CODECOV_TOKEN }} file: coverage/lcov.info
liquid_swipe_flutter/.github/workflows/flutterTest.yml/0
{'file_path': 'liquid_swipe_flutter/.github/workflows/flutterTest.yml', 'repo_id': 'liquid_swipe_flutter', 'token_count': 238}
import 'package:flutter/material.dart'; class Animator { Animator({this.controller, this.animation}); AnimationController controller; Animation<double> animation; } class StatefulMultipleAnimationController extends StatefulWidget { const StatefulMultipleAnimationController({Key key}); @override _AppState createState() => _AppState(); } class _AppState extends State<StatefulMultipleAnimationController> with TickerProviderStateMixin { List<Animator> animators = []; bool isDown = false; int numBoxes = 3; @override void initState() { for (int i = 0; i < numBoxes; i++) { final AnimationController c = AnimationController( duration: Duration(milliseconds: 500), vsync: this, ); animators.add( Animator( controller: c, animation: Tween<double>( begin: 0, end: 300, ) .chain( CurveTween( curve: Curves.easeOutBack, ), ) .animate(c), ), ); } super.initState(); } @override void dispose() { for (int i = 0; i < numBoxes; i++) { animators[i].controller.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( home: SafeArea( child: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { if (!isDown) { for (final Animator animator in animators) { animator.controller.forward(); } setState(() { isDown = true; }); } else { for (final Animator animator in animators) { animator.controller.reverse(); } setState(() { isDown = false; }); } }, ), body: Stack( children: List<Box>.generate( numBoxes, (int index) => Box( index: index, animation: animators[index].animation, ), ), ), ), ), ); } } class Box extends StatelessWidget { Box({ @required this.animation, @required this.index, }); final int index; final Animation<double> animation; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation, builder: (context, child) { return Positioned( top: (animation.value) + (index * (100 + 10)), left: (MediaQuery.of(context).size.width - 100) / 2, child: child, ); }, child: Container( width: 100, height: 100, color: Colors.blue, ), ); } }
local_widget_state_approaches/lib/stateful/multiple_animation_controller.dart/0
{'file_path': 'local_widget_state_approaches/lib/stateful/multiple_animation_controller.dart', 'repo_id': 'local_widget_state_approaches', 'token_count': 1413}
name: print_lumberdash description: >- Lumberdash plugin that uses print() to output your logs version: 2.1.0 author: Jorge Coca <jcocaramos@gmail.com> homepage: https://github.com/jorgecoca/lumberdash environment: sdk: ">=2.4.0 <3.0.0" dependencies: lumberdash: ^2.1.0 meta: ^1.0.0
lumberdash/plugins/print_lumberdash/pubspec.yaml/0
{'file_path': 'lumberdash/plugins/print_lumberdash/pubspec.yaml', 'repo_id': 'lumberdash', 'token_count': 118}
void main() { {{#flavors}}print('Running in {{.}} mode...');{{/flavors}} }
mason/bricks/flavors/__brick__/main_{{#flavors}}{{{.}}}{{/flavors}}.dart/0
{'file_path': 'mason/bricks/flavors/__brick__/main_{{#flavors}}{{{.}}}{{/flavors}}.dart', 'repo_id': 'mason', 'token_count': 30}
import 'package:mason/mason.dart'; /// {@template brick} /// Metadata for a brick template including the name and location. /// {@endtemplate} class Brick { /// {@macro brick} const Brick({required this.location, this.name}); /// Brick from a local path. Brick.path(String path) : this(location: BrickLocation(path: path)); /// Brick from a git url. Brick.git(GitPath git) : this(location: BrickLocation(git: git)); /// Brick from a version constraint. Brick.version({required String name, required String version}) : this( name: name, location: BrickLocation(version: version), ); /// The name of the brick. final String? name; /// The location of the brick. final BrickLocation location; }
mason/packages/mason/lib/src/brick.dart/0
{'file_path': 'mason/packages/mason/lib/src/brick.dart', 'repo_id': 'mason', 'token_count': 240}
import 'package:path/path.dart' as p; /// Canonicalizes [path]. /// /// This function implements the behaviour of `canonicalize` from /// `package:path`. /// However, it does not change the ASCII case of the path. /// See https://github.com/dart-lang/path/issues/102. String canonicalize(String path) { return p.normalize(p.absolute(path)).replaceAll(r'\', '/'); } /// Normalizes the [path]. String normalize(String path) => p.normalize(path).replaceAll(r'\', '/');
mason/packages/mason/lib/src/path.dart/0
{'file_path': 'mason/packages/mason/lib/src/path.dart', 'repo_id': 'mason', 'token_count': 150}
import 'package:mason/mason.dart'; import 'package:test/test.dart'; void main() { BrickYaml getBrickYaml(String constraint) { return BrickYaml( name: 'example', description: 'example', version: '0.1.0', environment: BrickEnvironment(mason: constraint), ); } group('isBrickCompatibleWithMason', () { test('returns true when constraint is any', () { expect( isBrickCompatibleWithMason(getBrickYaml('any')), isTrue, ); }); test('returns true when constraint is ^{currentVersion}', () { expect( isBrickCompatibleWithMason(getBrickYaml('^$packageVersion')), isTrue, ); }); test('returns true when constraint is {currentVersion}', () { expect( isBrickCompatibleWithMason(getBrickYaml(packageVersion)), isTrue, ); }); test('returns true when constraint is ">={currentVersion}"', () { expect( isBrickCompatibleWithMason(getBrickYaml('>=$packageVersion')), isTrue, ); }); test('returns false when constraint is 0.0.0', () { expect( isBrickCompatibleWithMason(getBrickYaml('0.0.0')), isFalse, ); }); test('returns false when constraint is ^0.0.0', () { expect( isBrickCompatibleWithMason(getBrickYaml('^0.0.0')), isFalse, ); }); test('returns false when constraint is >=0.0.0 <0.0.1', () { expect( isBrickCompatibleWithMason(getBrickYaml('>=0.0.0 <0.0.1')), isFalse, ); }); }); }
mason/packages/mason/test/src/brick_compatibility_test.dart/0
{'file_path': 'mason/packages/mason/test/src/brick_compatibility_test.dart', 'repo_id': 'mason', 'token_count': 707}
/// {@template user} /// A mason user account. /// {@endtemplate} class User { /// {@macro user} const User({ required this.email, required this.emailVerified, }); /// The user's email address. final String email; /// Whether the user's email address has been verified. final bool emailVerified; }
mason/packages/mason_api/lib/src/models/user.dart/0
{'file_path': 'mason/packages/mason_api/lib/src/models/user.dart', 'repo_id': 'mason', 'token_count': 101}
/// A Dart template generator which helps teams /// generate files quickly and consistently. /// /// ```sh /// # Activate mason /// dart pub global activate mason_cli /// /// # See usage /// mason --help /// ``` /// /// Get started at [https://github.com/felangel/mason](https://github.com/felangel/mason) 🧱 library mason_cli;
mason/packages/mason_cli/lib/mason_cli.dart/0
{'file_path': 'mason/packages/mason_cli/lib/mason_cli.dart', 'repo_id': 'mason', 'token_count': 101}
import 'dart:io'; import 'dart:math'; import 'package:mason/mason.dart' hide Brick, packageVersion; import 'package:mason_api/mason_api.dart'; import 'package:mason_cli/src/command.dart'; import 'package:mason_cli/src/command_runner.dart'; /// {@template logout_command} /// `mason search` command which searches registered bricks on `brickhub.dev`. /// {@endtemplate} class SearchCommand extends MasonCommand { /// {@macro logout_command} SearchCommand({super.logger, MasonApiBuilder? masonApiBuilder}) : _masonApiBuilder = masonApiBuilder ?? MasonApi.new; final MasonApiBuilder _masonApiBuilder; @override final String description = 'Search published bricks on brickhub.dev.'; @override final String name = 'search'; @override Future<int> run() async { if (results.rest.isEmpty) usageException('search term is required.'); final query = results.rest.first; final searchProgress = logger.progress( 'Searching "$query" on brickhub.dev', ); final masonApi = _masonApiBuilder(); try { final results = await masonApi.search(query: query); searchProgress.complete( results.isEmpty ? 'No bricks found.' : '''Found ${results.length} brick${results.length == 1 ? '' : 's'}.''', ); logger.info(''); for (final brick in results) { final brickLink = styleUnderlined.wrap( link( uri: Uri.parse( 'https://brickhub.dev/bricks/${brick.name}/${brick.version}', ), ), ); logger ..info( lightCyan.wrap(styleBold.wrap('${brick.name} v${brick.version}')), ) ..info(brick.description) ..info(brickLink) ..info(darkGray.wrap('-' * _separatorLength())); } return ExitCode.success.code; } catch (error) { searchProgress.fail(); logger.err('$error'); return ExitCode.software.code; } finally { masonApi.close(); } } } int _separatorLength() { const maxSeparatorLength = 80; try { return min(stdout.terminalColumns, maxSeparatorLength); } catch (_) { return maxSeparatorLength; } }
mason/packages/mason_cli/lib/src/commands/search.dart/0
{'file_path': 'mason/packages/mason_cli/lib/src/commands/search.dart', 'repo_id': 'mason', 'token_count': 908}
name: enum_no_choices description: A new brick created with the Mason CLI. version: 0.1.0+1 environment: mason: ">=0.1.0-dev <0.1.0" vars: color: type: enum description: Your favorite color prompt: What is your favorite color? values:
mason/packages/mason_cli/test/bricks/enum_no_choices/brick.yaml/0
{'file_path': 'mason/packages/mason_cli/test/bricks/enum_no_choices/brick.yaml', 'repo_id': 'mason', 'token_count': 101}
/// Indicates the desired logging level. enum Level { /// The most verbose log level -- everything is logged. verbose, /// Used for debug info. debug, /// Default log level used for standard logs. info, /// Used to indicate a potential problem. warning, /// Used to indicate a problem. error, /// Used to indicate an urgent/severe problem. critical, /// The least verbose level -- nothing is logged. quiet, }
mason/packages/mason_logger/lib/src/level.dart/0
{'file_path': 'mason/packages/mason_logger/lib/src/level.dart', 'repo_id': 'mason', 'token_count': 121}
import 'package:{{name}}/auth/state/auth_controller.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; class HomeScreen extends HookConsumerWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( body: Center( child: ElevatedButton( child: const Text( 'Sign out', style: TextStyle(fontSize: 20), ), onPressed: () { ref.read(authControllerProvider.notifier).signOut(); }, ), ), ); } }
mason_bricks-1/bricks/firebase_auth_riverpod/__brick__/auth/ui/screen/home_screen.dart/0
{'file_path': 'mason_bricks-1/bricks/firebase_auth_riverpod/__brick__/auth/ui/screen/home_screen.dart', 'repo_id': 'mason_bricks-1', 'token_count': 277}
import 'package:flutter/material.dart'; class ConfigurationData { final String foo; ConfigurationData({this.foo}); } class Configurations extends StatefulWidget { final Widget child; final ConfigurationData _mock; const Configurations({Key key, this.child}) : _mock = null, super(key: key); Configurations.mock({Key key, ConfigurationData configurations, this.child}) : _mock = configurations, super(key: key); static ConfigurationData of(BuildContext context) { _ConfigurationsInherited conf = context.inheritFromWidgetOfExactType(_ConfigurationsInherited); return conf.configurations; } @override _ConfigurationsState createState() => _ConfigurationsState(); } class _ConfigurationsState extends State<Configurations> { ConfigurationData configurations; @override void initState() { super.initState(); configurations = ConfigurationData( foo: "Hello World", ); } @override Widget build(BuildContext context) { return _ConfigurationsInherited( configurations: widget._mock ?? configurations, child: widget.child, ); } } class _ConfigurationsInherited extends InheritedWidget { final ConfigurationData configurations; _ConfigurationsInherited({this.configurations, Widget child}) : super(child: child); @override bool updateShouldNotify(_ConfigurationsInherited oldWidget) { return configurations != oldWidget.configurations; } }
meetup-18-10-18/lib/one-feature-one-widget/good-mock.dart/0
{'file_path': 'meetup-18-10-18/lib/one-feature-one-widget/good-mock.dart', 'repo_id': 'meetup-18-10-18', 'token_count': 460}
name: Prepare release on: push: branches: [main] jobs: prepare-release: name: Prepare release permissions: contents: write pull-requests: write runs-on: ubuntu-latest if: "!contains(github.event.head_commit.message, 'chore(release)')" steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 - uses: bluefireteam/melos-action@v3 with: run-versioning: true publish-dry-run: true create-pr: true
melos-action/examples/prepare-release.yml/0
{'file_path': 'melos-action/examples/prepare-release.yml', 'repo_id': 'melos-action', 'token_count': 227}
blank_issues_enabled: false
mini_sprite/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'mini_sprite/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'mini_sprite', 'token_count': 7}
library flutter_mini_sprite; export 'src/flutter_mini_sprite.dart';
mini_sprite/packages/flutter_mini_sprite/lib/flutter_mini_sprite.dart/0
{'file_path': 'mini_sprite/packages/flutter_mini_sprite/lib/flutter_mini_sprite.dart', 'repo_id': 'mini_sprite', 'token_count': 27}
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; part 'config_state.dart'; class ConfigCubit extends HydratedCubit<ConfigState> { ConfigCubit() : super(const ConfigState.initial()); void setThemeMode(ThemeMode mode) { emit(state.copyWith(themeMode: mode)); } void setFilledColor(Color color) { emit(state.copyWith(filledColor: color)); } void setUnfilledColor(Color color) { emit(state.copyWith(unfilledColor: color)); } void setBackgroundColor(Color color) { emit(state.copyWith(backgroundColor: color)); } void setGridSize(int value) { emit(state.copyWith(mapGridSize: value)); } @override ConfigState? fromJson(Map<String, dynamic> json) { final themeModeRaw = json['theme_mode'] as String?; final themeMode = ThemeMode.values.firstWhere( (ThemeMode mode) => mode.name == themeModeRaw, orElse: () => ThemeMode.system, ); return ConfigState( themeMode: themeMode, filledColor: Color(json['filled_color'] as int), unfilledColor: Color(json['unfilled_color'] as int), backgroundColor: Color(json['background_color'] as int), mapGridSize: json['map_grid_size'] as int, ); } @override Map<String, dynamic>? toJson(ConfigState state) { return <String, dynamic>{ 'theme_mode': state.themeMode.name, 'filled_color': state.filledColor.value, 'unfilled_color': state.unfilledColor.value, 'background_color': state.backgroundColor.value, 'map_grid_size': state.mapGridSize, }; } List<Color> palette() => [state.filledColor, state.unfilledColor]; }
mini_sprite/packages/mini_sprite_editor/lib/config/cubit/config_cubit.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/config/cubit/config_cubit.dart', 'repo_id': 'mini_sprite', 'token_count': 612}
export 'library_panel.dart';
mini_sprite/packages/mini_sprite_editor/lib/library/view/view.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/library/view/view.dart', 'repo_id': 'mini_sprite', 'token_count': 10}
import 'dart:ui'; import 'package:collection/collection.dart'; import 'package:equatable/equatable.dart'; import 'package:file_selector/file_selector.dart'; import 'package:flame_mini_sprite/flame_mini_sprite.dart'; import 'package:flutter/services.dart'; import 'package:mini_sprite/mini_sprite.dart'; import 'package:mini_sprite_editor/sprite/sprite.dart'; import 'package:replay_bloc/replay_bloc.dart'; part 'sprite_state.dart'; class SpriteCubit extends ReplayCubit<SpriteState> { SpriteCubit({ Future<void> Function(ClipboardData)? setClipboardData, Future<ClipboardData?> Function(String)? getClipboardData, }) : _setClipboardData = setClipboardData ?? Clipboard.setData, _getClipboardData = getClipboardData ?? Clipboard.getData, super(SpriteState.initial()); final Future<void> Function(ClipboardData) _setClipboardData; final Future<ClipboardData?> Function(String) _getClipboardData; bool toolActive = false; void copyToClipboard() { final sprite = MiniSprite(state.pixels); final data = sprite.toDataString(); _setClipboardData(ClipboardData(text: data)); } void setSprite(List<List<int>> pixels) { emit(state.copyWith(pixels: pixels)); clearHistory(); } Future<void> exportToImage({ required int pixelSize, required List<Color> palette, required Color backgroundColor, }) async { final miniSprite = MiniSprite(state.pixels); final sprite = await miniSprite.toSprite( pixelSize: pixelSize.toDouble(), palette: palette, backgroundColor: backgroundColor, ); final data = await sprite.image.toByteData(format: ImageByteFormat.png); const fileName = 'sprite.png'; final path = await getSavePath(suggestedName: fileName); if (path == null) { // Operation was canceled by the user. return; } final fileData = data!.buffer.asUint8List(); const mimeType = 'image/png'; final imageFile = XFile.fromData( fileData, mimeType: mimeType, name: fileName, ); await imageFile.saveTo(path); } Future<void> importFromClipboard() async { final data = await _getClipboardData('text/plain'); final text = data?.text; if (text != null) { final sprite = MiniSprite.fromDataString(text); emit(state.copyWith(pixels: sprite.pixels)); } } void cursorLeft() { emit(state.copyWith(cursorPosition: const Offset(-1, -1))); } Offset _projectOffset(Offset position, double pixelSize) { final projected = position / pixelSize; final x = projected.dx.floorToDouble(); final y = projected.dy.floorToDouble(); return Offset(x, y); } void _setPixel(int value) { final newPixels = [ ...state.pixels.map((e) => [...e]), ]; final x = state.cursorPosition.dx.toInt(); final y = state.cursorPosition.dy.toInt(); newPixels[y][x] = value; emit(state.copyWith(pixels: newPixels)); } void _floodFillSeek(int x, int y, int value, List<List<int>> pixels) { if (y < 0 || y >= pixels.length || x < 0 || x >= pixels[0].length) { return; } if (pixels[y][x] == value) { return; } pixels[y][x] = value; _floodFillSeek(x + 1, y, value, pixels); _floodFillSeek(x - 1, y, value, pixels); _floodFillSeek(x, y + 1, value, pixels); _floodFillSeek(x, y - 1, value, pixels); } void _floodFill(int value) { final newPixels = [ ...state.pixels.map((e) => [...e]), ]; _floodFillSeek( state.cursorPosition.dx.toInt(), state.cursorPosition.dy.toInt(), value, newPixels, ); emit(state.copyWith(pixels: newPixels)); toolActive = false; } void _processTool(SpriteTool tool, int selectedColor) { switch (tool) { case SpriteTool.brush: if (toolActive) { _setPixel(selectedColor); } break; case SpriteTool.eraser: if (toolActive) { _setPixel(-1); } break; case SpriteTool.bucket: if (toolActive) { _floodFill(selectedColor); } break; case SpriteTool.bucketEraser: if (toolActive) { _floodFill(-1); } break; } } void cursorHover( Offset position, double pixelSize, SpriteTool tool, int selectedColor, ) { final projected = _projectOffset(position, pixelSize); if (projected != state.cursorPosition) { emit(state.copyWith(cursorPosition: projected)); _processTool(tool, selectedColor); } } void cursorDown( Offset position, double pixelSize, SpriteTool tool, int selectedColor, ) { final projected = _projectOffset(position, pixelSize); emit(state.copyWith(cursorPosition: projected)); toolActive = true; _processTool(tool, selectedColor); } void cursorUp(SpriteTool tool, int selectedColor) { toolActive = false; _processTool(tool, selectedColor); } void setSize(int x, int y) { final newPixels = [ ...List.generate(y, (i) => List.generate(x, (j) => -1)), ]; for (var y = 0; y < state.pixels.length; y++) { for (var x = 0; x < state.pixels[y].length; x++) { if (y < newPixels.length && x < newPixels[y].length) { newPixels[y][x] = state.pixels[y][x]; } } } emit(state.copyWith(pixels: newPixels)); } void clearSprite() { final newPixels = [ ...List.generate( state.pixels.length, (i) => List.generate(state.pixels[0].length, (j) => -1), ), ]; emit(state.copyWith(pixels: newPixels)); } @override bool shouldReplay(SpriteState state) { final eq = const ListEquality<List<int>>(ListEquality()).equals; return !eq(state.pixels, this.state.pixels); } }
mini_sprite/packages/mini_sprite_editor/lib/sprite/cubit/sprite_cubit.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/sprite/cubit/sprite_cubit.dart', 'repo_id': 'mini_sprite', 'token_count': 2372}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mini_sprite_editor/l10n/l10n.dart'; import 'package:mini_sprite_editor/workspace/workspace.dart'; class InitialPanel extends StatelessWidget { const InitialPanel({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Card( child: SizedBox( width: 100, height: 100, child: IconButton( onPressed: () { context.read<WorkspaceCubit>().openPanel( WorkspacePanel.sprite, ); }, tooltip: l10n.openSpriteEditor, icon: const Icon(Icons.brush), ), ), ), const SizedBox(width: 32), Card( child: SizedBox( width: 100, height: 100, child: IconButton( onPressed: () { context.read<WorkspaceCubit>().openPanel( WorkspacePanel.map, ); }, tooltip: l10n.openMapEditor, icon: const Icon(Icons.map), ), ), ), ], ), ); } }
mini_sprite/packages/mini_sprite_editor/lib/workspace/view/initial_panel.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/workspace/view/initial_panel.dart', 'repo_id': 'mini_sprite', 'token_count': 823}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:mini_sprite_editor/sprite/cubit/tools_cubit.dart'; import 'package:mini_sprite_editor/sprite/sprite.dart'; void main() { group('ToolsState', () { test('can be instantiated', () { expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), isNotNull, ); }); test('supports equality', () { expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), equals( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), isNot( equals( ToolsState( pixelSize: 11, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), isNot( equals( ToolsState( pixelSize: 10, tool: SpriteTool.eraser, gridActive: true, currentColor: 0, ), ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), isNot( equals( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: false, currentColor: 0, ), ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), isNot( equals( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: false, currentColor: 1, ), ), ), ); }); test('copyWith returns a new isntance with the field updated', () { expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: false, currentColor: 0, ).copyWith(pixelSize: 11), equals( ToolsState( pixelSize: 11, tool: SpriteTool.brush, gridActive: false, currentColor: 0, ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: false, currentColor: 0, ).copyWith(tool: SpriteTool.eraser), equals( ToolsState( pixelSize: 10, tool: SpriteTool.eraser, gridActive: false, currentColor: 0, ), ), ); expect( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: false, currentColor: 0, ).copyWith(gridActive: true), equals( ToolsState( pixelSize: 10, tool: SpriteTool.brush, gridActive: true, currentColor: 0, ), ), ); }); }); }
mini_sprite/packages/mini_sprite_editor/test/sprite/cubit/tools_state_test.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/test/sprite/cubit/tools_state_test.dart', 'repo_id': 'mini_sprite', 'token_count': 2125}
version: 2 jobs: build_mobx: docker: - image: google/dart environment: - FLUTTER: false - PACKAGE: mobx steps: - checkout - run: command: tool/circle_run.sh build_mobx_codegen: docker: - image: google/dart environment: - FLUTTER: false - PACKAGE: mobx_codegen steps: - checkout - run: command: tool/circle_run.sh build_mobx_codegen_example: docker: - image: google/dart environment: - FLUTTER: false - PACKAGE: mobx_codegen/example steps: - checkout - run: command: tool/circle_run.sh build_flutter_mobx: docker: - image: cirrusci/flutter environment: - FLUTTER: true - PACKAGE: flutter_mobx steps: - checkout - run: command: tool/circle_run.sh workflows: version: 2 mobx_packages: jobs: - build_mobx - build_mobx_codegen - build_mobx_codegen_example - build_flutter_mobx
mobx.dart/.circleci/config-local.yml/0
{'file_path': 'mobx.dart/.circleci/config-local.yml', 'repo_id': 'mobx.dart', 'token_count': 499}
linter: rules: - always_declare_return_types - always_put_control_body_on_new_line - always_put_required_named_parameters_first - always_require_non_null_named_parameters - annotate_overrides - avoid_annotating_with_dynamic - avoid_as - avoid_bool_literals_in_conditional_expressions - avoid_catches_without_on_clauses - avoid_catching_errors - avoid_classes_with_only_static_members - avoid_double_and_int_checks - avoid_empty_else - avoid_field_initializers_in_const_classes - avoid_function_literals_in_foreach_calls - avoid_implementing_value_types - avoid_init_to_null - avoid_js_rounded_ints - avoid_null_checks_in_equality_operators - avoid_positional_boolean_parameters - avoid_private_typedef_functions - avoid_relative_lib_imports - avoid_renaming_method_parameters - avoid_return_types_on_setters - avoid_returning_null - avoid_returning_null_for_void - avoid_returning_this - avoid_setters_without_getters - avoid_single_cascade_in_expression_statements - avoid_slow_async_io - avoid_types_as_parameter_names - avoid_unused_constructor_parameters - avoid_void_async - await_only_futures - camel_case_types - cancel_subscriptions - cascade_invocations - close_sinks - comment_references - constant_identifier_names - control_flow_in_finally - curly_braces_in_flow_control_structures - directives_ordering - empty_catches - empty_constructor_bodies - empty_statements - file_names - flutter_style_todos - hash_and_equals - implementation_imports - invariant_booleans - iterable_contains_unrelated_type - join_return_with_assignment - library_names - library_prefixes - list_remove_unrelated_type - literal_only_boolean_expressions - no_adjacent_strings_in_list - no_duplicate_case_values - non_constant_identifier_names - null_closures - omit_local_variable_types - one_member_abstracts - only_throw_errors - overridden_fields - package_api_docs - package_names - package_prefixed_library_names - parameter_assignments - prefer_adjacent_string_concatenation - prefer_asserts_in_initializer_lists - prefer_collection_literals - prefer_conditional_assignment - prefer_const_constructors - prefer_const_constructors_in_immutables - prefer_const_declarations - prefer_const_literals_to_create_immutables - prefer_constructors_over_static_methods - prefer_contains - prefer_equal_for_default_values - prefer_expression_function_bodies - prefer_final_fields - prefer_final_locals - prefer_foreach - prefer_function_declarations_over_variables - prefer_generic_function_type_aliases - prefer_initializing_formals - prefer_int_literals - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_iterable_whereType - prefer_mixin - prefer_single_quotes - prefer_typing_uninitialized_variables - prefer_void_to_null - recursive_getters - slash_for_doc_comments - sort_constructors_first - sort_pub_dependencies - sort_unnamed_constructors_first - test_types_in_equals - throw_in_finally - type_annotate_public_apis - type_init_formals - unawaited_futures - unnecessary_brace_in_string_interps - unnecessary_const - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_in_if_null_operators - unnecessary_overrides - unnecessary_parenthesis - unnecessary_statements - unnecessary_this - unrelated_type_equality_checks - use_rethrow_when_possible - use_string_buffers - use_to_and_as_if_applicable - valid_regexps - void_checks analyzer: exclude: - mobx_examples/lib/**/*.g.dart
mobx.dart/analysis_options.yaml/0
{'file_path': 'mobx.dart/analysis_options.yaml', 'repo_id': 'mobx.dart', 'token_count': 1562}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'todos.dart'; // ************************************************************************** // StoreGenerator // ************************************************************************** mixin _$Todo on TodoBase, Store { final _$descriptionAtom = Atom(name: 'TodoBase.description'); @override String get description { _$descriptionAtom.reportObserved(); return super.description; } @override set description(String value) { mainContext.checkIfStateModificationsAreAllowed(_$descriptionAtom); super.description = value; _$descriptionAtom.reportChanged(); } final _$doneAtom = Atom(name: 'TodoBase.done'); @override bool get done { _$doneAtom.reportObserved(); return super.done; } @override set done(bool value) { mainContext.checkIfStateModificationsAreAllowed(_$doneAtom); super.done = value; _$doneAtom.reportChanged(); } } mixin _$TodoList on TodoListBase, Store { Computed<ObservableList<Todo>> _$pendingTodosComputed; @override ObservableList<Todo> get pendingTodos => (_$pendingTodosComputed ??= Computed<ObservableList<Todo>>(() => super.pendingTodos)) .value; Computed<ObservableList<Todo>> _$completedTodosComputed; @override ObservableList<Todo> get completedTodos => (_$completedTodosComputed ??= Computed<ObservableList<Todo>>(() => super.completedTodos)) .value; Computed<bool> _$hasCompletedTodosComputed; @override bool get hasCompletedTodos => (_$hasCompletedTodosComputed ??= Computed<bool>(() => super.hasCompletedTodos)) .value; Computed<bool> _$hasPendingTodosComputed; @override bool get hasPendingTodos => (_$hasPendingTodosComputed ??= Computed<bool>(() => super.hasPendingTodos)) .value; Computed<String> _$itemsDescriptionComputed; @override String get itemsDescription => (_$itemsDescriptionComputed ??= Computed<String>(() => super.itemsDescription)) .value; Computed<ObservableList<Todo>> _$visibleTodosComputed; @override ObservableList<Todo> get visibleTodos => (_$visibleTodosComputed ??= Computed<ObservableList<Todo>>(() => super.visibleTodos)) .value; final _$todosAtom = Atom(name: 'TodoListBase.todos'); @override ObservableList<Todo> get todos { _$todosAtom.reportObserved(); return super.todos; } @override set todos(ObservableList<Todo> value) { mainContext.checkIfStateModificationsAreAllowed(_$todosAtom); super.todos = value; _$todosAtom.reportChanged(); } final _$filterAtom = Atom(name: 'TodoListBase.filter'); @override VisibilityFilter get filter { _$filterAtom.reportObserved(); return super.filter; } @override set filter(VisibilityFilter value) { mainContext.checkIfStateModificationsAreAllowed(_$filterAtom); super.filter = value; _$filterAtom.reportChanged(); } final _$currentDescriptionAtom = Atom(name: 'TodoListBase.currentDescription'); @override String get currentDescription { _$currentDescriptionAtom.reportObserved(); return super.currentDescription; } @override set currentDescription(String value) { mainContext.checkIfStateModificationsAreAllowed(_$currentDescriptionAtom); super.currentDescription = value; _$currentDescriptionAtom.reportChanged(); } final _$TodoListBaseActionController = ActionController(name: 'TodoListBase'); @override void addTodo(String description) { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.addTodo(description); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } @override void removeTodo(Todo todo) { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.removeTodo(todo); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } @override void changeDescription(String description) { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.changeDescription(description); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } @override void changeFilter(VisibilityFilter filter) { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.changeFilter(filter); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } @override void removeCompleted() { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.removeCompleted(); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } @override void markAllAsCompleted() { final _$actionInfo = _$TodoListBaseActionController.startAction(); try { return super.markAllAsCompleted(); } finally { _$TodoListBaseActionController.endAction(_$actionInfo); } } }
mobx.dart/mobx/example/lib/todos.g.dart/0
{'file_path': 'mobx.dart/mobx/example/lib/todos.g.dart', 'repo_id': 'mobx.dart', 'token_count': 1817}
import 'package:fake_async/fake_async.dart'; import 'package:mobx/mobx.dart'; import 'package:mobx/src/api/reaction.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'shared_mocks.dart'; import 'util.dart'; void main() { turnOffEnforceActions(); group('autorun()', () { test('basics work', () { final c = Observable(0); int nextValue; final dispose = autorun((_) { nextValue = c.value + 1; }); expect(dispose.reaction.name, startsWith('Autorun@')); expect(nextValue, equals(1)); c.value = 10; expect(nextValue, equals(11)); dispose(); // reaction should not run after this, even as dependent observables change c.value = 100; expect(nextValue, isNot(equals(101))); // Should not change expect(nextValue, equals(11)); // Remains the same as last value }); test('with 2 observables', () { final x = Observable('Hello'); final y = Observable('Pavan'); String message; final dispose = autorun((_) { message = '${x.value} ${y.value}'; }, name: 'Message Effect'); expect(message, equals('Hello Pavan')); expect(dispose.reaction.name, equals('Message Effect')); x.value = 'Hey'; expect(message, equals('Hey Pavan')); y.value = 'MobX'; expect(message, equals('Hey MobX')); dispose(); }); test('with changing observables', () { final x = Observable(10); final y = Observable(20); int value; final dispose = autorun((_) { value = (value == null) ? x.value : y.value; }); expect(value, equals(10)); x.value = 30; expect(value, equals(20)); // Should use y now dispose(); }); test('with delayed scheduler', () { Function dispose; const delayMs = 5000; final x = Observable(10); var value = 0; fakeAsync((async) { dispose = autorun((_) { value = x.value + 1; }, delay: delayMs); async.elapse(Duration(milliseconds: 2500)); expect(value, 0); // autorun() should not have executed at this time async.elapse(Duration(milliseconds: 2500)); expect(value, 11); // autorun() should have executed x.value = 100; expect(value, 11); // should still retain the last value async.elapse(Duration(milliseconds: delayMs)); expect(value, 101); // should change now }); dispose(); }); test('with pre-mature disposal in predicate', () { final x = Observable(10); final d = autorun((reaction) { final isGreaterThan10 = x.value > 10; if (isGreaterThan10) { reaction.dispose(); } }); expect(d.reaction.isDisposed, isFalse); x.value = 11; expect(d.reaction.isDisposed, isTrue); d(); }); test('fires onError on exception', () { var thrown = false; final dispose = autorun((_) { throw Exception('FAILED in autorun'); }, onError: (_, _a) { thrown = true; }); expect(thrown, isTrue); expect(dispose.reaction.errorValue, isException); dispose(); }); test('uses provided context', () { final context = MockContext(); autorun((_) {}, context: context); verify(context.runReactions()); }); test('can be disposed inside the tracking function', () { final dispose = autorun((_) { _.dispose(); }); expect(dispose.reaction.isDisposed, isTrue); }); test('can be disposed inside the tracking function with delay', () { final x = Observable(10); ReactionDisposer dispose; fakeAsync((async) { dispose = autorun((_) { final value = x.value + 1; if (value > 10) { _.dispose(); } }, delay: 1000); async.elapse(Duration(milliseconds: 1000)); x.value = 11; async.elapse(Duration(milliseconds: 1000)); expect(dispose.reaction.isDisposed, isTrue); }); }); }); }
mobx.dart/mobx/test/autorun_test.dart/0
{'file_path': 'mobx.dart/mobx/test/autorun_test.dart', 'repo_id': 'mobx.dart', 'token_count': 1741}
import 'package:fake_async/fake_async.dart'; import 'package:mobx/mobx.dart'; import 'package:mockito/mockito.dart' hide when; import 'package:test/test.dart'; import 'shared_mocks.dart'; import 'util.dart'; void main() { turnOffEnforceActions(); group('when()', () { test('basics work', () { var executed = false; final x = Observable(10); final d = when((_) => x.value > 10, () { executed = true; }, name: 'Basic when'); expect(executed, isFalse); expect(d.reaction.name, 'Basic when'); x.value = 11; expect(executed, isTrue); expect(d.reaction.isDisposed, isTrue); executed = false; x.value = 12; expect(executed, isFalse); // No more effects as its disposed }); test('with default name', () { final d = when((_) => true, () {}); expect(d.reaction.name, startsWith('When@')); d(); }); test('works with asyncWhen', () { final x = Observable(10); asyncWhen((_) => x.value > 10, name: 'Async-when').then((_) { expect(true, isTrue); }); x.value = 11; }); test('fires onError on exception', () { var thrown = false; final dispose = when( (_) { throw Exception('FAILED in when'); }, () {}, onError: (_, _a) { thrown = true; }); expect(thrown, isTrue); dispose(); }); test('exceptions inside asyncWhen are caught and reaction is disposed', () { Reaction rxn; asyncWhen((_) { rxn = _; throw Exception('FAIL'); }, name: 'Async-when') .catchError((_) { expect(rxn.isDisposed, isTrue); }); }); test('uses provided context', () { final context = MockContext(); when((_) => true, () {}, context: context); verify(context.runReactions()); }); test('throws if timeout occurs before when() completes', () { fakeAsync((async) { final x = Observable(10); var thrown = false; final d = when((_) => x.value > 10, () {}, timeout: 1000, onError: (_, _a) { thrown = true; }); async.elapse(Duration(milliseconds: 1000)); // cause a timeout expect(thrown, isTrue); expect(d.reaction.isDisposed, isTrue); d(); }); }); test('does NOT throw if when() completes before timeout', () { fakeAsync((async) { final x = Observable(10); final d = when((_) => x.value > 10, () {}, timeout: 1000); x.value = 11; expect(() { async.elapse(Duration(milliseconds: 1000)); }, returnsNormally); expect(d.reaction.isDisposed, isTrue); d(); }); }); }); }
mobx.dart/mobx/test/when_test.dart/0
{'file_path': 'mobx.dart/mobx/test/when_test.dart', 'repo_id': 'mobx.dart', 'token_count': 1248}
import 'package:mobx/mobx.dart'; import '../lib/src/generator_example.dart'; import 'package:test/test.dart'; void main() { setUp(() => mainContext.config = ReactiveConfig(enforceActions: EnforceActions.never)); tearDown(() => mainContext.config = ReactiveConfig.main); void testStoreBasics(String name, User Function() createStore) { group(name, () { test('@observable works', () { final user = createStore(); var firstName = ''; autorun((_) { firstName = user.firstName; }); expect(firstName, equals('Jane')); user.firstName = 'Jill'; expect(firstName, equals('Jill')); }); test('@computed works', () { final user = createStore(); var fullName = ''; autorun((_) { fullName = user.fullName; }); expect(fullName, equals('Jane Doe')); user.firstName = 'John'; expect(fullName, equals('John Doe')); user.lastName = 'Addams'; expect(fullName, equals('John Addams')); }); test('@action works', () { final user = createStore(); var runCount = 0; var fullName = ''; autorun((_) { runCount++; fullName = user.fullName; }); expect(fullName, equals('Jane Doe')); expect(runCount, equals(1)); user.updateNames(firstName: 'John', lastName: 'Johnson'); expect(fullName, equals('John Johnson')); expect(runCount, equals(2)); }); }); } ({'User': () => User(1), 'Admin': () => Admin(1)}).forEach(testStoreBasics); test('Admins new generated field works', () { final admin = Admin(1); var userName = ''; autorun((_) => userName = admin.userName); expect(userName, equals('admin')); admin.userName = 'root'; expect(userName, equals('root')); }); test('Admins new', () { final admin = Admin(1); var rights = ''; autorun((_) => rights = admin.accessRights.join(',')); expect(rights, equals('')); admin.accessRights = ObservableList.of(['fileshare', 'webserver']); expect(rights, equals('fileshare,webserver')); admin.accessRights.removeAt(0); expect(rights, equals('webserver')); }); }
mobx.dart/mobx_codegen/example/test/generator_example_test.dart/0
{'file_path': 'mobx.dart/mobx_codegen/example/test/generator_example_test.dart', 'repo_id': 'mobx.dart', 'token_count': 952}
import 'package:analyzer/dart/element/element.dart'; import 'package:mobx_codegen/src/template/params.dart'; import 'package:source_gen/source_gen.dart'; String surroundNonEmpty(String prefix, String suffix, dynamic content) { final contentStr = content.toString(); return contentStr.isEmpty ? '' : '$prefix$contentStr$suffix'; } final _streamChecker = TypeChecker.fromRuntime(Stream); class AsyncMethodChecker { AsyncMethodChecker([TypeChecker checkStream]) { this._checkStream = checkStream ?? _streamChecker; } TypeChecker _checkStream; bool returnsFuture(MethodElement method) => method.returnType.isDartAsyncFuture || (method.isAsynchronous && !method.isGenerator && method.returnType.isDynamic); bool returnsStream(MethodElement method) => _checkStream.isAssignableFromType(method.returnType) || (method.isAsynchronous && method.isGenerator && method.returnType.isDynamic); } TypeParamTemplate typeParamTemplate(TypeParameterElement param) => TypeParamTemplate() ..name = param.name ..bound = param.bound?.displayName;
mobx.dart/mobx_codegen/lib/src/template/util.dart/0
{'file_path': 'mobx.dart/mobx_codegen/lib/src/template/util.dart', 'repo_id': 'mobx.dart', 'token_count': 386}
import 'package:mobx/mobx.dart'; part 'todo.g.dart'; class Todo = _Todo with _$Todo; abstract class _Todo with Store { _Todo(this.description); @observable String description = ''; @observable bool done = false; @action // ignore: avoid_positional_boolean_parameters void markDone(bool flag) { done = flag; } }
mobx.dart/mobx_examples/lib/todos/todo.dart/0
{'file_path': 'mobx.dart/mobx_examples/lib/todos/todo.dart', 'repo_id': 'mobx.dart', 'token_count': 130}
name: mocktail_image_network concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: branches: - main paths: - "packages/mocktail_image_network/**" - ".github/workflows/mocktail_image_network.yaml" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_channel: stable working_directory: packages/mocktail_image_network pana: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/pana.yml@v1 with: working_directory: packages/mocktail_image_network
mocktail/.github/workflows/mocktail_image_network.yaml/0
{'file_path': 'mocktail/.github/workflows/mocktail_image_network.yaml', 'repo_id': 'mocktail', 'token_count': 251}
part of 'mocktail.dart'; /// {@template invocation_matcher} /// A [Matcher] for [Invocation] instances. /// {@endtemplate} class InvocationMatcher { /// {@macro incovation_matcher} InvocationMatcher(this.roleInvocation); /// The role invocation final Invocation roleInvocation; /// matches function which determines whether the current /// [roleInvocation] matches the provided [invocation]. bool matches(Invocation invocation) { final isMatching = _isMethodMatches(invocation) && _isArgumentsMatches(invocation); if (isMatching) { _captureArguments(invocation); } return isMatching; } bool _isMethodMatches(Invocation invocation) { if (invocation.memberName != roleInvocation.memberName) { return false; } if ((invocation.isGetter != roleInvocation.isGetter) || (invocation.isSetter != roleInvocation.isSetter) || (invocation.isMethod != roleInvocation.isMethod)) { return false; } return true; } void _captureArguments(Invocation invocation) { var index = 0; for (final roleArg in roleInvocation.positionalArguments) { final dynamic actArg = invocation.positionalArguments[index]; if (roleArg is ArgMatcher && roleArg._capture) { _capturedArgs.add(actArg); } index++; } for (final roleKey in roleInvocation.namedArguments.keys) { final dynamic roleArg = roleInvocation.namedArguments[roleKey]; final dynamic actArg = invocation.namedArguments[roleKey]; if (roleArg is ArgMatcher && roleArg._capture) { _capturedArgs.add(actArg); } } } bool _isArgumentsMatches(Invocation invocation) { if (invocation.positionalArguments.length != roleInvocation.positionalArguments.length) { return false; } if (invocation.namedArguments.length != roleInvocation.namedArguments.length) { return false; } if (invocation.typeArguments.length != roleInvocation.typeArguments.length) { return false; } var positionalArgIndex = 0; for (final roleArg in roleInvocation.positionalArguments) { final dynamic actArg = invocation.positionalArguments[positionalArgIndex]; if (!_isMatchingArg(roleArg, actArg)) { return false; } positionalArgIndex++; } var typeArgIndex = 0; for (final roleArg in roleInvocation.typeArguments) { final dynamic actArg = invocation.typeArguments[typeArgIndex]; if (!_isMatchingTypeArg(roleArg, actArg)) { return false; } typeArgIndex++; } final roleKeys = roleInvocation.namedArguments.keys.toSet(); final actKeys = invocation.namedArguments.keys.toSet(); if (roleKeys.difference(actKeys).isNotEmpty || actKeys.difference(roleKeys).isNotEmpty) { return false; } for (final roleKey in roleInvocation.namedArguments.keys) { final dynamic roleArg = roleInvocation.namedArguments[roleKey]; final dynamic actArg = invocation.namedArguments[roleKey]; if (!_isMatchingArg(roleArg, actArg)) { return false; } } return true; } bool _isMatchingArg(dynamic roleArg, dynamic actArg) { if (roleArg is ArgMatcher) { return roleArg.matcher.matches(actArg, <dynamic, dynamic>{}); } else { return equals(roleArg).matches(actArg, <dynamic, dynamic>{}); } } bool _isMatchingTypeArg(Type roleTypeArg, dynamic actTypeArg) { return roleTypeArg == actTypeArg; } }
mocktail/packages/mocktail/lib/src/_invocation_matcher.dart/0
{'file_path': 'mocktail/packages/mocktail/lib/src/_invocation_matcher.dart', 'repo_id': 'mocktail', 'token_count': 1316}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'raw_config.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** RawConfig _$RawConfigFromJson(Map json) { return $checkedNew('RawConfig', json, () { $checkKeys(json, allowedKeys: const ['dart', 'stages', 'cache']); final val = RawConfig( $checkedConvert(json, 'dart', (v) => (v as List)?.map((e) => e as String)?.toList()), $checkedConvert( json, 'stages', (v) => (v as List) ?.map((e) => e == null ? null : RawStage.fromJson(e as Map)) ?.toList()), $checkedConvert(json, 'cache', (v) => v == null ? null : RawCache.fromJson(v as Map))); return val; }, fieldKeyMap: const {'sdks': 'dart'}); } RawCache _$RawCacheFromJson(Map json) { return $checkedNew('RawCache', json, () { final val = RawCache($checkedConvert(json, 'directories', (v) => (v as List)?.map((e) => e as String)?.toList())); return val; }); }
mono_repo/mono_repo/lib/src/raw_config.g.dart/0
{'file_path': 'mono_repo/mono_repo/lib/src/raw_config.g.dart', 'repo_id': 'mono_repo', 'token_count': 468}
/// Http Service Interface abstract class HttpService { /// Http base url String get baseUrl; /// Http headers Map<String, String> get headers; /// Http get request Future<Map<String, dynamic>> get( String endpoint, { Map<String, dynamic>? queryParameters, bool forceRefresh = false, }); /// Http post request Future<dynamic> post( String endpoint, { Map<String, dynamic>? queryParameters, }); /// Http put request Future<dynamic> put(); /// Http delete request Future<dynamic> delete(); }
movies_app/lib/core/services/http/http_service.dart/0
{'file_path': 'movies_app/lib/core/services/http/http_service.dart', 'repo_id': 'movies_app', 'token_count': 175}
import 'dart:developer'; import 'package:equatable/equatable.dart'; import 'package:intl/intl.dart'; import 'package:movies_app/features/media/models/media.dart'; import 'package:movies_app/features/people/enums/gender.dart'; import 'package:movies_app/features/tmdb-configs/enums/image_size.dart'; import 'package:movies_app/features/tmdb-configs/models/tmdb_image_configs.dart'; /// Model representing a Person object /// /// See: /// https://developers.themoviedb.org/3/people/get-popular-people /// https://developers.themoviedb.org/3/people/get-person-details class Person extends Equatable { /// Creates a new instance of [Person] const Person({ this.adult = false, this.gender = Gender.unknown, this.id, this.knownFor = const [], this.knownForDepartment, this.name = '', this.popularity = 0, this.profilePath, this.avatar, this.cover, this.biography, this.birthday, this.deathDate, this.homepage, this.imdbId, this.placeOfBirth, }); /// Creates a new instance of [Person] from parsed data factory Person.fromJson(Map<String, dynamic> json) { DateTime? birthday; try { birthday = json['birthday'] == null || (json['birthday'] as String).isEmpty ? null : DateTime.parse(json['birthday'] as String); } catch (e) { log('Error parsing birthday date! ${json['birthday']}'); } DateTime? deathDate; try { deathDate = json['deathday'] == null || (json['deathday'] as String).isEmpty ? null : DateTime.parse(json['deathday'] as String); } catch (e) { log('Error parsing deathDate date! ${json['deathday']}'); } return Person( adult: (json['adult'] as bool?) ?? false, gender: json['gender'] == null ? Gender.unknown : Gender.fromInt(json['gender'] as int), id: json['id'] as int?, knownFor: json['known_for'] == null ? [] : List<Media>.from( (json['known_for'] as List<dynamic>).map<Media>( (dynamic x) => Media.fromJson(x as Map<String, dynamic>), ), ), knownForDepartment: json['known_for_department'] as String?, name: json['name'] as String, popularity: (json['popularity'] as num?)?.toDouble() ?? 0.0, profilePath: json['profile_path'] as String?, biography: json['biography'] as String?, birthday: birthday, deathDate: deathDate, homepage: json['homepage'] as String?, imdbId: json['imdb_id'] as String?, placeOfBirth: json['place_of_birth'] as String?, ); } /// Indicates if the content of this person is +18 final bool adult; /// Person gender final Gender gender; /// Person id final int? id; /// Person media list final List<Media> knownFor; /// Person departments final String? knownForDepartment; /// Person name final String name; /// Person popularity final double popularity; /// Person profile path /// /// Used with [TMDBImageConfigs] to generate valid [avatar] & [cover] final String? profilePath; /// Generated avatar image from [TMDBImageConfigs] & [profilePath] final String? avatar; /// Generated cover image from [TMDBImageConfigs] & [profilePath] final String? cover; /// Person biography final String? biography; /// Person birthday final DateTime? birthday; /// Person death date if applicable final DateTime? deathDate; /// Person homepage if applicable final String? homepage; /// Person IMDB id final String? imdbId; /// Person place of borth final String? placeOfBirth; /// Default avatar image size static ImageSize avatarSize = ImageSize.h632; /// Default avatar cover image size static ImageSize coverSize = ImageSize.original; /// Converts object to raw data Map<String, dynamic> toJson() { return <String, dynamic>{ 'adult': adult, 'gender': gender.toInt, 'id': id, 'known_for': List<dynamic>.from( knownFor.map<Map<String, dynamic>>((x) => x.toJson()), ), 'known_for_department': knownForDepartment, 'name': name, 'popularity': popularity, 'profile_path': profilePath, 'biography': biography, 'birthday': birthday == null ? null : DateFormat('yyyy-MM-dd').format(birthday!), 'deathday': deathDate == null ? null : DateFormat('yyyy-MM-dd').format(deathDate!), 'homepage': homepage, 'imdb_id': imdbId, 'place_of_birth': placeOfBirth, }; } // Todo: to preserve clean architecture, // this should be handled in an entity not the data source model, // but it's done this way due to time limitation /// Populate the [avatar] and [cover] with generated /// valid images from the [TMDBImageConfigs] build image methods Person populateImages(TMDBImageConfigs imageConfigs) { return Person( adult: adult, gender: gender, id: id, knownFor: knownFor.map((media) => media.populateImages(imageConfigs)).toList(), knownForDepartment: knownForDepartment, name: name, popularity: popularity, profilePath: profilePath, avatar: profilePath == null ? null : imageConfigs.buildProfileImage(avatarSize, profilePath!), cover: profilePath == null ? null : imageConfigs.buildProfileImage(coverSize, profilePath!), biography: biography, birthday: birthday, deathDate: deathDate, homepage: homepage, imdbId: imdbId, placeOfBirth: placeOfBirth, ); } @override List<Object?> get props => [ adult, gender, id, knownFor, knownForDepartment, name, popularity, profilePath, avatar, cover, biography, birthday, deathDate, homepage, imdbId, placeOfBirth, ]; }
movies_app/lib/features/people/models/person.dart/0
{'file_path': 'movies_app/lib/features/people/models/person.dart', 'repo_id': 'movies_app', 'token_count': 2351}
import 'package:flutter/material.dart'; import 'package:movies_app/core/widgets/app_bar_leading.dart'; import 'package:movies_app/features/people/enums/gender.dart'; import 'package:movies_app/features/people/views/widgets/person_cover.dart'; /// Person details page Sliver AppBar widget class PersonDetailsSliverAppBar extends StatelessWidget { /// Creates a new instance of [PersonDetailsSliverAppBar] const PersonDetailsSliverAppBar({ super.key, this.avatar, this.gender = Gender.unknown, required this.personId, }); /// Id of the person being previewed final int personId; /// Avatar of the person /// used for the Hero animation final String? avatar; /// Gender of the person /// /// This is used to show female/male/unknown placeholder images: /// assets/images/placeholder-female.png /// assets/images/placeholder-male.png /// assets/images/placeholder-unknown.png final Gender gender; @override Widget build(BuildContext context) { return SliverAppBar( expandedHeight: MediaQuery.of(context).size.height * 0.35, collapsedHeight: 100, leadingWidth: 70, backgroundColor: Colors.transparent, leading: const AppBarLeading(), pinned: true, flexibleSpace: Padding( padding: const EdgeInsetsDirectional.only(start: 40), child: Hero( tag: 'person_${personId}_profile_picture', transitionOnUserGestures: true, child: ClipRRect( borderRadius: const BorderRadius.only( bottomLeft: Radius.circular(50), ), child: PersonCover( avatar, gender: gender, height: double.infinity, ), ), ), ), ); } }
movies_app/lib/features/people/views/widgets/person_details_sliver_app_bar.dart/0
{'file_path': 'movies_app/lib/features/people/views/widgets/person_details_sliver_app_bar.dart', 'repo_id': 'movies_app', 'token_count': 687}
import 'package:movies_app/core/configs/configs.dart'; import 'package:movies_app/core/services/http/http_service.dart'; import 'package:movies_app/features/tmdb-configs/models/tmdb_configs.dart'; import 'package:movies_app/features/tmdb-configs/repositories/tmdb_configs_repository.dart'; /// Http implementation of [TMDBConfigsRepository] /// /// See: https://developers.themoviedb.org/3/configuration/get-api-configuration class HttpTMDBConfigsRepository implements TMDBConfigsRepository { /// Creates a new instance of [HttpTMDBConfigsRepository] HttpTMDBConfigsRepository(this.httpService); /// Http service used to access an Http client and make calls final HttpService httpService; @override String get path => '/configuration'; @override String get apiKey => Configs.tmdbAPIKey; @override Future<TMDBConfigs> get({bool forceRefresh = false}) async { final response = await httpService.get( path, queryParameters: <String, dynamic>{ 'api_key': apiKey, }, forceRefresh: forceRefresh, ); return TMDBConfigs.fromJson(response); } }
movies_app/lib/features/tmdb-configs/repositories/http_tmdb_configs_repository.dart/0
{'file_path': 'movies_app/lib/features/tmdb-configs/repositories/http_tmdb_configs_repository.dart', 'repo_id': 'movies_app', 'token_count': 408}
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:movies_app/features/people/models/person.dart'; import 'package:movies_app/features/people/providers/person_details_provider.dart'; import 'package:movies_app/features/people/repositories/people_repository.dart'; import 'package:movies_app/features/tmdb-configs/providers/tmdb_configs_provider.dart'; import '../../../test-utils/dummy-data/dummy_configs.dart'; import '../../../test-utils/dummy-data/dummy_people.dart'; import '../../../test-utils/mocks.dart'; void main() { final PeopleRepository mockPeopleRepository = MockPeopleRepository(); setUp(() { when( () => mockPeopleRepository.getPersonDetails( DummyPeople.person1.id!, forceRefresh: false, imageConfigs: DummyConfigs.imageConfigs, ), ).thenAnswer((_) async => DummyPeople.person1); }); test('fetches person details', () async { final personListener = Listener<AsyncValue<Person>>(); final providerContainer = ProviderContainer( overrides: [ peopleRepositoryProvider.overrideWithValue(mockPeopleRepository), tmdbConfigsProvider.overrideWithProvider(dummyTmdbConfigsProvider), ], ); addTearDown(providerContainer.dispose); providerContainer.listen<AsyncValue<Person>>( personDetailsProvider(DummyPeople.person1.id!), personListener, fireImmediately: true, ); // Perform first reading, expects loading state final firstReading = providerContainer.read(personDetailsProvider(DummyPeople.person1.id!)); expect(firstReading, const AsyncValue<Person>.loading()); // Listener was fired from `null` to loading AsyncValue verify( () => personListener( null, const AsyncValue<Person>.loading(), ), ).called(1); // Perform second reading, by waiting for the request, expects fetched data final secondReading = await providerContainer .read(personDetailsProvider(DummyPeople.person1.id!).future); expect(secondReading, DummyPeople.person1); // Listener was fired from loading to fetched values verify( () => personListener( const AsyncValue<Person>.loading(), AsyncValue<Person>.data(DummyPeople.person1), ), ).called(1); // No more further listener events fired verifyNoMoreInteractions(personListener); }); }
movies_app/test/features/people/providers/person_details_provider_test.dart/0
{'file_path': 'movies_app/test/features/people/providers/person_details_provider_test.dart', 'repo_id': 'movies_app', 'token_count': 886}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:movies_app/core/widgets/error_view.dart'; import 'package:movies_app/features/people/models/person.dart'; import 'package:movies_app/features/people/providers/current_popular_person_provider.dart'; import 'package:movies_app/features/people/views/pages/person_details_page.dart'; import 'package:movies_app/features/people/views/widgets/popular_person_list_item.dart'; import '../../../../test-utils/dummy-data/dummy_people.dart'; import '../../../../test-utils/pump_app.dart'; void main() { testWidgets( 'renders ErrorView on FormatException', (WidgetTester tester) async { await tester.pumpProviderApp( const PopularPersonListItem(), overrides: [ currentPopularPersonProvider.overrideWithProvider( Provider<AsyncValue<Person>>( (ref) => throw const FormatException(), ), ), ], ); await tester.pumpAndSettle(); expect(find.byType(ErrorView), findsOneWidget); }, // Todo: make this test work skip: true, ); testWidgets('renders person data', (WidgetTester tester) async { await tester.pumpProviderApp( const Material( child: PopularPersonListItem(), ), overrides: [ currentPopularPersonProvider.overrideWithValue( AsyncValue.data(Person.fromJson(DummyPeople.rawPerson1)), ), ], ); await tester.pumpAndSettle(); expect(find.text(DummyPeople.person1.name), findsOneWidget); }); testWidgets('navigates to person details page', (WidgetTester tester) async { await tester.pumpProviderApp( const Material( child: PopularPersonListItem(), ), overrides: [ currentPopularPersonProvider.overrideWithValue( AsyncValue.data(Person.fromJson(DummyPeople.rawPerson1)), ), ], ); await tester.pumpAndSettle(); final inkWell = find.byType(InkWell); expect(inkWell, findsOneWidget); await tester.tap(inkWell); await tester.pumpAndSettle(); expect(find.byType(PersonDetailsPage), findsOneWidget); }); }
movies_app/test/features/people/views/widgets/popular_person_list_item_test.dart/0
{'file_path': 'movies_app/test/features/people/views/widgets/popular_person_list_item_test.dart', 'repo_id': 'movies_app', 'token_count': 900}
import 'src/template.dart' as t; /// A Template can be efficiently rendered multiple times with different /// values. abstract class Template { /// The constructor parses the template source and throws [TemplateException] /// if the syntax of the source is invalid. /// Tag names may only contain characters a-z, A-Z, 0-9, underscore, and minus, /// unless lenient mode is specified. factory Template(String source, {bool lenient, bool htmlEscapeValues, String name, PartialResolver? partialResolver, String delimiters}) = t.Template.fromSource; String? get name; String get source; /// [values] can be a combination of Map, List, String. Any non-String object /// will be converted using toString(). Null values will cause a /// [TemplateException], unless lenient module is enabled. String renderString(values); /// [values] can be a combination of Map, List, String. Any non-String object /// will be converted using toString(). Null values will cause a /// [TemplateException], unless lenient module is enabled. void render(values, StringSink sink); } typedef PartialResolver = Template? Function(String); typedef LambdaFunction = Object Function(LambdaContext context); /// Passed as an argument to a mustache lambda function. The methods on /// this object may only be called before the lambda function returns. If a /// method is called after it has returned an exception will be thrown. abstract class LambdaContext { /// Render the current section tag in the current context and return the /// result as a string. If provided, value will be added to the top of the /// context's stack. String renderString({Object? value}); /// Render and directly output the current section tag. If provided, value /// will be added to the top of the context's stack. void render({Object value}); /// Output a string. The output will not be html escaped, and will be written /// before the output returned from the lambda. void write(Object object); /// Get the unevaluated template source for the current section tag. String get source; /// Evaluate the string as a mustache template using the current context. If /// provided, value will be added to the top of the context's stack. String renderSource(String source, {Object? value}); /// Lookup the value of a variable in the current context. Object? lookup(String variableName); } /// [TemplateException] is used to obtain the line and column numbers /// of the token which caused parse or render to fail. abstract class TemplateException implements Exception { /// A message describing the problem parsing or rendering the template. String get message; /// The name used to identify the template, as passed to the Template /// constructor. String? get templateName; /// The 1-based line number of the token where formatting error was found. int get line; /// The 1-based column number of the token where formatting error was found. int get column; /// The character offset within the template source. int? get offset; /// The template source. String? get source; /// A short source substring of the source at the point the problem occurred /// with parsing or rendering. String get context; }
mustache/lib/mustache.dart/0
{'file_path': 'mustache/lib/mustache.dart', 'repo_id': 'mustache', 'token_count': 825}
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:flutter_html/style.dart'; import 'package:hacker_news_vanilla/src/error_view.dart'; import 'package:hacker_news_vanilla/src/models/item.dart'; import 'package:hacker_news_vanilla/src/news_repository.dart'; import 'package:url_launcher/url_launcher.dart'; class ItemView extends StatefulWidget { final int id; final NewsRepository repository; const ItemView({ Key key, @required this.id, @required this.repository, }) : super(key: key); @override _ItemViewState createState() => _ItemViewState(); } class _ItemViewState extends State<ItemView> { Future<Item> _item; @override void initState() { _item = widget.repository.item(widget.id); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).itemTitle), ), body: FutureBuilder<Item>( future: _item, builder: (context, snapshot) { if (snapshot.hasData) { final item = snapshot.data; return ListView( padding: EdgeInsets.all(16), children: [ Text(item.title, style: Theme.of(context).textTheme.headline3), SizedBox(height: 16), Text( AppLocalizations.of(context).commentCount(item.commentsCount), style: Theme.of(context).textTheme.headline5, ), SizedBox(height: 8), for (final comment in item.comments) ..._buildComments(comment, 0) ], ); } else if (snapshot.hasError) { return ErrorView( message: AppLocalizations.of(context).itemLoadingError, ); } return Center(child: CircularProgressIndicator()); }, ), ); } List<Widget> _buildComments(Item comment, int indentationLevel) { return [ _CommentView( comment: comment, indentationLevel: indentationLevel, ), if (comment.comments.isNotEmpty) for (final comment in comment.comments) ..._buildComments(comment, indentationLevel + 1) ]; } } class _CommentView extends StatelessWidget { final Item comment; final int indentationLevel; const _CommentView({ Key key, @required this.comment, @required this.indentationLevel, }) : super(key: key); @override Widget build(BuildContext context) { Widget widget = Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( comment.user ?? AppLocalizations.of(context).deleted, style: Theme.of(context).textTheme.subtitle1, ), SizedBox(height: 12), Html( style: { 'body': Style(margin: EdgeInsets.zero), 'p': Style( padding: EdgeInsets.all(0), margin: EdgeInsets.only(bottom: 12), ), }, data: comment.content, onLinkTap: (url) async { if (await canLaunch(url)) { await launch(url); } }, ), SizedBox(height: 8), ], ); if (indentationLevel > 0) { widget = Padding( padding: EdgeInsets.only(left: 20), child: widget, ); } return widget; } }
new_flutter_template/evaluations/hacker_news_vanilla/lib/src/item_view.dart/0
{'file_path': 'new_flutter_template/evaluations/hacker_news_vanilla/lib/src/item_view.dart', 'repo_id': 'new_flutter_template', 'token_count': 1624}
import 'package:journal_clean_architecture/domain/entities/app_theme.dart'; import 'package:journal_clean_architecture/domain/repositories/user_settings_repository.dart'; class UserSettingsService { final UserSettingsRepository repository; UserSettingsService(this.repository); Future<AppTheme> get theme => repository.theme(); Future<void> updateTheme(AppTheme theme) => repository.updateTheme(theme); Future<String> get locale => repository.locale(); Future<void> updateLocale(String locale) => repository.updateLocale(locale); }
new_flutter_template/evaluations/journal_clean_architecture/lib/domain/services/user_settings_service.dart/0
{'file_path': 'new_flutter_template/evaluations/journal_clean_architecture/lib/domain/services/user_settings_service.dart', 'repo_id': 'new_flutter_template', 'token_count': 158}
import 'package:flutter/cupertino.dart'; import 'package:journal_clean_architecture/domain/entities/app_theme.dart'; import 'package:journal_clean_architecture/domain/services/user_settings_service.dart'; class UserSettingsController with ChangeNotifier { final UserSettingsService service; UserSettingsController(this.service); AppTheme _theme; String _locale; AppTheme get theme => _theme; String get locale => _locale ?? 'en'; Future<void> loadUserSettings() async { _theme = await service.theme; _locale = await service.locale; } Future<void> updateTheme(AppTheme newTheme) async { _theme = newTheme; await service.updateTheme(_theme); notifyListeners(); } Future<void> updateLocale(String newLocale) async { _locale = newLocale; await service.updateLocale(newLocale); notifyListeners(); } }
new_flutter_template/evaluations/journal_clean_architecture/lib/ui/user_settings_controller.dart/0
{'file_path': 'new_flutter_template/evaluations/journal_clean_architecture/lib/ui/user_settings_controller.dart', 'repo_id': 'new_flutter_template', 'token_count': 279}
import 'dart:convert'; import 'package:journal_mvc/src/user_settings/models/user_settings.dart'; import 'package:shared_preferences/shared_preferences.dart'; class UserSettingsRepository { final SharedPreferences preferences; final String storageKey; UserSettingsRepository( this.preferences, { this.storageKey = '__userSettingsStorageKey', }); Future<void> updateSettings(UserSettings settings) => preferences.setString(storageKey, json.encode(settings.toJson())); Future<UserSettings> loadSettings() async { return UserSettings.fromJson( json.decode(preferences.getString(storageKey) ?? '{}'), ); } }
new_flutter_template/evaluations/journal_mvc/lib/src/user_settings/repositories/user_settings_repository.dart/0
{'file_path': 'new_flutter_template/evaluations/journal_mvc/lib/src/user_settings/repositories/user_settings_repository.dart', 'repo_id': 'new_flutter_template', 'token_count': 215}
import 'package:flutter/material.dart'; import 'package:list_detail_mvc_dummy/src/dummy_details_view.dart'; import 'package:list_detail_mvc_dummy/src/dummy_list_controller.dart'; import 'package:list_detail_mvc_dummy/src/dummy_list_view.dart'; import 'package:list_detail_mvc_dummy/src/dummy_repository.dart'; void main() async { // Setup Repositories which are responsible for storing and retrieving data final repository = DummyRepository(); // Setup Controllers which bind Data Storage (Repositories) to Flutter // Widgets. final controller = DummyController(repository); runApp(DummyListApp(controller: controller)); } class DummyListApp extends StatelessWidget { final DummyController controller; const DummyListApp({Key key, @required this.controller}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'List/Detail Demo', theme: ThemeData.dark(), initialRoute: '/', onGenerateRoute: (settings) { switch (settings.name) { case '/users': return MaterialPageRoute(builder: (_) => DummyDetailsPage()); case '/': default: return MaterialPageRoute( builder: (_) => DummyListPage(controller: controller), ); } }, ); } }
new_flutter_template/evaluations/list_detail_mvc_dummy/lib/main.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_dummy/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 491}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/all.dart'; import 'package:list_detail_mvc_riverpod/src/app.dart'; void main() { runApp( ProviderScope( child: MyApp(), ), ); }
new_flutter_template/evaluations/list_detail_mvc_riverpod/lib/main.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_riverpod/lib/main.dart', 'repo_id': 'new_flutter_template', 'token_count': 90}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:list_detail_mvc_vn_prettier/src/users/user.dart'; import 'package:list_detail_mvc_vn_prettier/src/users/user_avatar.dart'; import 'package:list_detail_mvc_vn_prettier/src/users/user_details_view.dart'; import 'package:list_detail_mvc_vn_prettier/src/users/user_list_controller.dart'; import 'package:list_detail_mvc_vn_prettier/src/users/user_list_model.dart'; class UserListView extends StatefulWidget { final UserController controller; const UserListView({Key key, @required this.controller}) : super(key: key); @override _UserListViewState createState() => _UserListViewState(); } class _UserListViewState extends State<UserListView> { @override void initState() { // Begin loading the users when the User List is first shown. widget.controller.loadUsers(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('User List'), actions: [ IconButton( icon: Icon(Icons.settings), onPressed: () { Navigator.pushNamed(context, '/settings'); }, ) ], ), body: ValueListenableBuilder<UserListModel>( valueListenable: widget.controller, builder: (context, model, _) { if (model.loading) { return Center(child: CircularProgressIndicator()); } else if (model.error) { return Center(child: Text('Oh no! Could not load the users')); } return ListView.builder( itemCount: model.users.length, itemBuilder: (context, index) { var user = model.users[index]; return Dismissible( key: ObjectKey(user), onDismissed: (_) => widget.controller.removeUser(user), background: Container(color: Colors.red), child: ListTile( leading: UserAvatar(color: user.color), title: Text('User #${user.id}'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (_) => UserDetailsView(user: user), ), ); }, ), ); }, ); }, ), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () { widget.controller.addUser(User(Random().nextInt(1000))); }, ), ); } }
new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user_list_view.dart/0
{'file_path': 'new_flutter_template/evaluations/list_detail_mvc_vn_prettier/lib/src/users/user_list_view.dart', 'repo_id': 'new_flutter_template', 'token_count': 1273}
include: package:pedantic/analysis_options.yaml
new_flutter_template/evaluations/list_detail_with_some_boilerplate/analysis_options.yaml/0
{'file_path': 'new_flutter_template/evaluations/list_detail_with_some_boilerplate/analysis_options.yaml', 'repo_id': 'new_flutter_template', 'token_count': 14}
import 'dart:io'; class Sample { final String name; final String path; Sample(String path) : name = path.split('/').last, path = '$path/lib'; } class Output { final String name; final int lineCount; Output(this.name, this.lineCount); @override String toString() { return 'Output{name: $name, lineCount: $lineCount}'; } } void main(List<String> args) { final samples = [ for (final entity in Directory(args.first).listSync()) if (entity is Directory) Sample(entity.path) ]; final outputs = samples.map<Output>((sample) { return Output( sample.name, _countLines(sample.path), ); }).toList(growable: false) ..sort((a, b) => a.lineCount - b.lineCount); final strings = outputs .map<String>((output) => '| ${output.name} | ${output.lineCount} |') .join('\n'); print(''' # Line Counts for ${args.first[0].toUpperCase() + args.first.substring(1)} Though not the only factor or even most important factor, can help us see which samples add a lot of code. Please note: This is not an exercise in code golf. The line counts are meant to be direct apples-to-apples comparisons. | *Sample* | *LOC (no comments)* | |--------|-------------------| $strings '''); } int _countLines(String path) { final dartFiles = _findDartFiles(path); return dartFiles.fold(0, (count, file) { final nonCommentsLineCount = file .readAsLinesSync() .where((line) => !line.startsWith('//') && line.trim().isNotEmpty) .length; return count + nonCommentsLineCount; }); } List<File> _findDartFiles(String path) { final paths = Directory(path) .listSync(recursive: true) .whereType<File>() .map((file) => file.path) .where((path) => path.endsWith('.dart') && !path.endsWith('.g.dart') && !path.contains('todos_repository') && !path.contains('file_storage') && !path.contains('web_client') && !path.contains('main_')) .toSet(); return List.unmodifiable(paths.map<File>((path) => File(path))); }
new_flutter_template/tool/evaluation_line_counter.dart/0
{'file_path': 'new_flutter_template/tool/evaluation_line_counter.dart', 'repo_id': 'new_flutter_template', 'token_count': 826}
name: permission_client concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - "flutter_news_example/packages/permission_client/**" - ".github/workflows/permission_client.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/permission_client
news_toolkit/.github/workflows/permission_client.yaml/0
{'file_path': 'news_toolkit/.github/workflows/permission_client.yaml', 'repo_id': 'news_toolkit', 'token_count': 197}
import 'dart:convert'; import 'dart:io'; import 'package:flutter_news_example_api/client.dart'; import 'package:http/http.dart' as http; /// {@template flutter_news_example_api_malformed_response} /// An exception thrown when there is a problem decoded the response body. /// {@endtemplate} class FlutterNewsExampleApiMalformedResponse implements Exception { /// {@macro flutter_news_example_api_malformed_response} const FlutterNewsExampleApiMalformedResponse({required this.error}); /// The associated error. final Object error; } /// {@template flutter_news_example_api_request_failure} /// An exception thrown when an http request failure occurs. /// {@endtemplate} class FlutterNewsExampleApiRequestFailure implements Exception { /// {@macro flutter_news_example_api_request_failure} const FlutterNewsExampleApiRequestFailure({ required this.statusCode, required this.body, }); /// The associated http status code. final int statusCode; /// The associated response body. final Map<String, dynamic> body; } /// Signature for the authentication token provider. typedef TokenProvider = Future<String?> Function(); /// {@template flutter_news_example_api_client} /// A Dart API client for the Flutter News Example API. /// {@endtemplate} class FlutterNewsExampleApiClient { /// Create an instance of [FlutterNewsExampleApiClient] that integrates /// with the remote API. /// /// {@macro flutter_news_example_api_client} FlutterNewsExampleApiClient({ required TokenProvider tokenProvider, http.Client? httpClient, }) : this._( baseUrl: 'https://example-api.a.run.app', httpClient: httpClient, tokenProvider: tokenProvider, ); /// Create an instance of [FlutterNewsExampleApiClient] that integrates /// with a local instance of the API (http://localhost:8080). /// /// {@macro flutter_news_example_api_client} FlutterNewsExampleApiClient.localhost({ required TokenProvider tokenProvider, http.Client? httpClient, }) : this._( baseUrl: 'http://localhost:8080', httpClient: httpClient, tokenProvider: tokenProvider, ); /// {@macro flutter_news_example_api_client} FlutterNewsExampleApiClient._({ required String baseUrl, required TokenProvider tokenProvider, http.Client? httpClient, }) : _baseUrl = baseUrl, _httpClient = httpClient ?? http.Client(), _tokenProvider = tokenProvider; final String _baseUrl; final http.Client _httpClient; final TokenProvider _tokenProvider; /// GET /api/v1/articles/<id> /// Requests article content metadata. /// /// Supported parameters: /// * [id] - Article id for which content is requested. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. /// * [preview] - Whether to return a preview of the article. Future<ArticleResponse> getArticle({ required String id, int? limit, int? offset, bool preview = false, }) async { final uri = Uri.parse('$_baseUrl/api/v1/articles/$id').replace( queryParameters: <String, String>{ if (limit != null) 'limit': '$limit', if (offset != null) 'offset': '$offset', 'preview': '$preview', }, ); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return ArticleResponse.fromJson(body); } /// GET /api/v1/articles/<id>/related /// Requests related articles. /// /// Supported parameters: /// * [id] - Article id for which related content is requested. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. Future<RelatedArticlesResponse> getRelatedArticles({ required String id, int? limit, int? offset, }) async { final uri = Uri.parse('$_baseUrl/api/v1/articles/$id/related').replace( queryParameters: <String, String>{ if (limit != null) 'limit': '$limit', if (offset != null) 'offset': '$offset', }, ); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return RelatedArticlesResponse.fromJson(body); } /// GET /api/v1/feed /// Requests news feed metadata. /// /// Supported parameters: /// * [category] - The desired news [Category]. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. Future<FeedResponse> getFeed({ Category? category, int? limit, int? offset, }) async { final uri = Uri.parse('$_baseUrl/api/v1/feed').replace( queryParameters: <String, String>{ if (category != null) 'category': category.name, if (limit != null) 'limit': '$limit', if (offset != null) 'offset': '$offset', }, ); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return FeedResponse.fromJson(body); } /// GET /api/v1/categories /// Requests the available news categories. Future<CategoriesResponse> getCategories() async { final uri = Uri.parse('$_baseUrl/api/v1/categories'); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return CategoriesResponse.fromJson(body); } /// GET /api/v1/users/me /// Requests the current user. Future<CurrentUserResponse> getCurrentUser() async { final uri = Uri.parse('$_baseUrl/api/v1/users/me'); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return CurrentUserResponse.fromJson(body); } /// GET /api/v1/search/popular /// Requests current, popular content. Future<PopularSearchResponse> popularSearch() async { final uri = Uri.parse('$_baseUrl/api/v1/search/popular'); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return PopularSearchResponse.fromJson(body); } /// GET /api/v1/search/relevant?q=term /// Requests relevant content based on the provided search [term]. Future<RelevantSearchResponse> relevantSearch({required String term}) async { final uri = Uri.parse('$_baseUrl/api/v1/search/relevant').replace( queryParameters: <String, String>{'q': term}, ); final response = await _httpClient.get( uri, headers: await _getRequestHeaders(), ); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: body, statusCode: response.statusCode, ); } return RelevantSearchResponse.fromJson(body); } /// POST /api/v1/newsletter/subscription /// Subscribes the provided [email] to the newsletter. Future<void> subscribeToNewsletter({required String email}) async { final uri = Uri.parse('$_baseUrl/api/v1/newsletter/subscription'); final response = await _httpClient.post( uri, headers: await _getRequestHeaders(), body: json.encode(<String, String>{'email': email}), ); if (response.statusCode != HttpStatus.created) { throw FlutterNewsExampleApiRequestFailure( body: const <String, dynamic>{}, statusCode: response.statusCode, ); } } /// POST /api/v1/subscriptions /// Creates a new subscription for the associated user. Future<void> createSubscription({ required String subscriptionId, }) async { final uri = Uri.parse('$_baseUrl/api/v1/subscriptions').replace( queryParameters: <String, String>{'subscriptionId': subscriptionId}, ); final response = await _httpClient.post( uri, headers: await _getRequestHeaders(), ); if (response.statusCode != HttpStatus.created) { throw FlutterNewsExampleApiRequestFailure( body: const <String, dynamic>{}, statusCode: response.statusCode, ); } } /// GET /api/v1/subscriptions /// Requests a list of all available subscriptions. Future<SubscriptionsResponse> getSubscriptions() async { final uri = Uri.parse('$_baseUrl/api/v1/subscriptions'); final response = await _httpClient.get(uri); final body = response.json(); if (response.statusCode != HttpStatus.ok) { throw FlutterNewsExampleApiRequestFailure( body: const <String, dynamic>{}, statusCode: response.statusCode, ); } return SubscriptionsResponse.fromJson(body); } Future<Map<String, String>> _getRequestHeaders() async { final token = await _tokenProvider(); return <String, String>{ HttpHeaders.contentTypeHeader: ContentType.json.value, HttpHeaders.acceptHeader: ContentType.json.value, if (token != null) HttpHeaders.authorizationHeader: 'Bearer $token', }; } } extension on http.Response { Map<String, dynamic> json() { try { final decodedBody = utf8.decode(bodyBytes); return jsonDecode(decodedBody) as Map<String, dynamic>; } catch (error, stackTrace) { Error.throwWithStackTrace( FlutterNewsExampleApiMalformedResponse(error: error), stackTrace, ); } } }
news_toolkit/flutter_news_example/api/lib/src/client/flutter_news_example_api_client.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/client/flutter_news_example_api_client.dart', 'repo_id': 'news_toolkit', 'token_count': 3801}
export 'news_data_source_provider.dart'; export 'user_provider.dart';
news_toolkit/flutter_news_example/api/lib/src/middleware/middleware.dart/0
{'file_path': 'news_toolkit/flutter_news_example/api/lib/src/middleware/middleware.dart', 'repo_id': 'news_toolkit', 'token_count': 26}