code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/behaviors/ball_spawning_behavior.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.load(theme.Assets.images.dash.ball.keyName); } Future<void> pump( List<Component> children, { GameBloc? gameBloc, }) async { await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc ?? GameBloc(), ), FlameBlocProvider<CharacterThemeCubit, CharacterThemeState>.value( value: CharacterThemeCubit(), ), ], children: children, ), ); } } class _MockGameState extends Mock implements GameState {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group( 'BallSpawningBehavior', () { final flameTester = FlameTester(_TestGame.new); test('can be instantiated', () { expect( BallSpawningBehavior(), isA<BallSpawningBehavior>(), ); }); flameTester.test( 'loads', (game) async { final behavior = BallSpawningBehavior(); await game.pump([behavior]); expect(game.descendants(), contains(behavior)); }, ); group('listenWhen', () { test( 'never listens when new state not playing', () { final waiting = const GameState.initial() ..copyWith(status: GameStatus.waiting); final gameOver = const GameState.initial() ..copyWith(status: GameStatus.gameOver); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(_MockGameState(), waiting), isFalse); expect(behavior.listenWhen(_MockGameState(), gameOver), isFalse); }, ); test( 'listens when started playing', () { final waiting = const GameState.initial().copyWith(status: GameStatus.waiting); final playing = const GameState.initial().copyWith(status: GameStatus.playing); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(waiting, playing), isTrue); }, ); test( 'listens when lost rounds', () { final playing1 = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 2, ); final playing2 = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 1, ); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(playing1, playing2), isTrue); }, ); test( "doesn't listen when didn't lose any rounds", () { final playing = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 2, ); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(playing, playing), isFalse); }, ); }); flameTester.test( 'onNewState adds a ball', (game) async { final behavior = BallSpawningBehavior(); await game.pump([ behavior, ZCanvasComponent(), Plunger.test(), ]); expect(game.descendants().whereType<Ball>(), isEmpty); behavior.onNewState(_MockGameState()); await game.ready(); expect(game.descendants().whereType<Ball>(), isNotEmpty); }, ); }, ); }
pinball/test/game/behaviors/ball_spawning_behavior_test.dart/0
{'file_path': 'pinball/test/game/behaviors/ball_spawning_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 1927}
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.android.ramp.boardOpening.keyName, Assets.images.android.ramp.railingForeground.keyName, Assets.images.android.ramp.railingBackground.keyName, Assets.images.android.ramp.main.keyName, Assets.images.android.ramp.arrow.inactive.keyName, Assets.images.android.ramp.arrow.active1.keyName, Assets.images.android.ramp.arrow.active2.keyName, Assets.images.android.ramp.arrow.active3.keyName, Assets.images.android.ramp.arrow.active4.keyName, Assets.images.android.ramp.arrow.active5.keyName, Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, Assets.images.score.fiveThousand.keyName, ]); } Future<void> pump( SpaceshipRamp child, { required GameBloc gameBloc, required SpaceshipRampCubit bloc, }) async { await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, ), FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value( value: bloc, ), ], children: [ ZCanvasComponent(children: [child]), ], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {} class _FakeGameEvent extends Fake implements GameEvent {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('RampMultiplierBehavior', () { late GameBloc gameBloc; setUp(() { registerFallbackValue(_FakeGameEvent()); gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.test( 'adds MultiplierIncreased ' 'when hits are multiples of 5 times and multiplier is less than 6', (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 5, ), ); when(() => gameBloc.add(any())).thenAnswer((_) async {}); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 5)); await Future<void>.delayed(Duration.zero); verify(() => gameBloc.add(const MultiplierIncreased())).called(1); }, ); flameTester.test( "doesn't add MultiplierIncreased " 'when hits are multiples of 5 times but multiplier is 6', (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 6, ), ); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 5)); await Future<void>.delayed(Duration.zero); verifyNever(() => gameBloc.add(const MultiplierIncreased())); }, ); flameTester.test( "doesn't add MultiplierIncreased " "when hits aren't multiples of 5 times", (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 5, ), ); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 1)); await game.ready(); verifyNever(() => gameBloc.add(const MultiplierIncreased())); }, ); }); }
pinball/test/game/components/android_acres/behaviors/ramp_multiplier_behavior_test.dart/0
{'file_path': 'pinball/test/game/components/android_acres/behaviors/ramp_multiplier_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 2342}
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.kicker.left.lit.keyName, Assets.images.kicker.left.dimmed.keyName, Assets.images.kicker.right.lit.keyName, Assets.images.kicker.right.dimmed.keyName, Assets.images.baseboard.left.keyName, Assets.images.baseboard.right.keyName, Assets.images.flipper.left.keyName, Assets.images.flipper.right.keyName, ]); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('BottomGroup', () { final flameTester = FlameTester(_TestGame.new); flameTester.test( 'loads correctly', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); expect(game.descendants(), contains(bottomGroup)); }, ); group('loads', () { flameTester.test( 'one left flipper', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final leftFlippers = bottomGroup.descendants().whereType<Flipper>().where( (flipper) => flipper.side.isLeft, ); expect(leftFlippers.length, equals(1)); }, ); flameTester.test( 'one right flipper', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final rightFlippers = bottomGroup.descendants().whereType<Flipper>().where( (flipper) => flipper.side.isRight, ); expect(rightFlippers.length, equals(1)); }, ); flameTester.test( 'two Baseboards', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final baseBottomGroups = bottomGroup.descendants().whereType<Baseboard>(); expect(baseBottomGroups.length, equals(2)); }, ); flameTester.test( 'two Kickers', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final kickers = bottomGroup.descendants().whereType<Kicker>(); expect(kickers.length, equals(2)); }, ); }); }); }
pinball/test/game/components/bottom_group_test.dart/0
{'file_path': 'pinball/test/game/components/bottom_group_test.dart', 'repo_id': 'pinball', 'token_count': 1640}
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/sparky_scorch/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.sparky.computer.top.keyName, Assets.images.sparky.computer.base.keyName, Assets.images.sparky.computer.glow.keyName, Assets.images.sparky.bumper.a.lit.keyName, Assets.images.sparky.bumper.a.dimmed.keyName, Assets.images.sparky.bumper.b.lit.keyName, Assets.images.sparky.bumper.b.dimmed.keyName, Assets.images.sparky.bumper.c.lit.keyName, Assets.images.sparky.bumper.c.dimmed.keyName, ]); } Future<void> pump( SparkyScorch child, { required GameBloc gameBloc, }) async { // Not needed once https://github.com/flame-engine/flame/issues/1607 // is fixed await onLoad(); await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('SparkyComputerBonusBehavior', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.testGameWidget( 'adds GameBonus.sparkyTurboCharge to the game ' 'when SparkyComputerState.withBall is emitted', setUp: (game, tester) async { final behavior = SparkyComputerBonusBehavior(); final parent = SparkyScorch.test(); final sparkyComputer = SparkyComputer(); await parent.add(sparkyComputer); await game.pump(parent, gameBloc: gameBloc); await parent.ensureAdd(behavior); sparkyComputer.bloc.onBallEntered(); await tester.pump(); verify( () => gameBloc.add(const BonusActivated(GameBonus.sparkyTurboCharge)), ).called(1); }, ); }); }
pinball/test/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior_test.dart/0
{'file_path': 'pinball/test/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 986}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:pinball/leaderboard/models/leader_board_entry.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('LeaderboardEntry', () { group('toEntry', () { test('returns the correct from a to entry data', () { expect( LeaderboardEntryData.empty.toEntry(1), LeaderboardEntry( rank: '1', playerInitials: '', score: 0, character: CharacterType.dash.toTheme.leaderboardIcon, ), ); }); }); group('CharacterType', () { test('toTheme returns the correct theme', () { expect(CharacterType.dash.toTheme, equals(DashTheme())); expect(CharacterType.sparky.toTheme, equals(SparkyTheme())); expect(CharacterType.android.toTheme, equals(AndroidTheme())); expect(CharacterType.dino.toTheme, equals(DinoTheme())); }); }); group('CharacterTheme', () { test('toType returns the correct type', () { expect(DashTheme().toType, equals(CharacterType.dash)); expect(SparkyTheme().toType, equals(CharacterType.sparky)); expect(AndroidTheme().toType, equals(CharacterType.android)); expect(DinoTheme().toType, equals(CharacterType.dino)); }); }); }); }
pinball/test/leaderboard/models/leader_board_entry_test.dart/0
{'file_path': 'pinball/test/leaderboard/models/leader_board_entry_test.dart', 'repo_id': 'pinball', 'token_count': 582}
name: playground description: A new Flutter project. version: 1.0.0+1 publish_to: 'none' environment: sdk: '>=2.15.0 <3.0.0' dependencies: cupertino_icons: ^1.0.4 flutter: sdk: flutter shake: # https://github.com/deven98/shake/pull/6 git: https://github.com/maxlapides/shake.git dev_dependencies: flutter_lints: flutter_test: sdk: flutter flutter: uses-material-design: true
playground/pubspec.yaml/0
{'file_path': 'playground/pubspec.yaml', 'repo_id': 'playground', 'token_count': 178}
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: build examples (Win32) script: .ci/scripts/build_examples_win32.sh - name: native unit tests (Win32) script: .ci/scripts/native_test_win32.sh - name: drive examples (Win32) script: .ci/scripts/drive_examples_win32.sh
plugins/.ci/targets/windows_build_and_platform_tests.yaml/0
{'file_path': 'plugins/.ci/targets/windows_build_and_platform_tests.yaml', 'repo_id': 'plugins', 'token_count': 121}
'needs-publishing': - packages/**/pubspec.yaml
plugins/.github/post_merge_labeler.yml/0
{'file_path': 'plugins/.github/post_merge_labeler.yml', 'repo_id': 'plugins', 'token_count': 18}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:camera_platform_interface/src/types/exposure_mode.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('ExposureMode should contain 2 options', () { const List<ExposureMode> values = ExposureMode.values; expect(values.length, 2); }); test('ExposureMode enum should have items in correct index', () { const List<ExposureMode> values = ExposureMode.values; expect(values[0], ExposureMode.auto); expect(values[1], ExposureMode.locked); }); test('serializeExposureMode() should serialize correctly', () { expect(serializeExposureMode(ExposureMode.auto), 'auto'); expect(serializeExposureMode(ExposureMode.locked), 'locked'); }); test('deserializeExposureMode() should deserialize correctly', () { expect(deserializeExposureMode('auto'), ExposureMode.auto); expect(deserializeExposureMode('locked'), ExposureMode.locked); }); }
plugins/packages/camera/camera_platform_interface/test/types/exposure_mode_test.dart/0
{'file_path': 'plugins/packages/camera/camera_platform_interface/test/types/exposure_mode_test.dart', 'repo_id': 'plugins', 'token_count': 350}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html'; import 'dart:ui'; import 'dart:js_util' as js_util; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:camera_web/src/camera.dart'; import 'package:camera_web/src/camera_service.dart'; import 'package:camera_web/src/shims/dart_js_util.dart'; import 'package:camera_web/src/types/types.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:mocktail/mocktail.dart'; import 'helpers/helpers.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('CameraService', () { const cameraId = 0; late Window window; late Navigator navigator; late MediaDevices mediaDevices; late CameraService cameraService; late JsUtil jsUtil; setUp(() async { window = MockWindow(); navigator = MockNavigator(); mediaDevices = MockMediaDevices(); jsUtil = MockJsUtil(); when(() => window.navigator).thenReturn(navigator); when(() => navigator.mediaDevices).thenReturn(mediaDevices); // Mock JsUtil to return the real getProperty from dart:js_util. when(() => jsUtil.getProperty(any(), any())).thenAnswer( (invocation) => js_util.getProperty( invocation.positionalArguments[0], invocation.positionalArguments[1], ), ); cameraService = CameraService()..window = window; }); group('getMediaStreamForOptions', () { testWidgets( 'calls MediaDevices.getUserMedia ' 'with provided options', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenAnswer((_) async => FakeMediaStream([])); final options = CameraOptions( video: VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.user), width: VideoSizeConstraint(ideal: 200), ), ); await cameraService.getMediaStreamForOptions(options); verify( () => mediaDevices.getUserMedia(options.toJson()), ).called(1); }); testWidgets( 'throws PlatformException ' 'with notSupported error ' 'when there are no media devices', (tester) async { when(() => navigator.mediaDevices).thenReturn(null); expect( () => cameraService.getMediaStreamForOptions(CameraOptions()), throwsA( isA<PlatformException>().having( (e) => e.code, 'code', CameraErrorCode.notSupported.toString(), ), ), ); }); group('throws CameraWebException', () { testWidgets( 'with notFound error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotFoundError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('NotFoundError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.notFound), ), ); }); testWidgets( 'with notFound error ' 'when MediaDevices.getUserMedia throws DomException ' 'with DevicesNotFoundError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('DevicesNotFoundError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.notFound), ), ); }); testWidgets( 'with notReadable error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotReadableError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('NotReadableError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.notReadable), ), ); }); testWidgets( 'with notReadable error ' 'when MediaDevices.getUserMedia throws DomException ' 'with TrackStartError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('TrackStartError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.notReadable), ), ); }); testWidgets( 'with overconstrained error ' 'when MediaDevices.getUserMedia throws DomException ' 'with OverconstrainedError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('OverconstrainedError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having( (e) => e.code, 'code', CameraErrorCode.overconstrained), ), ); }); testWidgets( 'with overconstrained error ' 'when MediaDevices.getUserMedia throws DomException ' 'with ConstraintNotSatisfiedError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('ConstraintNotSatisfiedError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having( (e) => e.code, 'code', CameraErrorCode.overconstrained), ), ); }); testWidgets( 'with permissionDenied error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotAllowedError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('NotAllowedError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having( (e) => e.code, 'code', CameraErrorCode.permissionDenied), ), ); }); testWidgets( 'with permissionDenied error ' 'when MediaDevices.getUserMedia throws DomException ' 'with PermissionDeniedError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('PermissionDeniedError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having( (e) => e.code, 'code', CameraErrorCode.permissionDenied), ), ); }); testWidgets( 'with type error ' 'when MediaDevices.getUserMedia throws DomException ' 'with TypeError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('TypeError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.type), ), ); }); testWidgets( 'with abort error ' 'when MediaDevices.getUserMedia throws DomException ' 'with AbortError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('AbortError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.abort), ), ); }); testWidgets( 'with security error ' 'when MediaDevices.getUserMedia throws DomException ' 'with SecurityError', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('SecurityError')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.security), ), ); }); testWidgets( 'with unknown error ' 'when MediaDevices.getUserMedia throws DomException ' 'with an unknown error', (tester) async { when(() => mediaDevices.getUserMedia(any())) .thenThrow(FakeDomException('Unknown')); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.unknown), ), ); }); testWidgets( 'with unknown error ' 'when MediaDevices.getUserMedia throws an unknown exception', (tester) async { when(() => mediaDevices.getUserMedia(any())).thenThrow(Exception()); expect( () => cameraService.getMediaStreamForOptions( CameraOptions(), cameraId: cameraId, ), throwsA( isA<CameraWebException>() .having((e) => e.cameraId, 'cameraId', cameraId) .having((e) => e.code, 'code', CameraErrorCode.unknown), ), ); }); }); }); group('getZoomLevelCapabilityForCamera', () { late Camera camera; late List<MediaStreamTrack> videoTracks; setUp(() { camera = MockCamera(); videoTracks = [MockMediaStreamTrack(), MockMediaStreamTrack()]; when(() => camera.textureId).thenReturn(0); when(() => camera.stream).thenReturn(FakeMediaStream(videoTracks)); cameraService.jsUtil = jsUtil; }); testWidgets( 'returns the zoom level capability ' 'based on the first video track', (tester) async { when(mediaDevices.getSupportedConstraints).thenReturn({ 'zoom': true, }); when(videoTracks.first.getCapabilities).thenReturn({ 'zoom': js_util.jsify({ 'min': 100, 'max': 400, 'step': 2, }), }); final zoomLevelCapability = cameraService.getZoomLevelCapabilityForCamera(camera); expect(zoomLevelCapability.minimum, equals(100.0)); expect(zoomLevelCapability.maximum, equals(400.0)); expect(zoomLevelCapability.videoTrack, equals(videoTracks.first)); }); group('throws CameraWebException', () { testWidgets( 'with zoomLevelNotSupported error ' 'when there are no media devices', (tester) async { when(() => navigator.mediaDevices).thenReturn(null); expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA<CameraWebException>() .having( (e) => e.cameraId, 'cameraId', camera.textureId, ) .having( (e) => e.code, 'code', CameraErrorCode.zoomLevelNotSupported, ), ), ); }); testWidgets( 'with zoomLevelNotSupported error ' 'when the zoom level is not supported ' 'in the browser', (tester) async { when(mediaDevices.getSupportedConstraints).thenReturn({ 'zoom': false, }); when(videoTracks.first.getCapabilities).thenReturn({ 'zoom': { 'min': 100, 'max': 400, 'step': 2, }, }); expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA<CameraWebException>() .having( (e) => e.cameraId, 'cameraId', camera.textureId, ) .having( (e) => e.code, 'code', CameraErrorCode.zoomLevelNotSupported, ), ), ); }); testWidgets( 'with zoomLevelNotSupported error ' 'when the zoom level is not supported ' 'by the camera', (tester) async { when(mediaDevices.getSupportedConstraints).thenReturn({ 'zoom': true, }); when(videoTracks.first.getCapabilities).thenReturn({}); expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA<CameraWebException>() .having( (e) => e.cameraId, 'cameraId', camera.textureId, ) .having( (e) => e.code, 'code', CameraErrorCode.zoomLevelNotSupported, ), ), ); }); testWidgets( 'with notStarted error ' 'when the camera stream has not been initialized', (tester) async { when(mediaDevices.getSupportedConstraints).thenReturn({ 'zoom': true, }); // Create a camera stream with no video tracks. when(() => camera.stream).thenReturn(FakeMediaStream([])); expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA<CameraWebException>() .having( (e) => e.cameraId, 'cameraId', camera.textureId, ) .having( (e) => e.code, 'code', CameraErrorCode.notStarted, ), ), ); }); }); }); group('getFacingModeForVideoTrack', () { setUp(() { cameraService.jsUtil = jsUtil; }); testWidgets( 'throws PlatformException ' 'with notSupported error ' 'when there are no media devices', (tester) async { when(() => navigator.mediaDevices).thenReturn(null); expect( () => cameraService.getFacingModeForVideoTrack(MockMediaStreamTrack()), throwsA( isA<PlatformException>().having( (e) => e.code, 'code', CameraErrorCode.notSupported.toString(), ), ), ); }); testWidgets( 'returns null ' 'when the facing mode is not supported', (tester) async { when(mediaDevices.getSupportedConstraints).thenReturn({ 'facingMode': false, }); final facingMode = cameraService.getFacingModeForVideoTrack(MockMediaStreamTrack()); expect(facingMode, isNull); }); group('when the facing mode is supported', () { late MediaStreamTrack videoTrack; setUp(() { videoTrack = MockMediaStreamTrack(); when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities')) .thenReturn(true); when(mediaDevices.getSupportedConstraints).thenReturn({ 'facingMode': true, }); }); testWidgets( 'returns an appropriate facing mode ' 'based on the video track settings', (tester) async { when(videoTrack.getSettings).thenReturn({'facingMode': 'user'}); final facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, equals('user')); }); testWidgets( 'returns an appropriate facing mode ' 'based on the video track capabilities ' 'when the facing mode setting is empty', (tester) async { when(videoTrack.getSettings).thenReturn({}); when(videoTrack.getCapabilities).thenReturn({ 'facingMode': ['environment', 'left'] }); when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities')) .thenReturn(true); final facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, equals('environment')); }); testWidgets( 'returns null ' 'when the facing mode setting ' 'and capabilities are empty', (tester) async { when(videoTrack.getSettings).thenReturn({}); when(videoTrack.getCapabilities).thenReturn({'facingMode': []}); final facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, isNull); }); testWidgets( 'returns null ' 'when the facing mode setting is empty and ' 'the video track capabilities are not supported', (tester) async { when(videoTrack.getSettings).thenReturn({}); when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities')) .thenReturn(false); final facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, isNull); }); }); }); group('mapFacingModeToLensDirection', () { testWidgets( 'returns front ' 'when the facing mode is user', (tester) async { expect( cameraService.mapFacingModeToLensDirection('user'), equals(CameraLensDirection.front), ); }); testWidgets( 'returns back ' 'when the facing mode is environment', (tester) async { expect( cameraService.mapFacingModeToLensDirection('environment'), equals(CameraLensDirection.back), ); }); testWidgets( 'returns external ' 'when the facing mode is left', (tester) async { expect( cameraService.mapFacingModeToLensDirection('left'), equals(CameraLensDirection.external), ); }); testWidgets( 'returns external ' 'when the facing mode is right', (tester) async { expect( cameraService.mapFacingModeToLensDirection('right'), equals(CameraLensDirection.external), ); }); }); group('mapFacingModeToCameraType', () { testWidgets( 'returns user ' 'when the facing mode is user', (tester) async { expect( cameraService.mapFacingModeToCameraType('user'), equals(CameraType.user), ); }); testWidgets( 'returns environment ' 'when the facing mode is environment', (tester) async { expect( cameraService.mapFacingModeToCameraType('environment'), equals(CameraType.environment), ); }); testWidgets( 'returns user ' 'when the facing mode is left', (tester) async { expect( cameraService.mapFacingModeToCameraType('left'), equals(CameraType.user), ); }); testWidgets( 'returns user ' 'when the facing mode is right', (tester) async { expect( cameraService.mapFacingModeToCameraType('right'), equals(CameraType.user), ); }); }); group('mapResolutionPresetToSize', () { testWidgets( 'returns 4096x2160 ' 'when the resolution preset is max', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.max), equals(Size(4096, 2160)), ); }); testWidgets( 'returns 4096x2160 ' 'when the resolution preset is ultraHigh', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh), equals(Size(4096, 2160)), ); }); testWidgets( 'returns 1920x1080 ' 'when the resolution preset is veryHigh', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.veryHigh), equals(Size(1920, 1080)), ); }); testWidgets( 'returns 1280x720 ' 'when the resolution preset is high', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.high), equals(Size(1280, 720)), ); }); testWidgets( 'returns 720x480 ' 'when the resolution preset is medium', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.medium), equals(Size(720, 480)), ); }); testWidgets( 'returns 320x240 ' 'when the resolution preset is low', (tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.low), equals(Size(320, 240)), ); }); }); group('mapDeviceOrientationToOrientationType', () { testWidgets( 'returns portraitPrimary ' 'when the device orientation is portraitUp', (tester) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.portraitUp, ), equals(OrientationType.portraitPrimary), ); }); testWidgets( 'returns landscapePrimary ' 'when the device orientation is landscapeLeft', (tester) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.landscapeLeft, ), equals(OrientationType.landscapePrimary), ); }); testWidgets( 'returns portraitSecondary ' 'when the device orientation is portraitDown', (tester) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.portraitDown, ), equals(OrientationType.portraitSecondary), ); }); testWidgets( 'returns landscapeSecondary ' 'when the device orientation is landscapeRight', (tester) async { expect( cameraService.mapDeviceOrientationToOrientationType( DeviceOrientation.landscapeRight, ), equals(OrientationType.landscapeSecondary), ); }); }); group('mapOrientationTypeToDeviceOrientation', () { testWidgets( 'returns portraitUp ' 'when the orientation type is portraitPrimary', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitPrimary, ), equals(DeviceOrientation.portraitUp), ); }); testWidgets( 'returns landscapeLeft ' 'when the orientation type is landscapePrimary', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.landscapePrimary, ), equals(DeviceOrientation.landscapeLeft), ); }); testWidgets( 'returns portraitDown ' 'when the orientation type is portraitSecondary', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitSecondary, ), equals(DeviceOrientation.portraitDown), ); }); testWidgets( 'returns portraitDown ' 'when the orientation type is portraitSecondary', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.portraitSecondary, ), equals(DeviceOrientation.portraitDown), ); }); testWidgets( 'returns landscapeRight ' 'when the orientation type is landscapeSecondary', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( OrientationType.landscapeSecondary, ), equals(DeviceOrientation.landscapeRight), ); }); testWidgets( 'returns portraitUp ' 'for an unknown orientation type', (tester) async { expect( cameraService.mapOrientationTypeToDeviceOrientation( 'unknown', ), equals(DeviceOrientation.portraitUp), ); }); }); }); } class JSNoSuchMethodError implements Exception {}
plugins/packages/camera/camera_web/example/integration_test/camera_service_test.dart/0
{'file_path': 'plugins/packages/camera/camera_web/example/integration_test/camera_service_test.dart', 'repo_id': 'plugins', 'token_count': 13465}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_util' as js_util; /// A utility that shims dart:js_util to manipulate JavaScript interop objects. class JsUtil { /// Returns true if the object [o] has the property [name]. bool hasProperty(Object o, Object name) => js_util.hasProperty(o, name); /// Returns the value of the property [name] in the object [o]. dynamic getProperty(Object o, Object name) => js_util.getProperty(o, name); }
plugins/packages/camera/camera_web/lib/src/shims/dart_js_util.dart/0
{'file_path': 'plugins/packages/camera/camera_web/lib/src/shims/dart_js_util.dart', 'repo_id': 'plugins', 'token_count': 169}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select a text file using `openFile`, then /// displays its contents in a dialog. class OpenTextPage extends StatelessWidget { Future<void> _openTextFile(BuildContext context) async { final XTypeGroup typeGroup = XTypeGroup( label: 'text', extensions: <String>['txt', 'json'], ); final XFile? file = await FileSelectorPlatform.instance .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); if (file == null) { // Operation was canceled by the user. return; } final String fileName = file.name; final String fileContent = await file.readAsString(); await showDialog<void>( context: context, builder: (BuildContext context) => TextDisplay(fileName, fileContent), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Open a text file'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.white, ), child: const Text('Press to open a text file (json, txt)'), onPressed: () => _openTextFile(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog. class TextDisplay extends StatelessWidget { /// Default Constructor. const TextDisplay(this.fileName, this.fileContent); /// The name of the selected file. final String fileName; /// The contents of the text file. final String fileContent; @override Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), content: Scrollbar( child: SingleChildScrollView( child: Text(fileContent), ), ), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () => Navigator.pop(context), ), ], ); } }
plugins/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart/0
{'file_path': 'plugins/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart', 'repo_id': 'plugins', 'token_count': 941}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; const CameraPosition _kInitialPosition = CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0); class LiteModePage extends GoogleMapExampleAppPage { LiteModePage() : super(const Icon(Icons.map), 'Lite mode'); @override Widget build(BuildContext context) { return const _LiteModeBody(); } } class _LiteModeBody extends StatelessWidget { const _LiteModeBody(); @override Widget build(BuildContext context) { return Card( child: Padding( padding: const EdgeInsets.symmetric(vertical: 30.0), child: Center( child: SizedBox( width: 300.0, height: 300.0, child: GoogleMap( initialCameraPosition: _kInitialPosition, liteModeEnabled: true, ), ), ), ), ); } }
plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart', 'repo_id': 'plugins', 'token_count': 478}
name: google_maps_flutter_example description: Demonstrates how to use the google_maps_flutter plugin. publish_to: none environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=2.5.0" dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.0 google_maps_flutter: # When depending on this package from a real application you should use: # google_maps_flutter: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ flutter_plugin_android_lifecycle: ^2.0.1 dev_dependencies: espresso: ^0.1.0+2 flutter_driver: sdk: flutter integration_test: sdk: flutter pedantic: ^1.10.0 flutter: uses-material-design: true assets: - assets/
plugins/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml', 'repo_id': 'plugins', 'token_count': 327}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show hashValues; import 'package:flutter/foundation.dart' show visibleForTesting; /// A pair of latitude and longitude coordinates, stored as degrees. class LatLng { /// Creates a geographical location specified in degrees [latitude] and /// [longitude]. /// /// The latitude is clamped to the inclusive interval from -90.0 to +90.0. /// /// The longitude is normalized to the half-open interval from -180.0 /// (inclusive) to +180.0 (exclusive). const LatLng(double latitude, double longitude) : assert(latitude != null), assert(longitude != null), latitude = (latitude < -90.0 ? -90.0 : (90.0 < latitude ? 90.0 : latitude)), // Avoids normalization if possible to prevent unnecessary loss of precision longitude = longitude >= -180 && longitude < 180 ? longitude : (longitude + 180.0) % 360.0 - 180.0; /// The latitude in degrees between -90.0 and 90.0, both inclusive. final double latitude; /// The longitude in degrees between -180.0 (inclusive) and 180.0 (exclusive). final double longitude; /// Converts this object to something serializable in JSON. Object toJson() { return <double>[latitude, longitude]; } /// Initialize a LatLng from an \[lat, lng\] array. static LatLng? fromJson(Object? json) { if (json == null) { return null; } assert(json is List && json.length == 2); final list = json as List; return LatLng(list[0], list[1]); } @override String toString() => '$runtimeType($latitude, $longitude)'; @override bool operator ==(Object o) { return o is LatLng && o.latitude == latitude && o.longitude == longitude; } @override int get hashCode => hashValues(latitude, longitude); } /// A latitude/longitude aligned rectangle. /// /// The rectangle conceptually includes all points (lat, lng) where /// * lat ∈ [`southwest.latitude`, `northeast.latitude`] /// * lng ∈ [`southwest.longitude`, `northeast.longitude`], /// if `southwest.longitude` ≤ `northeast.longitude`, /// * lng ∈ [-180, `northeast.longitude`] ∪ [`southwest.longitude`, 180], /// if `northeast.longitude` < `southwest.longitude` class LatLngBounds { /// Creates geographical bounding box with the specified corners. /// /// The latitude of the southwest corner cannot be larger than the /// latitude of the northeast corner. LatLngBounds({required this.southwest, required this.northeast}) : assert(southwest != null), assert(northeast != null), assert(southwest.latitude <= northeast.latitude); /// The southwest corner of the rectangle. final LatLng southwest; /// The northeast corner of the rectangle. final LatLng northeast; /// Converts this object to something serializable in JSON. Object toJson() { return <Object>[southwest.toJson(), northeast.toJson()]; } /// Returns whether this rectangle contains the given [LatLng]. bool contains(LatLng point) { return _containsLatitude(point.latitude) && _containsLongitude(point.longitude); } bool _containsLatitude(double lat) { return (southwest.latitude <= lat) && (lat <= northeast.latitude); } bool _containsLongitude(double lng) { if (southwest.longitude <= northeast.longitude) { return southwest.longitude <= lng && lng <= northeast.longitude; } else { return southwest.longitude <= lng || lng <= northeast.longitude; } } /// Converts a list to [LatLngBounds]. @visibleForTesting static LatLngBounds? fromList(Object? json) { if (json == null) { return null; } assert(json is List && json.length == 2); final list = json as List; return LatLngBounds( southwest: LatLng.fromJson(list[0])!, northeast: LatLng.fromJson(list[1])!, ); } @override String toString() { return '$runtimeType($southwest, $northeast)'; } @override bool operator ==(Object o) { return o is LatLngBounds && o.southwest == southwest && o.northeast == northeast; } @override int get hashCode => hashValues(southwest, northeast); }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart', 'repo_id': 'plugins', 'token_count': 1475}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show hashValues; import 'package:flutter/rendering.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object_updates.dart'; /// A trivial TestMapsObject implementation for testing updates with. class TestMapsObject implements MapsObject { const TestMapsObject(this.mapsId, {this.data = 1}); final MapsObjectId<TestMapsObject> mapsId; final int data; @override TestMapsObject clone() { return TestMapsObject(mapsId, data: data); } @override Object toJson() { return <String, Object>{'id': mapsId.value}; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is TestMapsObject && mapsId == other.mapsId && data == other.data; } @override int get hashCode => hashValues(mapsId, data); } class TestMapsObjectUpdate extends MapsObjectUpdates<TestMapsObject> { TestMapsObjectUpdate.from( Set<TestMapsObject> previous, Set<TestMapsObject> current) : super.from(previous, current, objectName: 'testObject'); }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart', 'repo_id': 'plugins', 'token_count': 439}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:html' as html; import 'dart:js_util' show getProperty; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'; import 'package:http/http.dart' as http; import 'package:integration_test/integration_test.dart'; import 'resources/icon_image_base64.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('MarkersController', () { late StreamController<MapEvent> events; late MarkersController controller; late gmaps.GMap map; setUp(() { events = StreamController<MapEvent>(); controller = MarkersController(stream: events); map = gmaps.GMap(html.DivElement()); controller.bindToMap(123, map); }); testWidgets('addMarkers', (WidgetTester tester) async { final markers = { Marker(markerId: MarkerId('1')), Marker(markerId: MarkerId('2')), }; controller.addMarkers(markers); expect(controller.markers.length, 2); expect(controller.markers, contains(MarkerId('1'))); expect(controller.markers, contains(MarkerId('2'))); expect(controller.markers, isNot(contains(MarkerId('66')))); }); testWidgets('changeMarkers', (WidgetTester tester) async { final markers = { Marker(markerId: MarkerId('1')), }; controller.addMarkers(markers); expect(controller.markers[MarkerId('1')]?.marker?.draggable, isFalse); // Update the marker with radius 10 final updatedMarkers = { Marker(markerId: MarkerId('1'), draggable: true), }; controller.changeMarkers(updatedMarkers); expect(controller.markers.length, 1); expect(controller.markers[MarkerId('1')]?.marker?.draggable, isTrue); }); testWidgets('removeMarkers', (WidgetTester tester) async { final markers = { Marker(markerId: MarkerId('1')), Marker(markerId: MarkerId('2')), Marker(markerId: MarkerId('3')), }; controller.addMarkers(markers); expect(controller.markers.length, 3); // Remove some markers... final markerIdsToRemove = { MarkerId('1'), MarkerId('3'), }; controller.removeMarkers(markerIdsToRemove); expect(controller.markers.length, 1); expect(controller.markers, isNot(contains(MarkerId('1')))); expect(controller.markers, contains(MarkerId('2'))); expect(controller.markers, isNot(contains(MarkerId('3')))); }); testWidgets('InfoWindow show/hide', (WidgetTester tester) async { final markers = { Marker( markerId: MarkerId('1'), infoWindow: InfoWindow(title: "Title", snippet: "Snippet"), ), }; controller.addMarkers(markers); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(MarkerId('1')); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isTrue); controller.hideMarkerInfoWindow(MarkerId('1')); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isFalse); }); // https://github.com/flutter/flutter/issues/67380 testWidgets('only single InfoWindow is visible', (WidgetTester tester) async { final markers = { Marker( markerId: MarkerId('1'), infoWindow: InfoWindow(title: "Title", snippet: "Snippet"), ), Marker( markerId: MarkerId('2'), infoWindow: InfoWindow(title: "Title", snippet: "Snippet"), ), }; controller.addMarkers(markers); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isFalse); expect(controller.markers[MarkerId('2')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(MarkerId('1')); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isTrue); expect(controller.markers[MarkerId('2')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(MarkerId('2')); expect(controller.markers[MarkerId('1')]?.infoWindowShown, isFalse); expect(controller.markers[MarkerId('2')]?.infoWindowShown, isTrue); }); // https://github.com/flutter/flutter/issues/66622 testWidgets('markers with custom bitmap icon work', (WidgetTester tester) async { final bytes = Base64Decoder().convert(iconImageBase64); final markers = { Marker( markerId: MarkerId('1'), icon: BitmapDescriptor.fromBytes(bytes)), }; controller.addMarkers(markers); expect(controller.markers.length, 1); expect(controller.markers[MarkerId('1')]?.marker?.icon, isNotNull); final blobUrl = getProperty( controller.markers[MarkerId('1')]!.marker!.icon!, 'url', ); expect(blobUrl, startsWith('blob:')); final response = await http.get(Uri.parse(blobUrl)); expect(response.bodyBytes, bytes, reason: 'Bytes from the Icon blob must match bytes used to create Marker'); }); // https://github.com/flutter/flutter/issues/67854 testWidgets('InfoWindow snippet can have links', (WidgetTester tester) async { final markers = { Marker( markerId: MarkerId('1'), infoWindow: InfoWindow( title: 'title for test', snippet: '<a href="https://www.google.com">Go to Google >>></a>', ), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final content = controller.markers[MarkerId('1')]?.infoWindow?.content as html.HtmlElement; expect(content.innerHtml, contains('title for test')); expect( content.innerHtml, contains( '<a href="https://www.google.com">Go to Google &gt;&gt;&gt;</a>')); }); // https://github.com/flutter/flutter/issues/67289 testWidgets('InfoWindow content is clickable', (WidgetTester tester) async { final markers = { Marker( markerId: MarkerId('1'), infoWindow: InfoWindow( title: 'title for test', snippet: 'some snippet', ), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final content = controller.markers[MarkerId('1')]?.infoWindow?.content as html.HtmlElement; content.click(); final event = await events.stream.first; expect(event, isA<InfoWindowTapEvent>()); expect((event as InfoWindowTapEvent).value, equals(MarkerId('1'))); }); }); }
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart', 'repo_id': 'plugins', 'token_count': 2894}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:google_sign_in_web/google_sign_in_web.dart'; import 'package:integration_test/integration_test.dart'; import 'package:js/js_util.dart' as js_util; import 'gapi_mocks/gapi_mocks.dart' as gapi_mocks; import 'src/test_utils.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); GoogleSignInTokenData expectedTokenData = GoogleSignInTokenData(idToken: '70k3n', accessToken: 'access_70k3n'); GoogleSignInUserData expectedUserData = GoogleSignInUserData( displayName: 'Foo Bar', email: 'foo@example.com', id: '123', photoUrl: 'http://example.com/img.jpg', idToken: expectedTokenData.idToken, ); late GoogleSignInPlugin plugin; group('plugin.init() throws a catchable exception', () { setUp(() { // The pre-configured use case for the instances of the plugin in this test gapiUrl = toBase64Url(gapi_mocks.auth2InitError()); plugin = GoogleSignInPlugin(); }); testWidgets('init throws PlatformException', (WidgetTester tester) async { await expectLater( plugin.init( hostedDomain: 'foo', scopes: <String>['some', 'scope'], clientId: '1234', ), throwsA(isA<PlatformException>())); }); testWidgets('init forwards error code from JS', (WidgetTester tester) async { try { await plugin.init( hostedDomain: 'foo', scopes: <String>['some', 'scope'], clientId: '1234', ); fail('plugin.init should have thrown an exception!'); } catch (e) { final String code = js_util.getProperty(e, 'code') as String; expect(code, 'idpiframe_initialization_failed'); } }); }); group('other methods also throw catchable exceptions on init fail', () { // This function ensures that init gets called, but for some reason, we // ignored that it has thrown stuff... Future<void> _discardInit() async { try { await plugin.init( hostedDomain: 'foo', scopes: <String>['some', 'scope'], clientId: '1234', ); } catch (e) { // Noop so we can call other stuff } } setUp(() { gapiUrl = toBase64Url(gapi_mocks.auth2InitError()); plugin = GoogleSignInPlugin(); }); testWidgets('signInSilently throws', (WidgetTester tester) async { await _discardInit(); await expectLater( plugin.signInSilently(), throwsA(isA<PlatformException>())); }); testWidgets('signIn throws', (WidgetTester tester) async { await _discardInit(); await expectLater(plugin.signIn(), throwsA(isA<PlatformException>())); }); testWidgets('getTokens throws', (WidgetTester tester) async { await _discardInit(); await expectLater(plugin.getTokens(email: 'test@example.com'), throwsA(isA<PlatformException>())); }); testWidgets('requestScopes', (WidgetTester tester) async { await _discardInit(); await expectLater(plugin.requestScopes(['newScope']), throwsA(isA<PlatformException>())); }); }); group('auth2 Init Successful', () { setUp(() { // The pre-configured use case for the instances of the plugin in this test gapiUrl = toBase64Url(gapi_mocks.auth2InitSuccess(expectedUserData)); plugin = GoogleSignInPlugin(); }); testWidgets('Init requires clientId', (WidgetTester tester) async { expect(plugin.init(hostedDomain: ''), throwsAssertionError); }); testWidgets('Init doesn\'t accept spaces in scopes', (WidgetTester tester) async { expect( plugin.init( hostedDomain: '', clientId: '', scopes: <String>['scope with spaces'], ), throwsAssertionError); }); group('Successful .init, then', () { setUp(() async { await plugin.init( hostedDomain: 'foo', scopes: <String>['some', 'scope'], clientId: '1234', ); await plugin.initialized; }); testWidgets('signInSilently', (WidgetTester tester) async { GoogleSignInUserData actualUser = (await plugin.signInSilently())!; expect(actualUser, expectedUserData); }); testWidgets('signIn', (WidgetTester tester) async { GoogleSignInUserData actualUser = (await plugin.signIn())!; expect(actualUser, expectedUserData); }); testWidgets('getTokens', (WidgetTester tester) async { GoogleSignInTokenData actualToken = await plugin.getTokens(email: expectedUserData.email); expect(actualToken, expectedTokenData); }); testWidgets('requestScopes', (WidgetTester tester) async { bool scopeGranted = await plugin.requestScopes(['newScope']); expect(scopeGranted, isTrue); }); }); }); group('auth2 Init successful, but exception on signIn() method', () { setUp(() async { // The pre-configured use case for the instances of the plugin in this test gapiUrl = toBase64Url(gapi_mocks.auth2SignInError()); plugin = GoogleSignInPlugin(); await plugin.init( hostedDomain: 'foo', scopes: <String>['some', 'scope'], clientId: '1234', ); await plugin.initialized; }); testWidgets('User aborts sign in flow, throws PlatformException', (WidgetTester tester) async { await expectLater(plugin.signIn(), throwsA(isA<PlatformException>())); }); testWidgets('User aborts sign in flow, error code is forwarded from JS', (WidgetTester tester) async { try { await plugin.signIn(); fail('plugin.signIn() should have thrown an exception!'); } catch (e) { final String code = js_util.getProperty(e, 'code') as String; expect(code, 'popup_closed_by_user'); } }); }); }
plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/auth2_test.dart/0
{'file_path': 'plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/auth2_test.dart', 'repo_id': 'plugins', 'token_count': 2511}
include: ../../../analysis_options_legacy.yaml
plugins/packages/image_picker/image_picker_for_web/analysis_options.yaml/0
{'file_path': 'plugins/packages/image_picker/image_picker_for_web/analysis_options.yaml', 'repo_id': 'plugins', 'token_count': 16}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'billing_client_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** const _$BillingResponseEnumMap = { BillingResponse.serviceTimeout: -3, BillingResponse.featureNotSupported: -2, BillingResponse.serviceDisconnected: -1, BillingResponse.ok: 0, BillingResponse.userCanceled: 1, BillingResponse.serviceUnavailable: 2, BillingResponse.billingUnavailable: 3, BillingResponse.itemUnavailable: 4, BillingResponse.developerError: 5, BillingResponse.error: 6, BillingResponse.itemAlreadyOwned: 7, BillingResponse.itemNotOwned: 8, }; const _$SkuTypeEnumMap = { SkuType.inapp: 'inapp', SkuType.subs: 'subs', }; const _$ProrationModeEnumMap = { ProrationMode.unknownSubscriptionUpgradeDowngradePolicy: 0, ProrationMode.immediateWithTimeProration: 1, ProrationMode.immediateAndChargeProratedPrice: 2, ProrationMode.immediateWithoutProration: 3, ProrationMode.deferred: 4, }; const _$BillingClientFeatureEnumMap = { BillingClientFeature.inAppItemsOnVR: 'inAppItemsOnVr', BillingClientFeature.priceChangeConfirmation: 'priceChangeConfirmation', BillingClientFeature.subscriptions: 'subscriptions', BillingClientFeature.subscriptionsOnVR: 'subscriptionsOnVr', BillingClientFeature.subscriptionsUpdate: 'subscriptionsUpdate', };
plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart/0
{'file_path': 'plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart', 'repo_id': 'plugins', 'token_count': 459}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/src/in_app_purchase_platform_addition.dart'; /// The [InAppPurchasePlatformAdditionProvider] is responsible for providing /// a platform-specific [InAppPurchasePlatformAddition]. /// /// [InAppPurchasePlatformAddition] implementation contain platform-specific /// features that are not available from the platform idiomatic /// [InAppPurchasePlatform] API. abstract class InAppPurchasePlatformAdditionProvider { /// Provides a platform-specific implementation of the [InAppPurchasePlatformAddition] /// class. T getPlatformAddition<T extends InAppPurchasePlatformAddition?>(); }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform_addition_provider.dart/0
{'file_path': 'plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform_addition_provider.dart', 'repo_id': 'plugins', 'token_count': 202}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Various types of biometric authentication. /// Some platforms report specific biometric types, while others report only /// classifications like strong and weak. enum BiometricType { /// Face authentication. face, /// Fingerprint authentication. fingerprint, /// Iris authentication. iris, /// Any biometric (e.g. fingerprint, iris, or face) on the device that the /// platform API considers to be strong. For example, on Android this /// corresponds to Class 3. strong, /// Any biometric (e.g. fingerprint, iris, or face) on the device that the /// platform API considers to be weak. For example, on Android this /// corresponds to Class 2. weak, }
plugins/packages/local_auth/local_auth_platform_interface/lib/types/biometric_type.dart/0
{'file_path': 'plugins/packages/local_auth/local_auth_platform_interface/lib/types/biometric_type.dart', 'repo_id': 'plugins', 'token_count': 218}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ffi'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'package:path_provider_windows/path_provider_windows.dart'; // A fake VersionInfoQuerier that just returns preset responses. class FakeVersionInfoQuerier implements VersionInfoQuerier { FakeVersionInfoQuerier(this.responses); final Map<String, String> responses; String? getStringValue(Pointer<Uint8>? versionInfo, String key) => responses[key]; } void main() { test('registered instance', () { PathProviderWindows.registerWith(); expect(PathProviderPlatform.instance, isA<PathProviderWindows>()); }); test('getTemporaryPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); expect(await pathProvider.getTemporaryPath(), contains(r'C:\')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with no version info', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{}); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, contains(r'C:\')); expect(path, contains(r'AppData')); // The last path component should be the executable name. expect(path, endsWith(r'flutter_tester')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with full version info', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with missing company', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'ProductName': 'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with problematic values', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': r'A <Bad> Company: Name.', 'ProductName': r'A"/Terrible\|App?*Name', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect( path, endsWith(r'AppData\Roaming\' r'A _Bad_ Company_ Name\' r'A__Terrible__App__Name')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with a completely invalid company', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': r'..', 'ProductName': r'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with very long app name', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String truncatedName = 'A' * 255; pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': truncatedName * 2, }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, endsWith('\\$truncatedName')); // The directory won't exist, since it's longer than MAXPATH, so don't check // that here. }, skip: !Platform.isWindows); test('getApplicationDocumentsPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String? path = await pathProvider.getApplicationDocumentsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Documents')); }, skip: !Platform.isWindows); test('getDownloadsPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String? path = await pathProvider.getDownloadsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Downloads')); }, skip: !Platform.isWindows); }
plugins/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart/0
{'file_path': 'plugins/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart', 'repo_id': 'plugins', 'token_count': 1681}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:quick_actions_ios/quick_actions_ios.dart'; import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$QuickActionsIos', () { late List<MethodCall> log; setUp(() { log = <MethodCall>[]; }); QuickActionsIos buildQuickActionsPlugin() { final QuickActionsIos quickActions = QuickActionsIos(); quickActions.channel .setMockMethodCallHandler((MethodCall methodCall) async { log.add(methodCall); return ''; }); return quickActions; } test('registerWith() registers correct instance', () { QuickActionsIos.registerWith(); expect(QuickActionsPlatform.instance, isA<QuickActionsIos>()); }); group('#initialize', () { test('passes getLaunchAction on launch method', () { final QuickActionsIos quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), ], ); }); test('initialize', () async { final QuickActionsIos quickActions = buildQuickActionsPlugin(); final Completer<bool> quickActionsHandler = Completer<bool>(); await quickActions .initialize((_) => quickActionsHandler.complete(true)); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), ], ); log.clear(); expect(quickActionsHandler.future, completion(isTrue)); }); }); group('#setShortCutItems', () { test('passes shortcutItem through channel', () { final QuickActionsIos quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); quickActions.setShortcutItems(<ShortcutItem>[ const ShortcutItem( type: 'test', localizedTitle: 'title', icon: 'icon.svg') ]); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), isMethodCall('setShortcutItems', arguments: <Map<String, String>>[ <String, String>{ 'type': 'test', 'localizedTitle': 'title', 'icon': 'icon.svg', } ]), ], ); }); test('setShortcutItems with demo data', () async { const String type = 'type'; const String localizedTitle = 'localizedTitle'; const String icon = 'icon'; final QuickActionsIos quickActions = buildQuickActionsPlugin(); await quickActions.setShortcutItems( const <ShortcutItem>[ ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon) ], ); expect( log, <Matcher>[ isMethodCall( 'setShortcutItems', arguments: <Map<String, String>>[ <String, String>{ 'type': type, 'localizedTitle': localizedTitle, 'icon': icon, } ], ), ], ); log.clear(); }); }); group('#clearShortCutItems', () { test('send clearShortcutItems through channel', () { final QuickActionsIos quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); quickActions.clearShortcutItems(); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), isMethodCall('clearShortcutItems', arguments: null), ], ); }); test('clearShortcutItems', () { final QuickActionsIos quickActions = buildQuickActionsPlugin(); quickActions.clearShortcutItems(); expect( log, <Matcher>[ isMethodCall('clearShortcutItems', arguments: null), ], ); log.clear(); }); }); }); group('$ShortcutItem', () { test('Shortcut item can be constructed', () { const String type = 'type'; const String localizedTitle = 'title'; const String icon = 'foo'; const ShortcutItem item = ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon); expect(item.type, type); expect(item.localizedTitle, localizedTitle); expect(item.icon, icon); }); }); }
plugins/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart/0
{'file_path': 'plugins/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart', 'repo_id': 'plugins', 'token_count': 2153}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; /// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing /// a persistent store for simple data. /// /// Data is persisted to disk asynchronously. class SharedPreferences { SharedPreferences._(this._preferenceCache); static const String _prefix = 'flutter.'; static Completer<SharedPreferences>? _completer; static SharedPreferencesStorePlatform get _store => SharedPreferencesStorePlatform.instance; /// Loads and parses the [SharedPreferences] for this app from disk. /// /// Because this is reading from disk, it shouldn't be awaited in /// performance-sensitive blocks. static Future<SharedPreferences> getInstance() async { if (_completer == null) { final Completer<SharedPreferences> completer = Completer<SharedPreferences>(); try { final Map<String, Object> preferencesMap = await _getSharedPreferencesMap(); completer.complete(SharedPreferences._(preferencesMap)); } on Exception catch (e) { // If there's an error, explicitly return the future with an error. // then set the completer to null so we can retry. completer.completeError(e); final Future<SharedPreferences> sharedPrefsFuture = completer.future; _completer = null; return sharedPrefsFuture; } _completer = completer; } return _completer!.future; } /// The cache that holds all preferences. /// /// It is instantiated to the current state of the SharedPreferences or /// NSUserDefaults object and then kept in sync via setter methods in this /// class. /// /// It is NOT guaranteed that this cache and the device prefs will remain /// in sync since the setter method might fail for any reason. final Map<String, Object> _preferenceCache; /// Returns all keys in the persistent storage. Set<String> getKeys() => Set<String>.from(_preferenceCache.keys); /// Reads a value of any type from persistent storage. Object? get(String key) => _preferenceCache[key]; /// Reads a value from persistent storage, throwing an exception if it's not a /// bool. bool? getBool(String key) => _preferenceCache[key] as bool?; /// Reads a value from persistent storage, throwing an exception if it's not /// an int. int? getInt(String key) => _preferenceCache[key] as int?; /// Reads a value from persistent storage, throwing an exception if it's not a /// double. double? getDouble(String key) => _preferenceCache[key] as double?; /// Reads a value from persistent storage, throwing an exception if it's not a /// String. String? getString(String key) => _preferenceCache[key] as String?; /// Returns true if persistent storage the contains the given [key]. bool containsKey(String key) => _preferenceCache.containsKey(key); /// Reads a set of string values from persistent storage, throwing an /// exception if it's not a string set. List<String>? getStringList(String key) { List<dynamic>? list = _preferenceCache[key] as List<dynamic>?; if (list != null && list is! List<String>) { list = list.cast<String>().toList(); _preferenceCache[key] = list; } // Make a copy of the list so that later mutations won't propagate return list?.toList() as List<String>?; } /// Saves a boolean [value] to persistent storage in the background. Future<bool> setBool(String key, bool value) => _setValue('Bool', key, value); /// Saves an integer [value] to persistent storage in the background. Future<bool> setInt(String key, int value) => _setValue('Int', key, value); /// Saves a double [value] to persistent storage in the background. /// /// Android doesn't support storing doubles, so it will be stored as a float. Future<bool> setDouble(String key, double value) => _setValue('Double', key, value); /// Saves a string [value] to persistent storage in the background. /// /// Note: Due to limitations in Android's SharedPreferences, /// values cannot start with any one of the following: /// /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu' /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy' /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu' Future<bool> setString(String key, String value) => _setValue('String', key, value); /// Saves a list of strings [value] to persistent storage in the background. Future<bool> setStringList(String key, List<String> value) => _setValue('StringList', key, value); /// Removes an entry from persistent storage. Future<bool> remove(String key) { final String prefixedKey = '$_prefix$key'; _preferenceCache.remove(key); return _store.remove(prefixedKey); } Future<bool> _setValue(String valueType, String key, Object value) { ArgumentError.checkNotNull(value, 'value'); final String prefixedKey = '$_prefix$key'; if (value is List<String>) { // Make a copy of the list so that later mutations won't propagate _preferenceCache[key] = value.toList(); } else { _preferenceCache[key] = value; } return _store.setValue(valueType, prefixedKey, value); } /// Always returns true. /// On iOS, synchronize is marked deprecated. On Android, we commit every set. @deprecated Future<bool> commit() async => true; /// Completes with true once the user preferences for the app has been cleared. Future<bool> clear() { _preferenceCache.clear(); return _store.clear(); } /// Fetches the latest values from the host platform. /// /// Use this method to observe modifications that were made in native code /// (without using the plugin) while the app is running. Future<void> reload() async { final Map<String, Object> preferences = await SharedPreferences._getSharedPreferencesMap(); _preferenceCache.clear(); _preferenceCache.addAll(preferences); } static Future<Map<String, Object>> _getSharedPreferencesMap() async { final Map<String, Object> fromSystem = await _store.getAll(); assert(fromSystem != null); // Strip the flutter. prefix from the returned preferences. final Map<String, Object> preferencesMap = <String, Object>{}; for (final String key in fromSystem.keys) { assert(key.startsWith(_prefix)); preferencesMap[key.substring(_prefix.length)] = fromSystem[key]!; } return preferencesMap; } /// Initializes the shared preferences with mock values for testing. /// /// If the singleton instance has been initialized already, it is nullified. @visibleForTesting static void setMockInitialValues(Map<String, Object> values) { final Map<String, Object> newValues = values.map<String, Object>((String key, Object value) { String newKey = key; if (!key.startsWith(_prefix)) { newKey = '$_prefix$key'; } return MapEntry<String, Object>(newKey, value); }); SharedPreferencesStorePlatform.instance = InMemorySharedPreferencesStore.withData(newValues); _completer = null; } }
plugins/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart/0
{'file_path': 'plugins/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart', 'repo_id': 'plugins', 'token_count': 2367}
name: video_player_for_web_integration_tests publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=2.2.0" dependencies: flutter: sdk: flutter video_player_web: path: ../ dev_dependencies: flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter
plugins/packages/video_player/video_player_web/example/pubspec.yaml/0
{'file_path': 'plugins/packages/video_player/video_player_web/example/pubspec.yaml', 'repo_id': 'plugins', 'token_count': 149}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; class WebResourceRequestData { String? url; bool? isForMainFrame; bool? isRedirect; bool? hasGesture; String? method; Map<String?, String?>? requestHeaders; } class WebResourceErrorData { int? errorCode; String? description; } @HostApi() abstract class CookieManagerHostApi { @async bool clearCookies(); void setCookie(String url, String value); } @HostApi(dartHostTestHandler: 'TestWebViewHostApi') abstract class WebViewHostApi { void create(int instanceId, bool useHybridComposition); void dispose(int instanceId); void loadData( int instanceId, String data, String mimeType, String encoding, ); void loadDataWithBaseUrl( int instanceId, String baseUrl, String data, String mimeType, String encoding, String historyUrl, ); void loadUrl( int instanceId, String url, Map<String, String> headers, ); void postUrl( int instanceId, String url, Uint8List data, ); String getUrl(int instanceId); bool canGoBack(int instanceId); bool canGoForward(int instanceId); void goBack(int instanceId); void goForward(int instanceId); void reload(int instanceId); void clearCache(int instanceId, bool includeDiskFiles); @async String evaluateJavascript( int instanceId, String javascriptString, ); String getTitle(int instanceId); void scrollTo(int instanceId, int x, int y); void scrollBy(int instanceId, int x, int y); int getScrollX(int instanceId); int getScrollY(int instanceId); void setWebContentsDebuggingEnabled(bool enabled); void setWebViewClient(int instanceId, int webViewClientInstanceId); void addJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId); void removeJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId); void setDownloadListener(int instanceId, int listenerInstanceId); void setWebChromeClient(int instanceId, int clientInstanceId); void setBackgroundColor(int instanceId, int color); } @HostApi(dartHostTestHandler: 'TestWebSettingsHostApi') abstract class WebSettingsHostApi { void create(int instanceId, int webViewInstanceId); void dispose(int instanceId); void setDomStorageEnabled(int instanceId, bool flag); void setJavaScriptCanOpenWindowsAutomatically(int instanceId, bool flag); void setSupportMultipleWindows(int instanceId, bool support); void setJavaScriptEnabled(int instanceId, bool flag); void setUserAgentString(int instanceId, String userAgentString); void setMediaPlaybackRequiresUserGesture(int instanceId, bool require); void setSupportZoom(int instanceId, bool support); void setLoadWithOverviewMode(int instanceId, bool overview); void setUseWideViewPort(int instanceId, bool use); void setDisplayZoomControls(int instanceId, bool enabled); void setBuiltInZoomControls(int instanceId, bool enabled); void setAllowFileAccess(int instanceId, bool enabled); } @HostApi(dartHostTestHandler: 'TestJavaScriptChannelHostApi') abstract class JavaScriptChannelHostApi { void create(int instanceId, String channelName); } @FlutterApi() abstract class JavaScriptChannelFlutterApi { void dispose(int instanceId); void postMessage(int instanceId, String message); } @HostApi(dartHostTestHandler: 'TestWebViewClientHostApi') abstract class WebViewClientHostApi { void create(int instanceId, bool shouldOverrideUrlLoading); } @FlutterApi() abstract class WebViewClientFlutterApi { void dispose(int instanceId); void onPageStarted(int instanceId, int webViewInstanceId, String url); void onPageFinished(int instanceId, int webViewInstanceId, String url); void onReceivedRequestError( int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceErrorData error, ); void onReceivedError( int instanceId, int webViewInstanceId, int errorCode, String description, String failingUrl, ); void requestLoading( int instanceId, int webViewInstanceId, WebResourceRequestData request, ); void urlLoading(int instanceId, int webViewInstanceId, String url); } @HostApi(dartHostTestHandler: 'TestDownloadListenerHostApi') abstract class DownloadListenerHostApi { void create(int instanceId); } @FlutterApi() abstract class DownloadListenerFlutterApi { void dispose(int instanceId); void onDownloadStart( int instanceId, String url, String userAgent, String contentDisposition, String mimetype, int contentLength, ); } @HostApi(dartHostTestHandler: 'TestWebChromeClientHostApi') abstract class WebChromeClientHostApi { void create(int instanceId, int webViewClientInstanceId); } @HostApi(dartHostTestHandler: 'TestAssetManagerHostApi') abstract class FlutterAssetManagerHostApi { List<String> list(String path); String getAssetFilePathByName(String name); } @FlutterApi() abstract class WebChromeClientFlutterApi { void dispose(int instanceId); void onProgressChanged(int instanceId, int webViewInstanceId, int progress); }
plugins/packages/webview_flutter/webview_flutter_android/pigeons/android_webview.dart/0
{'file_path': 'plugins/packages/webview_flutter/webview_flutter_android/pigeons/android_webview.dart', 'repo_id': 'plugins', 'token_count': 1624}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Mocks generated by Mockito 5.0.16 from annotations // in webview_flutter_web/test/webview_flutter_web_test.dart. // Do not manually edit this file. import 'dart:async' as _i6; import 'dart:html' as _i2; import 'dart:math' as _i3; import 'package:flutter/foundation.dart' as _i5; import 'package:flutter/widgets.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_platform_interface/src/types/auto_media_playback_policy.dart' as _i8; import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i7; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart' as _i9; import 'package:webview_flutter_web/webview_flutter_web.dart' as _i10; // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types class _FakeCssClassSet_0 extends _i1.Fake implements _i2.CssClassSet {} class _FakeRectangle_1<T extends num> extends _i1.Fake implements _i3.Rectangle<T> {} class _FakeCssRect_2 extends _i1.Fake implements _i2.CssRect {} class _FakePoint_3<T extends num> extends _i1.Fake implements _i3.Point<T> {} class _FakeElementEvents_4 extends _i1.Fake implements _i2.ElementEvents {} class _FakeCssStyleDeclaration_5 extends _i1.Fake implements _i2.CssStyleDeclaration {} class _FakeElementStream_6<T extends _i2.Event> extends _i1.Fake implements _i2.ElementStream<T> {} class _FakeElementList_7<T extends _i2.Element> extends _i1.Fake implements _i2.ElementList<T> {} class _FakeScrollState_8 extends _i1.Fake implements _i2.ScrollState {} class _FakeAnimation_9 extends _i1.Fake implements _i2.Animation {} class _FakeElement_10 extends _i1.Fake implements _i2.Element {} class _FakeShadowRoot_11 extends _i1.Fake implements _i2.ShadowRoot {} class _FakeDocumentFragment_12 extends _i1.Fake implements _i2.DocumentFragment {} class _FakeNode_13 extends _i1.Fake implements _i2.Node {} class _FakeWidget_14 extends _i1.Fake implements _i4.Widget { @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeInheritedWidget_15 extends _i1.Fake implements _i4.InheritedWidget { @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeDiagnosticsNode_16 extends _i1.Fake implements _i5.DiagnosticsNode { @override String toString( {_i5.TextTreeConfiguration? parentConfiguration, _i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeHttpRequest_17 extends _i1.Fake implements _i2.HttpRequest {} class _FakeHttpRequestUpload_18 extends _i1.Fake implements _i2.HttpRequestUpload {} class _FakeEvents_19 extends _i1.Fake implements _i2.Events {} /// A class which mocks [IFrameElement]. /// /// See the documentation for Mockito's code generation for more information. class MockIFrameElement extends _i1.Mock implements _i2.IFrameElement { MockIFrameElement() { _i1.throwOnMissingStub(this); } @override set allow(String? value) => super.noSuchMethod(Invocation.setter(#allow, value), returnValueForMissingStub: null); @override set allowFullscreen(bool? value) => super.noSuchMethod(Invocation.setter(#allowFullscreen, value), returnValueForMissingStub: null); @override set allowPaymentRequest(bool? value) => super.noSuchMethod(Invocation.setter(#allowPaymentRequest, value), returnValueForMissingStub: null); @override set csp(String? value) => super.noSuchMethod(Invocation.setter(#csp, value), returnValueForMissingStub: null); @override set height(String? value) => super.noSuchMethod(Invocation.setter(#height, value), returnValueForMissingStub: null); @override set name(String? value) => super.noSuchMethod(Invocation.setter(#name, value), returnValueForMissingStub: null); @override set referrerPolicy(String? value) => super.noSuchMethod(Invocation.setter(#referrerPolicy, value), returnValueForMissingStub: null); @override set src(String? value) => super.noSuchMethod(Invocation.setter(#src, value), returnValueForMissingStub: null); @override set srcdoc(String? value) => super.noSuchMethod(Invocation.setter(#srcdoc, value), returnValueForMissingStub: null); @override set width(String? value) => super.noSuchMethod(Invocation.setter(#width, value), returnValueForMissingStub: null); @override set nonce(String? value) => super.noSuchMethod(Invocation.setter(#nonce, value), returnValueForMissingStub: null); @override Map<String, String> get attributes => (super.noSuchMethod(Invocation.getter(#attributes), returnValue: <String, String>{}) as Map<String, String>); @override set attributes(Map<String, String>? value) => super.noSuchMethod(Invocation.setter(#attributes, value), returnValueForMissingStub: null); @override List<_i2.Element> get children => (super.noSuchMethod(Invocation.getter(#children), returnValue: <_i2.Element>[]) as List<_i2.Element>); @override set children(List<_i2.Element>? value) => super.noSuchMethod(Invocation.setter(#children, value), returnValueForMissingStub: null); @override _i2.CssClassSet get classes => (super.noSuchMethod(Invocation.getter(#classes), returnValue: _FakeCssClassSet_0()) as _i2.CssClassSet); @override set classes(Iterable<String>? value) => super.noSuchMethod(Invocation.setter(#classes, value), returnValueForMissingStub: null); @override Map<String, String> get dataset => (super.noSuchMethod(Invocation.getter(#dataset), returnValue: <String, String>{}) as Map<String, String>); @override set dataset(Map<String, String>? value) => super.noSuchMethod(Invocation.setter(#dataset, value), returnValueForMissingStub: null); @override _i3.Rectangle<num> get client => (super.noSuchMethod(Invocation.getter(#client), returnValue: _FakeRectangle_1<num>()) as _i3.Rectangle<num>); @override _i3.Rectangle<num> get offset => (super.noSuchMethod(Invocation.getter(#offset), returnValue: _FakeRectangle_1<num>()) as _i3.Rectangle<num>); @override String get localName => (super.noSuchMethod(Invocation.getter(#localName), returnValue: '') as String); @override _i2.CssRect get contentEdge => (super.noSuchMethod(Invocation.getter(#contentEdge), returnValue: _FakeCssRect_2()) as _i2.CssRect); @override _i2.CssRect get paddingEdge => (super.noSuchMethod(Invocation.getter(#paddingEdge), returnValue: _FakeCssRect_2()) as _i2.CssRect); @override _i2.CssRect get borderEdge => (super.noSuchMethod(Invocation.getter(#borderEdge), returnValue: _FakeCssRect_2()) as _i2.CssRect); @override _i2.CssRect get marginEdge => (super.noSuchMethod(Invocation.getter(#marginEdge), returnValue: _FakeCssRect_2()) as _i2.CssRect); @override _i3.Point<num> get documentOffset => (super.noSuchMethod(Invocation.getter(#documentOffset), returnValue: _FakePoint_3<num>()) as _i3.Point<num>); @override set innerHtml(String? html) => super.noSuchMethod(Invocation.setter(#innerHtml, html), returnValueForMissingStub: null); @override String get innerText => (super.noSuchMethod(Invocation.getter(#innerText), returnValue: '') as String); @override set innerText(String? value) => super.noSuchMethod(Invocation.setter(#innerText, value), returnValueForMissingStub: null); @override _i2.ElementEvents get on => (super.noSuchMethod(Invocation.getter(#on), returnValue: _FakeElementEvents_4()) as _i2.ElementEvents); @override int get offsetHeight => (super.noSuchMethod(Invocation.getter(#offsetHeight), returnValue: 0) as int); @override int get offsetLeft => (super.noSuchMethod(Invocation.getter(#offsetLeft), returnValue: 0) as int); @override int get offsetTop => (super.noSuchMethod(Invocation.getter(#offsetTop), returnValue: 0) as int); @override int get offsetWidth => (super.noSuchMethod(Invocation.getter(#offsetWidth), returnValue: 0) as int); @override int get scrollHeight => (super.noSuchMethod(Invocation.getter(#scrollHeight), returnValue: 0) as int); @override int get scrollLeft => (super.noSuchMethod(Invocation.getter(#scrollLeft), returnValue: 0) as int); @override set scrollLeft(int? value) => super.noSuchMethod(Invocation.setter(#scrollLeft, value), returnValueForMissingStub: null); @override int get scrollTop => (super.noSuchMethod(Invocation.getter(#scrollTop), returnValue: 0) as int); @override set scrollTop(int? value) => super.noSuchMethod(Invocation.setter(#scrollTop, value), returnValueForMissingStub: null); @override int get scrollWidth => (super.noSuchMethod(Invocation.getter(#scrollWidth), returnValue: 0) as int); @override String get contentEditable => (super.noSuchMethod(Invocation.getter(#contentEditable), returnValue: '') as String); @override set contentEditable(String? value) => super.noSuchMethod(Invocation.setter(#contentEditable, value), returnValueForMissingStub: null); @override set dir(String? value) => super.noSuchMethod(Invocation.setter(#dir, value), returnValueForMissingStub: null); @override bool get draggable => (super.noSuchMethod(Invocation.getter(#draggable), returnValue: false) as bool); @override set draggable(bool? value) => super.noSuchMethod(Invocation.setter(#draggable, value), returnValueForMissingStub: null); @override bool get hidden => (super.noSuchMethod(Invocation.getter(#hidden), returnValue: false) as bool); @override set hidden(bool? value) => super.noSuchMethod(Invocation.setter(#hidden, value), returnValueForMissingStub: null); @override set inert(bool? value) => super.noSuchMethod(Invocation.setter(#inert, value), returnValueForMissingStub: null); @override set inputMode(String? value) => super.noSuchMethod(Invocation.setter(#inputMode, value), returnValueForMissingStub: null); @override set lang(String? value) => super.noSuchMethod(Invocation.setter(#lang, value), returnValueForMissingStub: null); @override set spellcheck(bool? value) => super.noSuchMethod(Invocation.setter(#spellcheck, value), returnValueForMissingStub: null); @override _i2.CssStyleDeclaration get style => (super.noSuchMethod( Invocation.getter(#style), returnValue: _FakeCssStyleDeclaration_5()) as _i2.CssStyleDeclaration); @override set tabIndex(int? value) => super.noSuchMethod(Invocation.setter(#tabIndex, value), returnValueForMissingStub: null); @override set title(String? value) => super.noSuchMethod(Invocation.setter(#title, value), returnValueForMissingStub: null); @override set translate(bool? value) => super.noSuchMethod(Invocation.setter(#translate, value), returnValueForMissingStub: null); @override String get className => (super.noSuchMethod(Invocation.getter(#className), returnValue: '') as String); @override set className(String? value) => super.noSuchMethod(Invocation.setter(#className, value), returnValueForMissingStub: null); @override int get clientHeight => (super.noSuchMethod(Invocation.getter(#clientHeight), returnValue: 0) as int); @override int get clientWidth => (super.noSuchMethod(Invocation.getter(#clientWidth), returnValue: 0) as int); @override String get id => (super.noSuchMethod(Invocation.getter(#id), returnValue: '') as String); @override set id(String? value) => super.noSuchMethod(Invocation.setter(#id, value), returnValueForMissingStub: null); @override set slot(String? value) => super.noSuchMethod(Invocation.setter(#slot, value), returnValueForMissingStub: null); @override String get tagName => (super.noSuchMethod(Invocation.getter(#tagName), returnValue: '') as String); @override _i2.ElementStream<_i2.Event> get onAbort => (super.noSuchMethod(Invocation.getter(#onAbort), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforeCopy => (super.noSuchMethod(Invocation.getter(#onBeforeCopy), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforeCut => (super.noSuchMethod(Invocation.getter(#onBeforeCut), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforePaste => (super.noSuchMethod(Invocation.getter(#onBeforePaste), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBlur => (super.noSuchMethod(Invocation.getter(#onBlur), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onCanPlay => (super.noSuchMethod(Invocation.getter(#onCanPlay), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onCanPlayThrough => (super.noSuchMethod(Invocation.getter(#onCanPlayThrough), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onChange => (super.noSuchMethod(Invocation.getter(#onChange), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onClick => (super.noSuchMethod(Invocation.getter(#onClick), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onContextMenu => (super.noSuchMethod(Invocation.getter(#onContextMenu), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onCopy => (super.noSuchMethod(Invocation.getter(#onCopy), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>()) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onCut => (super.noSuchMethod(Invocation.getter(#onCut), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>()) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.Event> get onDoubleClick => (super.noSuchMethod(Invocation.getter(#onDoubleClick), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onDrag => (super.noSuchMethod(Invocation.getter(#onDrag), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragEnd => (super.noSuchMethod(Invocation.getter(#onDragEnd), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragEnter => (super.noSuchMethod(Invocation.getter(#onDragEnter), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragLeave => (super.noSuchMethod(Invocation.getter(#onDragLeave), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragOver => (super.noSuchMethod(Invocation.getter(#onDragOver), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragStart => (super.noSuchMethod(Invocation.getter(#onDragStart), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDrop => (super.noSuchMethod(Invocation.getter(#onDrop), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.Event> get onDurationChange => (super.noSuchMethod(Invocation.getter(#onDurationChange), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onEmptied => (super.noSuchMethod(Invocation.getter(#onEmptied), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onEnded => (super.noSuchMethod(Invocation.getter(#onEnded), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onError => (super.noSuchMethod(Invocation.getter(#onError), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFocus => (super.noSuchMethod(Invocation.getter(#onFocus), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onInput => (super.noSuchMethod(Invocation.getter(#onInput), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onInvalid => (super.noSuchMethod(Invocation.getter(#onInvalid), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyDown => (super.noSuchMethod(Invocation.getter(#onKeyDown), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>()) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyPress => (super.noSuchMethod(Invocation.getter(#onKeyPress), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>()) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyUp => (super.noSuchMethod(Invocation.getter(#onKeyUp), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>()) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.Event> get onLoad => (super.noSuchMethod(Invocation.getter(#onLoad), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onLoadedData => (super.noSuchMethod(Invocation.getter(#onLoadedData), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onLoadedMetadata => (super.noSuchMethod(Invocation.getter(#onLoadedMetadata), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseDown => (super.noSuchMethod(Invocation.getter(#onMouseDown), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseEnter => (super.noSuchMethod(Invocation.getter(#onMouseEnter), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseLeave => (super.noSuchMethod(Invocation.getter(#onMouseLeave), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseMove => (super.noSuchMethod(Invocation.getter(#onMouseMove), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseOut => (super.noSuchMethod(Invocation.getter(#onMouseOut), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseOver => (super.noSuchMethod(Invocation.getter(#onMouseOver), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseUp => (super.noSuchMethod(Invocation.getter(#onMouseUp), returnValue: _FakeElementStream_6<_i2.MouseEvent>()) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.WheelEvent> get onMouseWheel => (super.noSuchMethod(Invocation.getter(#onMouseWheel), returnValue: _FakeElementStream_6<_i2.WheelEvent>()) as _i2.ElementStream<_i2.WheelEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onPaste => (super.noSuchMethod(Invocation.getter(#onPaste), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>()) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.Event> get onPause => (super.noSuchMethod(Invocation.getter(#onPause), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onPlay => (super.noSuchMethod(Invocation.getter(#onPlay), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onPlaying => (super.noSuchMethod(Invocation.getter(#onPlaying), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onRateChange => (super.noSuchMethod(Invocation.getter(#onRateChange), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onReset => (super.noSuchMethod(Invocation.getter(#onReset), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onResize => (super.noSuchMethod(Invocation.getter(#onResize), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onScroll => (super.noSuchMethod(Invocation.getter(#onScroll), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSearch => (super.noSuchMethod(Invocation.getter(#onSearch), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSeeked => (super.noSuchMethod(Invocation.getter(#onSeeked), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSeeking => (super.noSuchMethod(Invocation.getter(#onSeeking), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSelect => (super.noSuchMethod(Invocation.getter(#onSelect), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSelectStart => (super.noSuchMethod(Invocation.getter(#onSelectStart), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onStalled => (super.noSuchMethod(Invocation.getter(#onStalled), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSubmit => (super.noSuchMethod(Invocation.getter(#onSubmit), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSuspend => (super.noSuchMethod(Invocation.getter(#onSuspend), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onTimeUpdate => (super.noSuchMethod(Invocation.getter(#onTimeUpdate), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchCancel => (super.noSuchMethod(Invocation.getter(#onTouchCancel), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchEnd => (super.noSuchMethod(Invocation.getter(#onTouchEnd), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchEnter => (super.noSuchMethod(Invocation.getter(#onTouchEnter), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchLeave => (super.noSuchMethod(Invocation.getter(#onTouchLeave), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchMove => (super.noSuchMethod(Invocation.getter(#onTouchMove), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchStart => (super.noSuchMethod(Invocation.getter(#onTouchStart), returnValue: _FakeElementStream_6<_i2.TouchEvent>()) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TransitionEvent> get onTransitionEnd => (super.noSuchMethod(Invocation.getter(#onTransitionEnd), returnValue: _FakeElementStream_6<_i2.TransitionEvent>()) as _i2.ElementStream<_i2.TransitionEvent>); @override _i2.ElementStream<_i2.Event> get onVolumeChange => (super.noSuchMethod(Invocation.getter(#onVolumeChange), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onWaiting => (super.noSuchMethod(Invocation.getter(#onWaiting), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFullscreenChange => (super.noSuchMethod(Invocation.getter(#onFullscreenChange), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFullscreenError => (super.noSuchMethod(Invocation.getter(#onFullscreenError), returnValue: _FakeElementStream_6<_i2.Event>()) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.WheelEvent> get onWheel => (super.noSuchMethod(Invocation.getter(#onWheel), returnValue: _FakeElementStream_6<_i2.WheelEvent>()) as _i2.ElementStream<_i2.WheelEvent>); @override List<_i2.Node> get nodes => (super.noSuchMethod(Invocation.getter(#nodes), returnValue: <_i2.Node>[]) as List<_i2.Node>); @override set nodes(Iterable<_i2.Node>? value) => super.noSuchMethod(Invocation.setter(#nodes, value), returnValueForMissingStub: null); @override List<_i2.Node> get childNodes => (super.noSuchMethod(Invocation.getter(#childNodes), returnValue: <_i2.Node>[]) as List<_i2.Node>); @override int get nodeType => (super.noSuchMethod(Invocation.getter(#nodeType), returnValue: 0) as int); @override set text(String? value) => super.noSuchMethod(Invocation.setter(#text, value), returnValueForMissingStub: null); @override String? getAttribute(String? name) => (super.noSuchMethod(Invocation.method(#getAttribute, [name])) as String?); @override String? getAttributeNS(String? namespaceURI, String? name) => (super.noSuchMethod( Invocation.method(#getAttributeNS, [namespaceURI, name])) as String?); @override bool hasAttribute(String? name) => (super.noSuchMethod(Invocation.method(#hasAttribute, [name]), returnValue: false) as bool); @override bool hasAttributeNS(String? namespaceURI, String? name) => (super .noSuchMethod(Invocation.method(#hasAttributeNS, [namespaceURI, name]), returnValue: false) as bool); @override void removeAttribute(String? name) => super.noSuchMethod(Invocation.method(#removeAttribute, [name]), returnValueForMissingStub: null); @override void removeAttributeNS(String? namespaceURI, String? name) => super .noSuchMethod(Invocation.method(#removeAttributeNS, [namespaceURI, name]), returnValueForMissingStub: null); @override void setAttribute(String? name, Object? value) => super.noSuchMethod(Invocation.method(#setAttribute, [name, value]), returnValueForMissingStub: null); @override void setAttributeNS(String? namespaceURI, String? name, Object? value) => super.noSuchMethod( Invocation.method(#setAttributeNS, [namespaceURI, name, value]), returnValueForMissingStub: null); @override _i2.ElementList<T> querySelectorAll<T extends _i2.Element>( String? selectors) => (super.noSuchMethod(Invocation.method(#querySelectorAll, [selectors]), returnValue: _FakeElementList_7<T>()) as _i2.ElementList<T>); @override _i6.Future<_i2.ScrollState> setApplyScroll(String? nativeScrollBehavior) => (super.noSuchMethod( Invocation.method(#setApplyScroll, [nativeScrollBehavior]), returnValue: Future<_i2.ScrollState>.value(_FakeScrollState_8())) as _i6.Future<_i2.ScrollState>); @override _i6.Future<_i2.ScrollState> setDistributeScroll( String? nativeScrollBehavior) => (super.noSuchMethod( Invocation.method(#setDistributeScroll, [nativeScrollBehavior]), returnValue: Future<_i2.ScrollState>.value(_FakeScrollState_8())) as _i6.Future<_i2.ScrollState>); @override Map<String, String> getNamespacedAttributes(String? namespace) => (super .noSuchMethod(Invocation.method(#getNamespacedAttributes, [namespace]), returnValue: <String, String>{}) as Map<String, String>); @override _i2.CssStyleDeclaration getComputedStyle([String? pseudoElement]) => (super.noSuchMethod(Invocation.method(#getComputedStyle, [pseudoElement]), returnValue: _FakeCssStyleDeclaration_5()) as _i2.CssStyleDeclaration); @override void appendText(String? text) => super.noSuchMethod(Invocation.method(#appendText, [text]), returnValueForMissingStub: null); @override void appendHtml(String? text, {_i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer}) => super.noSuchMethod( Invocation.method(#appendHtml, [text], {#validator: validator, #treeSanitizer: treeSanitizer}), returnValueForMissingStub: null); @override void attached() => super.noSuchMethod(Invocation.method(#attached, []), returnValueForMissingStub: null); @override void detached() => super.noSuchMethod(Invocation.method(#detached, []), returnValueForMissingStub: null); @override void enteredView() => super.noSuchMethod(Invocation.method(#enteredView, []), returnValueForMissingStub: null); @override List<_i3.Rectangle<num>> getClientRects() => (super.noSuchMethod(Invocation.method(#getClientRects, []), returnValue: <_i3.Rectangle<num>>[]) as List<_i3.Rectangle<num>>); @override void leftView() => super.noSuchMethod(Invocation.method(#leftView, []), returnValueForMissingStub: null); @override _i2.Animation animate(Iterable<Map<String, dynamic>>? frames, [dynamic timing]) => (super.noSuchMethod(Invocation.method(#animate, [frames, timing]), returnValue: _FakeAnimation_9()) as _i2.Animation); @override void attributeChanged(String? name, String? oldValue, String? newValue) => super.noSuchMethod( Invocation.method(#attributeChanged, [name, oldValue, newValue]), returnValueForMissingStub: null); @override String toString() => super.toString(); @override void scrollIntoView([_i2.ScrollAlignment? alignment]) => super.noSuchMethod(Invocation.method(#scrollIntoView, [alignment]), returnValueForMissingStub: null); @override void insertAdjacentText(String? where, String? text) => super.noSuchMethod(Invocation.method(#insertAdjacentText, [where, text]), returnValueForMissingStub: null); @override void insertAdjacentHtml(String? where, String? html, {_i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer}) => super.noSuchMethod( Invocation.method(#insertAdjacentHtml, [where, html], {#validator: validator, #treeSanitizer: treeSanitizer}), returnValueForMissingStub: null); @override _i2.Element insertAdjacentElement(String? where, _i2.Element? element) => (super.noSuchMethod( Invocation.method(#insertAdjacentElement, [where, element]), returnValue: _FakeElement_10()) as _i2.Element); @override bool matches(String? selectors) => (super.noSuchMethod(Invocation.method(#matches, [selectors]), returnValue: false) as bool); @override bool matchesWithAncestors(String? selectors) => (super.noSuchMethod(Invocation.method(#matchesWithAncestors, [selectors]), returnValue: false) as bool); @override _i2.ShadowRoot createShadowRoot() => (super.noSuchMethod(Invocation.method(#createShadowRoot, []), returnValue: _FakeShadowRoot_11()) as _i2.ShadowRoot); @override _i3.Point<num> offsetTo(_i2.Element? parent) => (super.noSuchMethod(Invocation.method(#offsetTo, [parent]), returnValue: _FakePoint_3<num>()) as _i3.Point<num>); @override _i2.DocumentFragment createFragment(String? html, {_i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer}) => (super.noSuchMethod( Invocation.method(#createFragment, [html], {#validator: validator, #treeSanitizer: treeSanitizer}), returnValue: _FakeDocumentFragment_12()) as _i2.DocumentFragment); @override void setInnerHtml(String? html, {_i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer}) => super.noSuchMethod( Invocation.method(#setInnerHtml, [html], {#validator: validator, #treeSanitizer: treeSanitizer}), returnValueForMissingStub: null); @override void blur() => super.noSuchMethod(Invocation.method(#blur, []), returnValueForMissingStub: null); @override void click() => super.noSuchMethod(Invocation.method(#click, []), returnValueForMissingStub: null); @override void focus() => super.noSuchMethod(Invocation.method(#focus, []), returnValueForMissingStub: null); @override _i2.ShadowRoot attachShadow(Map<dynamic, dynamic>? shadowRootInitDict) => (super.noSuchMethod( Invocation.method(#attachShadow, [shadowRootInitDict]), returnValue: _FakeShadowRoot_11()) as _i2.ShadowRoot); @override _i2.Element? closest(String? selectors) => (super.noSuchMethod(Invocation.method(#closest, [selectors])) as _i2.Element?); @override List<_i2.Animation> getAnimations() => (super.noSuchMethod(Invocation.method(#getAnimations, []), returnValue: <_i2.Animation>[]) as List<_i2.Animation>); @override List<String> getAttributeNames() => (super.noSuchMethod(Invocation.method(#getAttributeNames, []), returnValue: <String>[]) as List<String>); @override _i3.Rectangle<num> getBoundingClientRect() => (super.noSuchMethod(Invocation.method(#getBoundingClientRect, []), returnValue: _FakeRectangle_1<num>()) as _i3.Rectangle<num>); @override List<_i2.Node> getDestinationInsertionPoints() => (super.noSuchMethod(Invocation.method(#getDestinationInsertionPoints, []), returnValue: <_i2.Node>[]) as List<_i2.Node>); @override List<_i2.Node> getElementsByClassName(String? classNames) => (super .noSuchMethod(Invocation.method(#getElementsByClassName, [classNames]), returnValue: <_i2.Node>[]) as List<_i2.Node>); @override bool hasPointerCapture(int? pointerId) => (super.noSuchMethod(Invocation.method(#hasPointerCapture, [pointerId]), returnValue: false) as bool); @override void releasePointerCapture(int? pointerId) => super.noSuchMethod(Invocation.method(#releasePointerCapture, [pointerId]), returnValueForMissingStub: null); @override void requestPointerLock() => super.noSuchMethod(Invocation.method(#requestPointerLock, []), returnValueForMissingStub: null); @override void scroll([dynamic options_OR_x, num? y]) => super.noSuchMethod(Invocation.method(#scroll, [options_OR_x, y]), returnValueForMissingStub: null); @override void scrollBy([dynamic options_OR_x, num? y]) => super.noSuchMethod(Invocation.method(#scrollBy, [options_OR_x, y]), returnValueForMissingStub: null); @override void scrollTo([dynamic options_OR_x, num? y]) => super.noSuchMethod(Invocation.method(#scrollTo, [options_OR_x, y]), returnValueForMissingStub: null); @override void setPointerCapture(int? pointerId) => super.noSuchMethod(Invocation.method(#setPointerCapture, [pointerId]), returnValueForMissingStub: null); // TODO(ditman): Undo this manual change when the return type change to // Future<void> has propagated to stable. /*@override void requestFullscreen() => super.noSuchMethod(Invocation.method(#requestFullscreen, []), returnValueForMissingStub: null);*/ @override void after(Object? nodes) => super.noSuchMethod(Invocation.method(#after, [nodes]), returnValueForMissingStub: null); @override void before(Object? nodes) => super.noSuchMethod(Invocation.method(#before, [nodes]), returnValueForMissingStub: null); @override _i2.Element? querySelector(String? selectors) => (super.noSuchMethod(Invocation.method(#querySelector, [selectors])) as _i2.Element?); @override void remove() => super.noSuchMethod(Invocation.method(#remove, []), returnValueForMissingStub: null); @override _i2.Node replaceWith(_i2.Node? otherNode) => (super.noSuchMethod(Invocation.method(#replaceWith, [otherNode]), returnValue: _FakeNode_13()) as _i2.Node); @override void insertAllBefore(Iterable<_i2.Node>? newNodes, _i2.Node? refChild) => super.noSuchMethod( Invocation.method(#insertAllBefore, [newNodes, refChild]), returnValueForMissingStub: null); @override _i2.Node append(_i2.Node? node) => (super.noSuchMethod(Invocation.method(#append, [node]), returnValue: _FakeNode_13()) as _i2.Node); @override _i2.Node clone(bool? deep) => (super.noSuchMethod(Invocation.method(#clone, [deep]), returnValue: _FakeNode_13()) as _i2.Node); @override bool contains(_i2.Node? other) => (super.noSuchMethod(Invocation.method(#contains, [other]), returnValue: false) as bool); @override _i2.Node getRootNode([Map<dynamic, dynamic>? options]) => (super.noSuchMethod(Invocation.method(#getRootNode, [options]), returnValue: _FakeNode_13()) as _i2.Node); @override bool hasChildNodes() => (super.noSuchMethod(Invocation.method(#hasChildNodes, []), returnValue: false) as bool); @override _i2.Node insertBefore(_i2.Node? node, _i2.Node? child) => (super.noSuchMethod(Invocation.method(#insertBefore, [node, child]), returnValue: _FakeNode_13()) as _i2.Node); @override void addEventListener(String? type, _i2.EventListener? listener, [bool? useCapture]) => super.noSuchMethod( Invocation.method(#addEventListener, [type, listener, useCapture]), returnValueForMissingStub: null); @override void removeEventListener(String? type, _i2.EventListener? listener, [bool? useCapture]) => super.noSuchMethod( Invocation.method(#removeEventListener, [type, listener, useCapture]), returnValueForMissingStub: null); @override bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(Invocation.method(#dispatchEvent, [event]), returnValue: false) as bool); } /// A class which mocks [BuildContext]. /// /// See the documentation for Mockito's code generation for more information. class MockBuildContext extends _i1.Mock implements _i4.BuildContext { MockBuildContext() { _i1.throwOnMissingStub(this); } @override _i4.Widget get widget => (super.noSuchMethod(Invocation.getter(#widget), returnValue: _FakeWidget_14()) as _i4.Widget); @override bool get debugDoingBuild => (super .noSuchMethod(Invocation.getter(#debugDoingBuild), returnValue: false) as bool); @override _i4.InheritedWidget dependOnInheritedElement(_i4.InheritedElement? ancestor, {Object? aspect}) => (super.noSuchMethod( Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}), returnValue: _FakeInheritedWidget_15()) as _i4.InheritedWidget); @override void visitAncestorElements(bool Function(_i4.Element)? visitor) => super.noSuchMethod(Invocation.method(#visitAncestorElements, [visitor]), returnValueForMissingStub: null); @override void visitChildElements(_i4.ElementVisitor? visitor) => super.noSuchMethod(Invocation.method(#visitChildElements, [visitor]), returnValueForMissingStub: null); @override _i5.DiagnosticsNode describeElement(String? name, {_i5.DiagnosticsTreeStyle? style = _i5.DiagnosticsTreeStyle.errorProperty}) => (super.noSuchMethod( Invocation.method(#describeElement, [name], {#style: style}), returnValue: _FakeDiagnosticsNode_16()) as _i5.DiagnosticsNode); @override _i5.DiagnosticsNode describeWidget(String? name, {_i5.DiagnosticsTreeStyle? style = _i5.DiagnosticsTreeStyle.errorProperty}) => (super.noSuchMethod( Invocation.method(#describeWidget, [name], {#style: style}), returnValue: _FakeDiagnosticsNode_16()) as _i5.DiagnosticsNode); @override List<_i5.DiagnosticsNode> describeMissingAncestor( {Type? expectedAncestorType}) => (super.noSuchMethod( Invocation.method(#describeMissingAncestor, [], {#expectedAncestorType: expectedAncestorType}), returnValue: <_i5.DiagnosticsNode>[]) as List<_i5.DiagnosticsNode>); @override _i5.DiagnosticsNode describeOwnershipChain(String? name) => (super.noSuchMethod(Invocation.method(#describeOwnershipChain, [name]), returnValue: _FakeDiagnosticsNode_16()) as _i5.DiagnosticsNode); @override String toString() => super.toString(); } /// A class which mocks [CreationParams]. /// /// See the documentation for Mockito's code generation for more information. class MockCreationParams extends _i1.Mock implements _i7.CreationParams { MockCreationParams() { _i1.throwOnMissingStub(this); } @override Set<String> get javascriptChannelNames => (super.noSuchMethod(Invocation.getter(#javascriptChannelNames), returnValue: <String>{}) as Set<String>); @override _i8.AutoMediaPlaybackPolicy get autoMediaPlaybackPolicy => (super.noSuchMethod(Invocation.getter(#autoMediaPlaybackPolicy), returnValue: _i8.AutoMediaPlaybackPolicy .require_user_action_for_all_media_types) as _i8.AutoMediaPlaybackPolicy); @override List<_i7.WebViewCookie> get cookies => (super.noSuchMethod(Invocation.getter(#cookies), returnValue: <_i7.WebViewCookie>[]) as List<_i7.WebViewCookie>); @override String toString() => super.toString(); } /// A class which mocks [WebViewPlatformCallbacksHandler]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatformCallbacksHandler extends _i1.Mock implements _i9.WebViewPlatformCallbacksHandler { MockWebViewPlatformCallbacksHandler() { _i1.throwOnMissingStub(this); } @override _i6.FutureOr<bool> onNavigationRequest({String? url, bool? isForMainFrame}) => (super.noSuchMethod( Invocation.method(#onNavigationRequest, [], {#url: url, #isForMainFrame: isForMainFrame}), returnValue: Future<bool>.value(false)) as _i6.FutureOr<bool>); @override void onPageStarted(String? url) => super.noSuchMethod(Invocation.method(#onPageStarted, [url]), returnValueForMissingStub: null); @override void onPageFinished(String? url) => super.noSuchMethod(Invocation.method(#onPageFinished, [url]), returnValueForMissingStub: null); @override void onProgress(int? progress) => super.noSuchMethod(Invocation.method(#onProgress, [progress]), returnValueForMissingStub: null); @override void onWebResourceError(_i7.WebResourceError? error) => super.noSuchMethod(Invocation.method(#onWebResourceError, [error]), returnValueForMissingStub: null); @override String toString() => super.toString(); } /// A class which mocks [HttpRequestFactory]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequestFactory extends _i1.Mock implements _i10.HttpRequestFactory { MockHttpRequestFactory() { _i1.throwOnMissingStub(this); } @override _i6.Future<_i2.HttpRequest> request(String? url, {String? method, bool? withCredentials, String? responseType, String? mimeType, Map<String, String>? requestHeaders, dynamic sendData, void Function(_i2.ProgressEvent)? onProgress}) => (super.noSuchMethod( Invocation.method(#request, [ url ], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress }), returnValue: Future<_i2.HttpRequest>.value(_FakeHttpRequest_17())) as _i6.Future<_i2.HttpRequest>); @override String toString() => super.toString(); } /// A class which mocks [HttpRequest]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequest extends _i1.Mock implements _i2.HttpRequest { MockHttpRequest() { _i1.throwOnMissingStub(this); } @override Map<String, String> get responseHeaders => (super.noSuchMethod(Invocation.getter(#responseHeaders), returnValue: <String, String>{}) as Map<String, String>); @override int get readyState => (super.noSuchMethod(Invocation.getter(#readyState), returnValue: 0) as int); @override String get responseType => (super.noSuchMethod(Invocation.getter(#responseType), returnValue: '') as String); @override set responseType(String? value) => super.noSuchMethod(Invocation.setter(#responseType, value), returnValueForMissingStub: null); @override set timeout(int? value) => super.noSuchMethod(Invocation.setter(#timeout, value), returnValueForMissingStub: null); @override _i2.HttpRequestUpload get upload => (super.noSuchMethod(Invocation.getter(#upload), returnValue: _FakeHttpRequestUpload_18()) as _i2.HttpRequestUpload); @override set withCredentials(bool? value) => super.noSuchMethod(Invocation.setter(#withCredentials, value), returnValueForMissingStub: null); @override _i6.Stream<_i2.Event> get onReadyStateChange => (super.noSuchMethod(Invocation.getter(#onReadyStateChange), returnValue: Stream<_i2.Event>.empty()) as _i6.Stream<_i2.Event>); @override _i6.Stream<_i2.ProgressEvent> get onAbort => (super.noSuchMethod(Invocation.getter(#onAbort), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onError => (super.noSuchMethod(Invocation.getter(#onError), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onLoad => (super.noSuchMethod(Invocation.getter(#onLoad), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onLoadEnd => (super.noSuchMethod(Invocation.getter(#onLoadEnd), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onLoadStart => (super.noSuchMethod(Invocation.getter(#onLoadStart), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onProgress => (super.noSuchMethod(Invocation.getter(#onProgress), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i6.Stream<_i2.ProgressEvent> get onTimeout => (super.noSuchMethod(Invocation.getter(#onTimeout), returnValue: Stream<_i2.ProgressEvent>.empty()) as _i6.Stream<_i2.ProgressEvent>); @override _i2.Events get on => (super.noSuchMethod(Invocation.getter(#on), returnValue: _FakeEvents_19()) as _i2.Events); @override void open(String? method, String? url, {bool? async, String? user, String? password}) => super.noSuchMethod( Invocation.method(#open, [method, url], {#async: async, #user: user, #password: password}), returnValueForMissingStub: null); @override void abort() => super.noSuchMethod(Invocation.method(#abort, []), returnValueForMissingStub: null); @override String getAllResponseHeaders() => (super.noSuchMethod(Invocation.method(#getAllResponseHeaders, []), returnValue: '') as String); @override String? getResponseHeader(String? name) => (super.noSuchMethod(Invocation.method(#getResponseHeader, [name])) as String?); @override void overrideMimeType(String? mime) => super.noSuchMethod(Invocation.method(#overrideMimeType, [mime]), returnValueForMissingStub: null); @override void send([dynamic body_OR_data]) => super.noSuchMethod(Invocation.method(#send, [body_OR_data]), returnValueForMissingStub: null); @override void setRequestHeader(String? name, String? value) => super.noSuchMethod(Invocation.method(#setRequestHeader, [name, value]), returnValueForMissingStub: null); @override void addEventListener(String? type, _i2.EventListener? listener, [bool? useCapture]) => super.noSuchMethod( Invocation.method(#addEventListener, [type, listener, useCapture]), returnValueForMissingStub: null); @override void removeEventListener(String? type, _i2.EventListener? listener, [bool? useCapture]) => super.noSuchMethod( Invocation.method(#removeEventListener, [type, listener, useCapture]), returnValueForMissingStub: null); @override bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(Invocation.method(#dispatchEvent, [event]), returnValue: false) as bool); @override String toString() => super.toString(); }
plugins/packages/webview_flutter/webview_flutter_web/test/webview_flutter_web_test.mocks.dart/0
{'file_path': 'plugins/packages/webview_flutter/webview_flutter_web/test/webview_flutter_web_test.mocks.dart', 'repo_id': 'plugins', 'token_count': 22426}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:path/path.dart' as p; import 'package:pubspec_parse/pubspec_parse.dart'; import 'core.dart'; /// A package in the repository. // // TODO(stuartmorgan): Add more package-related info here, such as an on-demand // cache of the parsed pubspec. class RepositoryPackage { /// Creates a representation of the package at [directory]. RepositoryPackage(this.directory); /// The location of the package. final Directory directory; /// The path to the package. String get path => directory.path; /// Returns the string to use when referring to the package in user-targeted /// messages. /// /// Callers should not expect a specific format for this string, since /// it uses heuristics to try to be precise without being overly verbose. If /// an exact format (e.g., published name, or basename) is required, that /// should be used instead. String get displayName { List<String> components = directory.fileSystem.path.split(directory.path); // Remove everything up to the packages directory. final int packagesIndex = components.indexOf('packages'); if (packagesIndex != -1) { components = components.sublist(packagesIndex + 1); } // For the common federated plugin pattern of `foo/foo_subpackage`, drop // the first part since it's not useful. if (components.length >= 2 && components[1].startsWith('${components[0]}_')) { components = components.sublist(1); } return p.posix.joinAll(components); } /// The package's top-level pubspec.yaml. File get pubspecFile => directory.childFile('pubspec.yaml'); late final Pubspec _parsedPubspec = Pubspec.parse(pubspecFile.readAsStringSync()); /// Returns the parsed [pubspecFile]. /// /// Caches for future use. Pubspec parsePubspec() => _parsedPubspec; /// True if this appears to be a federated plugin package, according to /// repository conventions. bool get isFederated => directory.parent.basename != 'packages' && directory.basename.startsWith(directory.parent.basename); /// True if this appears to be a platform interface package, according to /// repository conventions. bool get isPlatformInterface => directory.basename.endsWith('_platform_interface'); /// True if this appears to be a platform implementation package, according to /// repository conventions. bool get isPlatformImplementation => // Any part of a federated plugin that isn't the platform interface and // isn't the app-facing package should be an implementation package. isFederated && !isPlatformInterface && directory.basename != directory.parent.basename; /// Returns the Flutter example packages contained in the package, if any. Iterable<RepositoryPackage> getExamples() { final Directory exampleDirectory = directory.childDirectory('example'); if (!exampleDirectory.existsSync()) { return <RepositoryPackage>[]; } if (isFlutterPackage(exampleDirectory)) { return <RepositoryPackage>[RepositoryPackage(exampleDirectory)]; } // Only look at the subdirectories of the example directory if the example // directory itself is not a Dart package, and only look one level below the // example directory for other Dart packages. return exampleDirectory .listSync() .where((FileSystemEntity entity) => isFlutterPackage(entity)) // isFlutterPackage guarantees that the cast to Directory is safe. .map((FileSystemEntity entity) => RepositoryPackage(entity as Directory)); } /// Returns the example directory, assuming there is only one. /// /// DO NOT USE THIS METHOD. It exists only to easily find code that was /// written to use a single example and needs to be restructured to handle /// multiple examples. New code should always use [getExamples]. // TODO(stuartmorgan): Eliminate all uses of this. RepositoryPackage getSingleExampleDeprecated() => RepositoryPackage(directory.childDirectory('example')); }
plugins/script/tool/lib/src/common/repository_package.dart/0
{'file_path': 'plugins/script/tool/lib/src/common/repository_package.dart', 'repo_id': 'plugins', 'token_count': 1235}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:git/git.dart'; import 'package:platform/platform.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:yaml/yaml.dart'; import 'common/core.dart'; import 'common/package_looping_command.dart'; import 'common/process_runner.dart'; import 'common/repository_package.dart'; /// A command to enforce pubspec conventions across the repository. /// /// This both ensures that repo best practices for which optional fields are /// used are followed, and that the structure is consistent to make edits /// across multiple pubspec files easier. class PubspecCheckCommand extends PackageLoopingCommand { /// Creates an instance of the version check command. PubspecCheckCommand( Directory packagesDir, { ProcessRunner processRunner = const ProcessRunner(), Platform platform = const LocalPlatform(), GitDir? gitDir, }) : super( packagesDir, processRunner: processRunner, platform: platform, gitDir: gitDir, ); // Section order for plugins. Because the 'flutter' section is critical // information for plugins, and usually small, it goes near the top unlike in // a normal app or package. static const List<String> _majorPluginSections = <String>[ 'environment:', 'flutter:', 'dependencies:', 'dev_dependencies:', 'false_secrets:', ]; static const List<String> _majorPackageSections = <String>[ 'environment:', 'dependencies:', 'dev_dependencies:', 'flutter:', 'false_secrets:', ]; static const String _expectedIssueLinkFormat = 'https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A'; @override final String name = 'pubspec-check'; @override final String description = 'Checks that pubspecs follow repository conventions.'; @override bool get hasLongOutput => false; @override bool get includeSubpackages => true; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final File pubspec = package.pubspecFile; final bool passesCheck = !pubspec.existsSync() || await _checkPubspec(pubspec, package: package); if (!passesCheck) { return PackageResult.fail(); } return PackageResult.success(); } Future<bool> _checkPubspec( File pubspecFile, { required RepositoryPackage package, }) async { final String contents = pubspecFile.readAsStringSync(); final Pubspec? pubspec = _tryParsePubspec(contents); if (pubspec == null) { return false; } final List<String> pubspecLines = contents.split('\n'); final bool isPlugin = pubspec.flutter?.containsKey('plugin') ?? false; final List<String> sectionOrder = isPlugin ? _majorPluginSections : _majorPackageSections; bool passing = _checkSectionOrder(pubspecLines, sectionOrder); if (!passing) { printError('${indentation}Major sections should follow standard ' 'repository ordering:'); final String listIndentation = indentation * 2; printError('$listIndentation${sectionOrder.join('\n$listIndentation')}'); } if (isPlugin) { final String? implementsError = _checkForImplementsError(pubspec, package: package); if (implementsError != null) { printError('$indentation$implementsError'); passing = false; } final String? defaultPackageError = _checkForDefaultPackageError(pubspec, package: package); if (defaultPackageError != null) { printError('$indentation$defaultPackageError'); passing = false; } } // Ignore metadata that's only relevant for published packages if the // packages is not intended for publishing. if (pubspec.publishTo != 'none') { final List<String> repositoryErrors = _checkForRepositoryLinkErrors(pubspec, package: package); if (repositoryErrors.isNotEmpty) { for (final String error in repositoryErrors) { printError('$indentation$error'); } passing = false; } if (!_checkIssueLink(pubspec)) { printError( '${indentation}A package should have an "issue_tracker" link to a ' 'search for open flutter/flutter bugs with the relevant label:\n' '${indentation * 2}$_expectedIssueLinkFormat<package label>'); passing = false; } // Don't check descriptions for federated package components other than // the app-facing package, since they are unlisted, and are expected to // have short descriptions. if (!package.isPlatformInterface && !package.isPlatformImplementation) { final String? descriptionError = _checkDescription(pubspec, package: package); if (descriptionError != null) { printError('$indentation$descriptionError'); passing = false; } } } return passing; } Pubspec? _tryParsePubspec(String pubspecContents) { try { return Pubspec.parse(pubspecContents); } on Exception catch (exception) { print(' Cannot parse pubspec.yaml: $exception'); } return null; } bool _checkSectionOrder( List<String> pubspecLines, List<String> sectionOrder) { int previousSectionIndex = 0; for (final String line in pubspecLines) { final int index = sectionOrder.indexOf(line); if (index == -1) { continue; } if (index < previousSectionIndex) { return false; } previousSectionIndex = index; } return true; } List<String> _checkForRepositoryLinkErrors( Pubspec pubspec, { required RepositoryPackage package, }) { final List<String> errorMessages = <String>[]; if (pubspec.repository == null) { errorMessages.add('Missing "repository"'); } else { final String relativePackagePath = getRelativePosixPath(package.directory, from: packagesDir.parent); if (!pubspec.repository!.path.endsWith(relativePackagePath)) { errorMessages .add('The "repository" link should end with the package path.'); } } if (pubspec.homepage != null) { errorMessages .add('Found a "homepage" entry; only "repository" should be used.'); } return errorMessages; } // Validates the "description" field for a package, returning an error // string if there are any issues. String? _checkDescription( Pubspec pubspec, { required RepositoryPackage package, }) { final String? description = pubspec.description; if (description == null) { return 'Missing "description"'; } if (description.length < 60) { return '"description" is too short. pub.dev recommends package ' 'descriptions of 60-180 characters.'; } if (description.length > 180) { return '"description" is too long. pub.dev recommends package ' 'descriptions of 60-180 characters.'; } return null; } bool _checkIssueLink(Pubspec pubspec) { return pubspec.issueTracker ?.toString() .startsWith(_expectedIssueLinkFormat) == true; } // Validates the "implements" keyword for a plugin, returning an error // string if there are any issues. // // Should only be called on plugin packages. String? _checkForImplementsError( Pubspec pubspec, { required RepositoryPackage package, }) { if (_isImplementationPackage(package)) { final String? implements = pubspec.flutter!['plugin']!['implements'] as String?; final String expectedImplements = package.directory.parent.basename; if (implements == null) { return 'Missing "implements: $expectedImplements" in "plugin" section.'; } else if (implements != expectedImplements) { return 'Expecetd "implements: $expectedImplements"; ' 'found "implements: $implements".'; } } return null; } // Validates any "default_package" entries a plugin, returning an error // string if there are any issues. // // Should only be called on plugin packages. String? _checkForDefaultPackageError( Pubspec pubspec, { required RepositoryPackage package, }) { final dynamic platformsEntry = pubspec.flutter!['plugin']!['platforms']; if (platformsEntry == null) { logWarning('Does not implement any platforms'); return null; } final YamlMap platforms = platformsEntry as YamlMap; final String packageName = package.directory.basename; // Validate that the default_package entries look correct (e.g., no typos). final Set<String> defaultPackages = <String>{}; for (final MapEntry<dynamic, dynamic> platformEntry in platforms.entries) { final String? defaultPackage = platformEntry.value['default_package'] as String?; if (defaultPackage != null) { defaultPackages.add(defaultPackage); if (!defaultPackage.startsWith('${packageName}_')) { return '"$defaultPackage" is not an expected implementation name ' 'for "$packageName"'; } } } // Validate that all default_packages are also dependencies. final Iterable<String> dependencies = pubspec.dependencies.keys; final Iterable<String> missingPackages = defaultPackages .where((String package) => !dependencies.contains(package)); if (missingPackages.isNotEmpty) { return 'The following default_packages are missing ' 'corresponding dependencies:\n ' + missingPackages.join('\n '); } return null; } // Returns true if [packageName] appears to be an implementation package // according to repository conventions. bool _isImplementationPackage(RepositoryPackage package) { if (!package.isFederated) { return false; } final String packageName = package.directory.basename; final String parentName = package.directory.parent.basename; // A few known package names are not implementation packages; assume // anything else is. (This is done instead of listing known implementation // suffixes to allow for non-standard suffixes; e.g., to put several // platforms in one package for code-sharing purposes.) const Set<String> nonImplementationSuffixes = <String>{ '', // App-facing package. '_platform_interface', // Platform interface package. }; final String suffix = packageName.substring(parentName.length); return !nonImplementationSuffixes.contains(suffix); } }
plugins/script/tool/lib/src/pubspec_check_command.dart/0
{'file_path': 'plugins/script/tool/lib/src/pubspec_check_command.dart', 'repo_id': 'plugins', 'token_count': 3787}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/test_command.dart'; import 'package:platform/platform.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('$TestCommand', () { late FileSystem fileSystem; late Platform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final TestCommand command = TestCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>('test_test', 'Test for $TestCommand'); runner.addCommand(command); }); test('runs flutter test on each plugin', () async { final Directory plugin1Dir = createFakePlugin('plugin1', packagesDir, extraFiles: <String>['test/empty_test.dart']); final Directory plugin2Dir = createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint(runner, <String>['test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin1Dir.path), ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin2Dir.path), ]), ); }); test('fails when Flutter tests fail', () async { createFakePlugin('plugin1', packagesDir, extraFiles: <String>['test/empty_test.dart']); createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <io.Process>[ MockProcess(exitCode: 1), // plugin 1 test MockProcess(), // plugin 2 test ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin1'), ])); }); test('skips testing plugins without test directory', () async { createFakePlugin('plugin1', packagesDir); final Directory plugin2Dir = createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint(runner, <String>['test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin2Dir.path), ]), ); }); test('runs pub run test on non-Flutter packages', () async { final Directory pluginDir = createFakePlugin('a', packagesDir, extraFiles: <String>['test/empty_test.dart']); final Directory packageDir = createFakePackage('b', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint( runner, <String>['test', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--enable-experiment=exp1'], pluginDir.path), ProcessCall('dart', const <String>['pub', 'get'], packageDir.path), ProcessCall( 'dart', const <String>['pub', 'run', '--enable-experiment=exp1', 'test'], packageDir.path), ]), ); }); test('fails when getting non-Flutter package dependencies fails', () async { createFakePackage('a_package', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner.mockProcessesForExecutable['dart'] = <io.Process>[ MockProcess(exitCode: 1), // dart pub get ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Unable to fetch dependencies'), contains('The following packages had errors:'), contains(' a_package'), ])); }); test('fails when non-Flutter tests fail', () async { createFakePackage('a_package', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner.mockProcessesForExecutable['dart'] = <io.Process>[ MockProcess(), // dart pub get MockProcess(exitCode: 1), // dart pub run test ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' a_package'), ])); }); test('runs on Chrome for web plugins', () async { final Directory pluginDir = createFakePlugin( 'plugin', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ kPlatformWeb: const PlatformDetails(PlatformSupport.inline), }, ); await runCapturingPrint(runner, <String>['test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome'], pluginDir.path), ]), ); }); test('enable-experiment flag', () async { final Directory pluginDir = createFakePlugin('a', packagesDir, extraFiles: <String>['test/empty_test.dart']); final Directory packageDir = createFakePackage('b', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint( runner, <String>['test', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--enable-experiment=exp1'], pluginDir.path), ProcessCall('dart', const <String>['pub', 'get'], packageDir.path), ProcessCall( 'dart', const <String>['pub', 'run', '--enable-experiment=exp1', 'test'], packageDir.path), ]), ); }); }); }
plugins/script/tool/test/test_command_test.dart/0
{'file_path': 'plugins/script/tool/test/test_command_test.dart', 'repo_id': 'plugins', 'token_count': 3159}
import 'package:flutter/material.dart'; @immutable class CoordinatorBase { const CoordinatorBase(this.navigatorKey) : assert(navigatorKey != null); final GlobalKey<NavigatorState> navigatorKey; NavigatorState get navigator => navigatorKey?.currentState; }
pnyws/lib/coordinator/coordinator_base.dart/0
{'file_path': 'pnyws/lib/coordinator/coordinator_base.dart', 'repo_id': 'pnyws', 'token_count': 77}
import 'package:pnyws/environments/environment.dart'; import 'package:pnyws/main.dart' as def; void main() => def.main(delay: 1, environment: Environment.PRODUCTION);
pnyws/lib/main_prod.dart/0
{'file_path': 'pnyws/lib/main_prod.dart', 'repo_id': 'pnyws', 'token_count': 56}
import 'package:pnyws/data/data.dart'; class AppState { const AppState({this.account}); final AccountData account; AppState copyWith({AccountData account}) { return AppState(account: account ?? this.account); } }
pnyws/lib/state/app_state.dart/0
{'file_path': 'pnyws/lib/state/app_state.dart', 'repo_id': 'pnyws', 'token_count': 72}
import 'package:pnyws/constants/mk_strings.dart'; class NoInternetException extends MkException { NoInternetException() : super(MkStrings.networkError); } class MkException implements Exception { MkException([this.message]); final String message; @override String toString() => message == null ? "$runtimeType" : "$runtimeType($message)"; }
pnyws/lib/wrappers/mk_exceptions.dart/0
{'file_path': 'pnyws/lib/wrappers/mk_exceptions.dart', 'repo_id': 'pnyws', 'token_count': 101}
import 'package:flame/components/resizable.dart'; import 'game.dart'; class Camera extends Resizable { MyGame gameRef; Camera(this.gameRef); void handle(double dt) { if (gameRef.player == null) { return; } gameRef.camera.x = gameRef.player.x - size.width / 2 + gameRef.player.width / 2; gameRef.camera.y = gameRef.player.y - size.height / 2 + gameRef.player.height / 2; } }
pocket-dungeons/game/lib/camera.dart/0
{'file_path': 'pocket-dungeons/game/lib/camera.dart', 'repo_id': 'pocket-dungeons', 'token_count': 156}
import '../engine/coords.dart'; import '../engine/matrix.dart'; import 'enemy_type.dart'; class Dungeon { Matrix<int> matrix; Coords initialCoords; Map<Coords, EnemyType> enemies; Dungeon(this.matrix, this.initialCoords, this.enemies); Matrix<EnemyType> objects() { // TODO this return null; } }
pocket-dungeons/game/lib/map_gen/dungeon.dart/0
{'file_path': 'pocket-dungeons/game/lib/map_gen/dungeon.dart', 'repo_id': 'pocket-dungeons', 'token_count': 117}
import 'package:provider_example/core/enums/viewstate.dart'; import 'package:provider_example/core/models/post.dart'; import 'package:provider_example/core/services/api.dart'; import 'base_model.dart'; class HomeModel extends BaseModel { Api _api; Api get api => _api; set api(Api api) { _api = api; notifyListeners(); } int _userId; int get userId => _userId; set userId(int userId) { if (_userId != userId) { _userId = userId; _getPosts(userId); notifyListeners(); } } List<Post> posts = []; Future _getPosts(int userId) async { if (state == ViewState.Busy) { throw StateError( "fetching posts again when the current request haven't finished"); } setState(ViewState.Busy); posts = await _api.getPostsForUser(userId); setState(ViewState.Idle); } }
provider-example/lib/core/viewmodels/home_model.dart/0
{'file_path': 'provider-example/lib/core/viewmodels/home_model.dart', 'repo_id': 'provider-example', 'token_count': 337}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'postlist_item.dart'; // ************************************************************************** // FunctionalWidgetGenerator // ************************************************************************** class PostListItem extends StatelessWidget { const PostListItem({Key key}) : super(key: key); @override Widget build(BuildContext _context) => postListItem(_context); } class _PostListItem extends StatelessWidget { const _PostListItem({Key key, this.title, this.body, this.onTap}) : super(key: key); final Widget title; final Widget body; final VoidCallback onTap; @override Widget build(BuildContext _context) => _postListItem(title: title, body: body, onTap: onTap); }
provider-example/lib/ui/widgets/postlist_item.g.dart/0
{'file_path': 'provider-example/lib/ui/widgets/postlist_item.g.dart', 'repo_id': 'provider-example', 'token_count': 215}
import 'package:flutter/widgets.dart' hide TypeMatcher; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; // ignore: deprecated_member_use import 'package:test_api/test_api.dart' show TypeMatcher; import 'common.dart'; void main() { testWidgets('works with MultiProvider', (tester) async { await tester.pumpWidget( MultiProvider( providers: [ Provider.value( value: 42, ), ], child: const TextOf<int>(), ), ); expect(find.text('42'), findsOneWidget); }); group('Provider.of', () { testWidgets('throws if T is dynamic', (tester) async { await tester.pumpWidget( Provider<dynamic>.value( value: 42, child: Container(), ), ); expect( () => Provider.of<dynamic>(tester.element(find.byType(Container))), throwsAssertionError, ); }); testWidgets( 'listen defaults to true when building widgets', (tester) async { var buildCount = 0; final child = Builder( builder: (context) { buildCount++; Provider.of<int>(context); return Container(); }, ); await tester.pumpWidget( InheritedProvider<int>.value( value: 42, child: child, ), ); expect(buildCount, equals(1)); await tester.pumpWidget( InheritedProvider<int>.value( value: 24, child: child, ), ); expect(buildCount, equals(2)); }, ); testWidgets( 'listen defaults to false outside of the widget tree', (tester) async { var buildCount = 0; final child = Builder( builder: (context) { buildCount++; return Container(); }, ); await tester.pumpWidget( InheritedProvider<int>.value( value: 42, child: child, ), ); final context = tester.element(find.byWidget(child)); Provider.of<int>(context, listen: false); expect(buildCount, equals(1)); await tester.pumpWidget( InheritedProvider<int>.value( value: 24, child: child, ), ); expect(buildCount, equals(1)); }, ); testWidgets( "listen:false doesn't trigger rebuild", (tester) async { var buildCount = 0; final child = Builder( builder: (context) { Provider.of<int>(context, listen: false); buildCount++; return Container(); }, ); await tester.pumpWidget( InheritedProvider<int>.value( value: 42, child: child, ), ); expect(buildCount, equals(1)); await tester.pumpWidget( InheritedProvider<int>.value( value: 24, child: child, ), ); expect(buildCount, equals(1)); }, ); testWidgets( 'listen:true outside of the widget tree throws', (tester) async { final child = Builder( builder: (context) { return Container(); }, ); await tester.pumpWidget( InheritedProvider<int>.value( value: 42, child: child, ), ); final context = tester.element(find.byWidget(child)); expect( () => Provider.of<int>(context, listen: true), throwsAssertionError, ); }, ); }); group('Provider', () { testWidgets('throws if the provided value is a Listenable/Stream', (tester) async { expect( () => Provider.value( value: MyListenable(), child: const TextOf<MyListenable>(), ), throwsFlutterError, ); expect( () => Provider.value( value: MyStream(), child: const TextOf<MyListenable>(), ), throwsFlutterError, ); await tester.pumpWidget( Provider( key: UniqueKey(), create: (_) => MyListenable(), child: const TextOf<MyListenable>(), ), ); expect(tester.takeException(), isFlutterError); await tester.pumpWidget( Provider( key: UniqueKey(), create: (_) => MyStream(), child: const TextOf<MyStream>(), ), ); expect(tester.takeException(), isFlutterError); }); testWidgets('debugCheckInvalidValueType can be disabled', (tester) async { final previous = Provider.debugCheckInvalidValueType; Provider.debugCheckInvalidValueType = null; addTearDown(() => Provider.debugCheckInvalidValueType = previous); await tester.pumpWidget( Provider.value( value: MyListenable(), child: const TextOf<MyListenable>(), ), ); await tester.pumpWidget( Provider.value( value: MyStream(), child: const TextOf<MyStream>(), ), ); }); testWidgets('simple usage', (tester) async { var buildCount = 0; int value; double second; // We voluntarily reuse the builder instance so that later call to // pumpWidget don't call builder again unless subscribed to an // inheritedWidget final builder = Builder( builder: (context) { buildCount++; value = Provider.of<int>(context); second = Provider.of<double>(context, listen: false); return Container(); }, ); await tester.pumpWidget( Provider<double>.value( value: 24.0, child: Provider<int>.value( value: 42, child: builder, ), ), ); expect(value, equals(42)); expect(second, equals(24.0)); expect(buildCount, equals(1)); // nothing changed await tester.pumpWidget( Provider<double>.value( value: 24.0, child: Provider<int>.value( value: 42, child: builder, ), ), ); // didn't rebuild expect(buildCount, equals(1)); // changed a value we are subscribed to await tester.pumpWidget( Provider<double>.value( value: 24.0, child: Provider<int>.value( value: 43, child: builder, ), ), ); expect(value, equals(43)); expect(second, equals(24.0)); // got rebuilt expect(buildCount, equals(2)); // changed a value we are _not_ subscribed to await tester.pumpWidget( Provider<double>.value( value: 20.0, child: Provider<int>.value( value: 43, child: builder, ), ), ); // didn't get rebuilt expect(buildCount, equals(2)); }); testWidgets('throws an error if no provider found', (tester) async { await tester.pumpWidget(Builder(builder: (context) { Provider.of<String>(context); return Container(); })); expect( tester.takeException(), const TypeMatcher<ProviderNotFoundException>() .having((err) => err.valueType, 'valueType', String) .having((err) => err.widgetType, 'widgetType', Builder) .having((err) => err.toString(), 'toString()', ''' Error: Could not find the correct Provider<String> above this Builder Widget To fix, please: * Ensure the Provider<String> is an ancestor to this Builder Widget * Provide types to Provider<String> * Provide types to Consumer<String> * Provide types to Provider.of<String>() * Ensure the correct `context` is being used. If none of these solutions work, please file a bug at: https://github.com/rrousselGit/provider/issues '''), ); }); testWidgets('update should notify', (tester) async { int old; int curr; var callCount = 0; final updateShouldNotify = (int o, int c) { callCount++; old = o; curr = c; return o != c; }; var buildCount = 0; int buildValue; final builder = Builder(builder: (BuildContext context) { buildValue = Provider.of(context); buildCount++; return Container(); }); await tester.pumpWidget( Provider<int>.value( value: 24, updateShouldNotify: updateShouldNotify, child: builder, ), ); expect(callCount, equals(0)); expect(buildCount, equals(1)); expect(buildValue, equals(24)); // value changed await tester.pumpWidget( Provider<int>.value( value: 25, updateShouldNotify: updateShouldNotify, child: builder, ), ); expect(callCount, equals(1)); expect(old, equals(24)); expect(curr, equals(25)); expect(buildCount, equals(2)); expect(buildValue, equals(25)); // value didn't change await tester.pumpWidget( Provider<int>.value( value: 25, updateShouldNotify: updateShouldNotify, child: builder, ), ); expect(callCount, equals(2)); expect(old, equals(25)); expect(curr, equals(25)); expect(buildCount, equals(2)); }); }); }
provider/test/provider_test.dart/0
{'file_path': 'provider/test/provider_test.dart', 'repo_id': 'provider', 'token_count': 4439}
export 'package_info.dart';
pub_updater/lib/src/models/models.dart/0
{'file_path': 'pub_updater/lib/src/models/models.dart', 'repo_id': 'pub_updater', 'token_count': 10}
import 'package:equatable/equatable.dart'; class CaptureCubitState extends Equatable { const CaptureCubitState({ required this.score, required this.chipIndexes, this.maxScore = 5, }); factory CaptureCubitState.initial() => const CaptureCubitState(score: -1, chipIndexes: []); final int score; final List<int> chipIndexes; final int maxScore; CaptureCubitState copyWith({int? score, List<int>? chipIndexes}) => CaptureCubitState( score: score ?? this.score, chipIndexes: chipIndexes ?? this.chipIndexes, maxScore: maxScore, ); @override List<Object> get props => [score, chipIndexes, maxScore]; }
put-flutter-to-work/flutter_nps/lib/capture/cubit/capture_cubit_state.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/lib/capture/cubit/capture_cubit_state.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 244}
abstract class Breakpoints { static const double small = 511; static const double maxHeight = 558; }
put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/spacing/breakpoints.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/spacing/breakpoints.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 30}
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('CaptureScoreSelectorLabels', () { const maxLabel = 'max'; const minLabel = 'min'; testWidgets( 'renders assets and texts', (tester) async { await tester.pumpApp( CaptureScoreSelectorLabels( maxLabel: maxLabel, minLabel: minLabel, ), ); expect(find.text(minLabel), findsOneWidget); expect(find.text(maxLabel), findsOneWidget); expect(find.image(Assets.icons.lovingEmoji), findsOneWidget); expect(find.image(Assets.icons.thumbDownEmoji), findsOneWidget); }, ); }); }
put-flutter-to-work/flutter_nps/packages/app_ui/test/src/widgets/capture_score_selector_labels_test.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/packages/app_ui/test/src/widgets/capture_score_selector_labels_test.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 345}
import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_nps/capture/capture.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockNoSubmitCaptureCubit extends MockCubit<CaptureCubitState> implements CaptureCubit {} class MockSubmitCaptureCubit extends MockCubit<CaptureCubitState> implements CaptureCubit {} void main() { group('CapturePage', () { testWidgets('renders CaptureView fullscreen on width <= 511 screen size', (tester) async { await tester.binding.setSurfaceSize(const Size(Breakpoints.small, 600)); await tester.pumpApp(const CapturePage()); expect( find.ancestor( of: find.byType(CaptureView), matching: find.byType(Scaffold).first, ), findsOneWidget, ); await tester.binding.setSurfaceSize(null); }); testWidgets('renders CaptureView in card on width > 511 screen size', (tester) async { await tester.binding .setSurfaceSize(const Size(Breakpoints.small + 1, 600)); await tester.pumpApp(const CapturePage()); expect( find.ancestor( of: find.byType(CaptureView), matching: find.byType(Card).first, ), findsOneWidget, ); await tester.binding.setSurfaceSize(null); }); }); group('CaptureView', () { late CaptureCubit noSubmitCaptureCubit; late CaptureCubit submitCaptureCubit; setUp(() { noSubmitCaptureCubit = MockNoSubmitCaptureCubit(); submitCaptureCubit = MockSubmitCaptureCubit(); }); testWidgets('renders 5 unselected widget', (tester) async { when(() => noSubmitCaptureCubit.state) .thenReturn(CaptureCubitState.initial()); await tester.pumpApp( BlocProvider( create: (_) => noSubmitCaptureCubit, child: const CaptureView(), ), ); for (var i = 1; i <= 5; i++) { expect( find.widgetWithText(TextButton, i.toString()), findsOneWidget, ); } }); testWidgets('calls selectScore when score is tapped', (tester) async { when(() => noSubmitCaptureCubit.state) .thenReturn(CaptureCubitState.initial()); await tester.pumpApp( BlocProvider.value( value: noSubmitCaptureCubit, child: const CaptureView(), ), ); await tester.tap(find.widgetWithText(TextButton, '1')); verify(() => noSubmitCaptureCubit.selectScore(score: 1)).called(1); }); testWidgets('selectedScore has changed background', (tester) async { when(() => noSubmitCaptureCubit.state) .thenReturn(const CaptureCubitState(score: 1, chipIndexes: [])); await tester.pumpApp( BlocProvider.value( value: noSubmitCaptureCubit, child: const CaptureView(), ), ); final decoration = tester .widget<AnimatedContainer>( find.ancestor( of: find.widgetWithText(TextButton, '1'), matching: find.byType(AnimatedContainer), ), ) .decoration as BoxDecoration?; expect(decoration, isNotNull); expect(decoration?.color, NpsColors.colorSecondary); }); testWidgets('unselected Chip calls addChip when tapped', (tester) async { when(() => noSubmitCaptureCubit.state) .thenReturn(const CaptureCubitState(score: 1, chipIndexes: [])); await tester.pumpApp( BlocProvider.value( value: noSubmitCaptureCubit, child: const CaptureView(), ), ); await tester.tap(find.byType(ActionChip).first); verify( () => noSubmitCaptureCubit.chipToggled(index: any(named: 'index')), ).called(1); }); testWidgets('selected Chip calls removeChip when tapped', (tester) async { when(() => noSubmitCaptureCubit.state) .thenReturn(const CaptureCubitState(score: 1, chipIndexes: [0])); await tester.pumpApp( BlocProvider.value( value: noSubmitCaptureCubit, child: const CaptureView(), ), ); await tester.tap(find.byType(ActionChip).first); verify( () => noSubmitCaptureCubit.chipToggled(index: any(named: 'index')), ).called(1); }); testWidgets('submit button calls cubit submitResult on tap', (tester) async { when(() => submitCaptureCubit.state) .thenReturn(const CaptureCubitState(score: 1, chipIndexes: [1])); when(() => submitCaptureCubit.submitResult()) .thenAnswer((invocation) => Future.value()); await tester.pumpApp( BlocProvider.value( value: submitCaptureCubit, child: const CaptureView(), ), ); final button = find.byKey(const Key('capturePage_submit_elevatedButton')); await tester.dragUntilVisible( button, find.byType(SingleChildScrollView), const Offset(0, 50), ); await tester.tap(button); verify(() => submitCaptureCubit.submitResult()).called(1); }); }); }
put-flutter-to-work/flutter_nps/test/capture/view/capture_page_test.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/test/capture/view/capture_page_test.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 2262}
import 'package:quidpay/quidpay.dart'; import '_bootstrap.dart'; void preauth() async { await PreAuth().preauth( cardno: '5840406187553286', cvv: '116', expirymonth: '12', expiryyear: '21', amount: '2000', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', pin: '1111', redirectUrl: 'https://rave-web.herokuapp.com/receivepayment', ); } void voidCard() async { final _charge = await PreAuth().preauth( cardno: '5840406187553286', cvv: '116', expirymonth: '12', expiryyear: '21', amount: '2000', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', pin: '1111', redirectUrl: 'https://rave-web.herokuapp.com/receivepayment', ); await PreAuth().voidCard(_charge.data!.flwRef); } void refundCard() async { final _charge = await PreAuth().preauth( cardno: '5840406187553286', cvv: '116', expirymonth: '12', expiryyear: '21', amount: '2000', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', pin: '1111', redirectUrl: 'https://rave-web.herokuapp.com/receivepayment', ); await PreAuth().refundCard(_charge.data!.flwRef); } void main() async { init(); // preauth(); voidCard(); // refundCard(); }
quidpay.dart/example/preauth.dart/0
{'file_path': 'quidpay.dart/example/preauth.dart', 'repo_id': 'quidpay.dart', 'token_count': 559}
arb-dir: lib/r13n/arb template-arb-file: app_us.arb
r13n/example/r13n.yaml/0
{'file_path': 'r13n/example/r13n.yaml', 'repo_id': 'r13n', 'token_count': 23}
import 'steerable.dart'; abstract class Behavior { Behavior(this.own); final Steerable own; void update(double dt); }
radiance/lib/src/steering/behavior.dart/0
{'file_path': 'radiance/lib/src/steering/behavior.dart', 'repo_id': 'radiance', 'token_count': 44}
import 'dart:ui'; import 'package:meta/meta.dart'; import 'package:radiance/steering.dart'; import 'package:vector_math/vector_math_64.dart'; abstract class Entity implements Steerable { Entity({ Vector2? position, Vector2? velocity, double? angle, double? angularVelocity, Kinematics? kinematics, double? size, this.behavior, }) : position = position ?? Vector2.zero(), velocity = velocity ?? Vector2.zero(), angle = angle ?? 0, angularVelocity = angularVelocity ?? 0, size = size ?? 0, kinematics = kinematics ?? BasicKinematics() { this.kinematics.handleAttach(this); } final double size; @override final Vector2 position; @override final Vector2 velocity; @override double angle; @override double angularVelocity; @override Kinematics kinematics; Behavior? behavior; _EntityState _savedState = _EntityState(); void render(Canvas canvas); void update(double dt) { behavior?.update(dt); kinematics.update(dt); } List<Vector2> get vectors; @mustCallSuper void saveState() { _savedState = _EntityState() ..position.setFrom(position) ..velocity.setFrom(velocity) ..angle = angle ..angularVelocity = angularVelocity; } @mustCallSuper void restoreState() { position.setFrom(_savedState.position); velocity.setFrom(_savedState.velocity); angle = _savedState.angle; angularVelocity = _savedState.angularVelocity; if (kinematics is HeavyKinematics) { (kinematics as HeavyKinematics).setAcceleration(Vector2.zero()); } } } class _EntityState { Vector2 position = Vector2.zero(); Vector2 velocity = Vector2.zero(); double angle = 0; double angularVelocity = 0; }
radiance/sandbox/lib/entities/entity.dart/0
{'file_path': 'radiance/sandbox/lib/entities/entity.dart', 'repo_id': 'radiance', 'token_count': 647}
import 'package:radiance/steering.dart'; import 'package:test/test.dart' hide throws; import 'package:vector_math/vector_math_64.dart'; import '../../utils/close_to_vector.dart'; import '../../utils/simple_steerable.dart'; import '../../utils/throws.dart'; void main() { group('Flee', () { group('common', () { test('errors', () { final agent = SimpleSteerable(kinematics: LightKinematics(10)); expect( () => Flee(owner: agent, targets: []), throws<AssertionError>('The list of targets to Flee cannot be empty'), ); }); /// Return flee direction against the set of [targets], for an agent with /// initial facing direction given by [orientation]. Vector2 getFleeDirection( List<Vector2> targets, { double orientation = 0, }) { final agent = SimpleSteerable(kinematics: LightKinematics(10)); agent.angle = orientation; final behavior = Flee(owner: agent, targets: targets); expect(agent.position, closeToVector(0, 0)); return behavior.fleeDirection; } // Fleeing from the point you're currently at test('fleeDirection: on target', () { final direction1 = getFleeDirection([Vector2.zero()]); expect(direction1, closeToVector(1, 0)); final direction2 = getFleeDirection([Vector2.zero()], orientation: 1); expect(direction2, closeToVector(0.540302, -0.841471, epsilon: 1e-5)); }); // Fleeing when in the middle of a square test('fleeDirection: surrounded', () { final targets = [ Vector2(0, 10), Vector2(10, 0), Vector2(-10, 0), Vector2(0, -10), ]; final direction = getFleeDirection(targets); expect(direction, closeToVector(1, 0)); }); // When much closer to one of the targets, it becomes dominant test('fleeDirection: uneven', () { final targets = [Vector2(1, 0), Vector2(-5, 5), Vector2(-5, -5)]; final direction = getFleeDirection(targets); expect(direction, closeToVector(-1, 0)); }); }); group(':MaxSpeedKinematics', () { test('properties', () { final agent = SimpleSteerable(kinematics: LightKinematics(10)); final behavior = Flee(owner: agent, targets: [Vector2(20, 10)]); expect(behavior.own, agent); expect(behavior.targets.length, 1); expect(behavior.targets.first, closeToVector(20, 10)); }); test('flee 1', () { final distance = fleeDistance( initialPosition: Vector2(5, 0), initialVelocity: Vector2.zero(), kinematics: LightKinematics(10), duration: 10, ); expect(distance, closeTo(105, 0.1)); }); test('flee 2', () { final distance = fleeDistance( initialPosition: Vector2(12, -10), initialVelocity: Vector2(3, 5), kinematics: LightKinematics(10), ); expect(distance, closeTo(1015.62, 0.01)); }); test('flee 3', () { final distance = fleeDistance( initialPosition: Vector2(0, 0.01), initialVelocity: Vector2.zero(), kinematics: LightKinematics(10), targets: [Vector2(10, 0), Vector2(-10, 3), Vector2(-10, -3)], ); expect(distance, closeTo(999.71, 0.01)); }); /// Normally, the agent is able to escape even if completely surrounded. test('flee 4', () { final distance = fleeDistance( initialPosition: Vector2(0.02, 0.01), initialVelocity: Vector2.zero(), kinematics: LightKinematics(10), targets: [ Vector2(10, 0), Vector2(-10, 0), Vector2(0, 10), Vector2(0, -10), Vector2(7, 7), Vector2(7, -7), Vector2(-7, 7), Vector2(-7, -7), ], ); expect(distance, closeTo(998.22, 0.01)); }); /// However, when the initial configuration is symmetrical with respect /// to the targets, the agent may get "stuck" in infinite loop. test('flee 5', () { final distance = fleeDistance( initialPosition: Vector2.zero(), initialVelocity: Vector2.zero(), kinematics: LightKinematics(10), targets: [Vector2(10, 0), Vector2(-10, 4), Vector2(-10, -4)], ); expect(distance, closeTo(6.33, 0.01)); }); }); group(':MaxAccelerationKinematics', () { test('properties', () { final agent = SimpleSteerable( kinematics: HeavyKinematics( maxSpeed: 20, maxAcceleration: 15, ), ); final behavior = Flee(owner: agent, targets: [Vector2(20, 10)]); expect(behavior.own, agent); expect(behavior.targets.length, 1); expect(behavior.targets.first, closeToVector(20, 10)); }); test('flee 1', () { const x0 = 5.0; const vMax = 10.0; const aMax = 5.0; const t0 = 10.0; final distance = fleeDistance( initialPosition: Vector2(x0, 0), initialVelocity: Vector2.zero(), kinematics: HeavyKinematics( maxSpeed: vMax, maxAcceleration: aMax, ), duration: t0, ); const t1 = vMax / aMax; // time to gain full speed // expected coordinate after t0 time const x1 = x0 + (t0 - t1) * vMax + 1 / 2 * aMax * t1 * t1; expect(distance, closeTo(x1, 0.1)); }); test('flee 2', () { final distance = fleeDistance( initialPosition: Vector2(12, -10), initialVelocity: Vector2(3, 5), kinematics: HeavyKinematics( maxSpeed: 10, maxAcceleration: 5, ), ); expect(distance, closeTo(1006.42, 0.01)); }); test('flee 3', () { final distance = fleeDistance( initialPosition: Vector2(0, 0.01), initialVelocity: Vector2.zero(), kinematics: HeavyKinematics( maxSpeed: 10, maxAcceleration: 5, ), targets: [Vector2(10, 0), Vector2(-10, 3), Vector2(-10, -3)], ); expect(distance, closeTo(966.64, 0.01)); }); test('flee 4', () { final distance = fleeDistance( initialPosition: Vector2(0.02, 0.01), initialVelocity: Vector2.zero(), kinematics: HeavyKinematics( maxSpeed: 10, maxAcceleration: 5, ), targets: [ Vector2(10, 0), Vector2(-10, 0), Vector2(0, 10), Vector2(0, -10), Vector2(7, 7), Vector2(7, -7), Vector2(-7, 7), Vector2(-7, -7), ], ); expect(distance, closeTo(978.90, 0.01)); }); }); }); } /// Return the distance between the runner and his flee target(s) after the /// [duration] seconds. double fleeDistance({ required Vector2 initialPosition, required Vector2 initialVelocity, required Kinematics kinematics, List<Vector2>? targets, double duration = 100.0, double dt = 0.01, }) { final runner = SimpleSteerable( velocity: initialVelocity, position: initialPosition, kinematics: kinematics, ); runner.behavior = Flee( owner: runner, targets: targets ?? [Vector2.zero()], ); for (var time = 0.0; time <= duration; time += dt) { runner.update(dt); } if (targets == null) { return runner.position.length; } else { final sum = Vector2.zero(); for (final target in targets) { sum.x += runner.position.x - target.x; sum.y += runner.position.y - target.y; } return sum.length / targets.length; } }
radiance/test/steering/behaviors/flee_test.dart/0
{'file_path': 'radiance/test/steering/behaviors/flee_test.dart', 'repo_id': 'radiance', 'token_count': 3623}
import 'package:ravepay/ravepay.dart'; import '_bootstrap.dart'; Future<Response<Result>> card() async { final charge = Charge.card( amount: '2000', cardno: '4556052704172643', cvv: '899', email: 'jeremiahogbomo@gmail.com', expirymonth: '08', expiryyear: '21', firstname: 'Jeremiah', lastname: 'Ogbomo', meta: [Metadata.named(name: 'hello', value: 'world')], ); return await charge.charge(); } Future<Response<Result>> pin() async { final charge = Charge.pin( cardno: '5399838383838381', cvv: '470', expirymonth: '10', expiryyear: '22', amount: '12345', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', txRef: 'LM5GVOUW3TYF', pin: '1234', meta: [Metadata.named(name: 'hello', value: 'world')], ); return await charge.charge(); } Future<Response<Result>> account() async { final _banks = await Banks().fetch(); final banks = _banks.data; final accessBankCode = banks.first.code; final charge = Charge.account( amount: '2000', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', accountbank: accessBankCode, accountnumber: '0690000031', ); return await charge.charge(); } Future<Response<Result>> ussd() async { final _banks = await Banks().fetch(); final banks = _banks.data; final accessBankCode = banks.first.code; final charge = Charge.ussd( amount: '2000', email: 'jeremiahogbomo@gmail.com', firstname: 'Jeremiah', lastname: 'Ogbomo', accountbank: accessBankCode, accountnumber: '0690000031', phonenumber: '081245554343', ); return await charge.charge(); } void main() async { init(); await card(); // await pin(); // await account(); // await ussd(); }
ravepay.dart/example/charge.dart/0
{'file_path': 'ravepay.dart/example/charge.dart', 'repo_id': 'ravepay.dart', 'token_count': 703}
import 'package:ravepay/src/api/api.dart'; class Transfers extends Api {}
ravepay.dart/lib/src/api/transfers.dart/0
{'file_path': 'ravepay.dart/lib/src/api/transfers.dart', 'repo_id': 'ravepay.dart', 'token_count': 27}
abstract class ModelInterface { Map<String, dynamic> toJson(); @override String toString() => toJson().toString(); }
ravepay.dart/lib/src/models/main.dart/0
{'file_path': 'ravepay.dart/lib/src/models/main.dart', 'repo_id': 'ravepay.dart', 'token_count': 40}
import 'package:flutter/material.dart'; class AppTextStyles { static const String fontFamily = 'Rubik'; static const TextStyle h1 = TextStyle( fontFamily: fontFamily, fontSize: 45, ); static const TextStyle h2 = TextStyle( fontFamily: fontFamily, fontWeight: FontWeight.w300, fontSize: 35, ); static const TextStyle h3 = TextStyle( fontFamily: fontFamily, fontSize: 30, ); static const TextStyle h4 = TextStyle( fontFamily: fontFamily, fontSize: 25, fontWeight: FontWeight.w500, ); static const TextStyle h5 = TextStyle( fontFamily: fontFamily, fontSize: 20, fontWeight: FontWeight.w500, ); static const TextStyle body = TextStyle( fontFamily: fontFamily, fontSize: 16, ); static const TextStyle bodySm = TextStyle( fontFamily: fontFamily, fontSize: 14, ); static const TextStyle bodyLg = TextStyle( fontFamily: fontFamily, fontWeight: FontWeight.w400, fontSize: 18, ); static const TextStyle caption = TextStyle( fontFamily: fontFamily, fontSize: 10, ); }
recipes_ui_app/lib/core/styles/app_text_styles.dart/0
{'file_path': 'recipes_ui_app/lib/core/styles/app_text_styles.dart', 'repo_id': 'recipes_ui_app', 'token_count': 392}
import 'package:flutter/material.dart'; import 'package:recipes_ui/core/enums/screen_size.dart'; class RecipesLayout { final BuildContext context; RecipesLayout(this.context); static RecipesLayout of(BuildContext context) { return RecipesLayout(context); } int get gridCrossAxisCount { switch (ScreenSize.of(context)) { case ScreenSize.xs: case ScreenSize.sm: return 1; case ScreenSize.md: return 2; case ScreenSize.lg: case ScreenSize.xl: case ScreenSize.xxl: return 3; } } double get gridChildAspectRatio { switch (ScreenSize.of(context)) { case ScreenSize.xs: case ScreenSize.sm: return 1.5; case ScreenSize.md: return 2; case ScreenSize.lg: return 1.5; case ScreenSize.xl: return 1.5; case ScreenSize.xxl: return 1.5; } } double get recipeImageSize { double screenWidth = MediaQuery.of(context).size.width; return screenWidth * 0.45 / gridCrossAxisCount; } }
recipes_ui_app/lib/features/recipes/recipes_layout.dart/0
{'file_path': 'recipes_ui_app/lib/features/recipes/recipes_layout.dart', 'repo_id': 'recipes_ui_app', 'token_count': 443}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:recipes_ui/core/styles/app_themes.dart'; import 'package:recipes_ui/features/recipes/models/recipe.dart'; import 'package:recipes_ui/features/recipes/recipes_data.dart'; import 'package:recipes_ui/features/recipes/views/pages/recipes_page.dart'; void main() { runApp( const ProviderScope( child: MyApp(), ), ); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { bool _isInit = true; @override void didChangeDependencies() { if (_isInit) { for (Recipe menuItem in RecipesData.dessertMenu) { precacheImage(Image.asset(menuItem.image).image, context); } } _isInit = false; super.didChangeDependencies(); } @override Widget build(BuildContext context) { SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark); return MaterialApp( title: 'Recipes UI Demo', debugShowCheckedModeBanner: false, theme: AppThemes.main(), home: const RecipesPage(), ); } }
recipes_ui_app/lib/main.dart/0
{'file_path': 'recipes_ui_app/lib/main.dart', 'repo_id': 'recipes_ui_app', 'token_count': 476}
import 'package:flutter/material.dart'; class ResponsiveScaffold extends StatelessWidget { const ResponsiveScaffold({ this.scaffoldKey, this.drawer, this.endDrawer, this.title, this.body, this.trailing, this.floatingActionButton, this.menuIcon, this.endIcon, this.kTabletBreakpoint = 720.0, this.kDesktopBreakpoint = 1440.0, this.appBarElevation, }); final Widget drawer, endDrawer; final Widget title; final Widget body; final Widget trailing; final Widget floatingActionButton; final kTabletBreakpoint; final kDesktopBreakpoint; final _drawerWidth = 304.0; final IconData menuIcon, endIcon; final double appBarElevation; final Key scaffoldKey; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (_, constraints) { if (constraints.maxWidth >= kDesktopBreakpoint) { return Material( child: Stack( children: <Widget>[ Row( children: <Widget>[ if (drawer != null) ...[ SizedBox( width: _drawerWidth, child: Drawer( child: SafeArea( child: drawer, ), ), ), ], Expanded( child: Scaffold( key: scaffoldKey, appBar: AppBar( elevation: appBarElevation, automaticallyImplyLeading: false, title: title, actions: <Widget>[ if (trailing != null) ...[ trailing, ], ], ), body: Row( children: <Widget>[ Expanded( child: body ?? Container(), ), if (endDrawer != null) ...[ Container( width: _drawerWidth, child: Drawer( elevation: 3.0, child: SafeArea( child: endDrawer, ), ), ), ], ], ), ), ), ], ), if (floatingActionButton != null) ...[ Positioned( top: 100.0, left: _drawerWidth - 30, child: floatingActionButton, ) ], ], ), ); } if (constraints.maxWidth >= kTabletBreakpoint) { return Scaffold( key: scaffoldKey, drawer: drawer == null ? null : Drawer( child: SafeArea( child: drawer, ), ), appBar: AppBar( elevation: appBarElevation, automaticallyImplyLeading: false, title: title, leading: _MenuButton(iconData: menuIcon), actions: <Widget>[ if (trailing != null) ...[ trailing, ], ], ), body: SafeArea( right: false, bottom: false, child: Stack( children: <Widget>[ Row( children: <Widget>[ Expanded( child: body ?? Container(), ), if (endDrawer != null) ...[ Container( width: _drawerWidth, child: Drawer( elevation: 3.0, child: SafeArea( child: endDrawer, ), ), ), ], ], ), if (floatingActionButton != null) ...[ Positioned( top: 10.0, left: 10.0, child: floatingActionButton, ) ], ], ), ), ); } return Scaffold( key: scaffoldKey, drawer: drawer == null ? null : Drawer( child: SafeArea( child: drawer, ), ), endDrawer: endDrawer == null ? null : Drawer( child: SafeArea( child: endDrawer, ), ), appBar: AppBar( elevation: appBarElevation, automaticallyImplyLeading: false, leading: _MenuButton(iconData: menuIcon), title: title, actions: <Widget>[ if (trailing != null) ...[ trailing, ], if (endDrawer != null) ...[ _OptionsButton(iconData: endIcon), ] ], ), body: body, floatingActionButton: floatingActionButton, floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, ); }, ); } } class _OptionsButton extends StatelessWidget { const _OptionsButton({ Key key, @required this.iconData, }) : super(key: key); final IconData iconData; @override Widget build(BuildContext context) { return IconButton( icon: Icon(iconData ?? Icons.more_vert), onPressed: () { Scaffold.of(context).openEndDrawer(); }, ); } } class _MenuButton extends StatelessWidget { const _MenuButton({ Key key, @required this.iconData, }) : super(key: key); final IconData iconData; @override Widget build(BuildContext context) { return IconButton( icon: Icon(iconData ?? Icons.menu), onPressed: () { Scaffold.of(context).openDrawer(); }, ); } }
responsive_scaffold/lib/templates/layout/scaffold.dart/0
{'file_path': 'responsive_scaffold/lib/templates/layout/scaffold.dart', 'repo_id': 'responsive_scaffold', 'token_count': 4146}
export 'widgets/art_color_row.dart'; export 'widgets/art_dimension_item.dart'; export 'widgets/art_grid_item.dart'; export 'widgets/art_links_button.dart'; export 'widgets/art_maker_item.dart'; export 'widgets/art_material_row.dart'; export 'widgets/cached_image.dart'; export 'widgets/error_display_view.dart'; export 'widgets/image_dialog.dart'; export 'widgets/loading_spinner.dart';
rijksbook/lib/widgets.dart/0
{'file_path': 'rijksbook/lib/widgets.dart', 'repo_id': 'rijksbook', 'token_count': 147}
name: counter description: A new Flutter project. publish_to: "none" environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=1.17.0" dependencies: cupertino_icons: ^1.0.2 flutter: sdk: flutter flutter_riverpod: path: ../../packages/flutter_riverpod freezed_annotation: ^2.2.0 hooks_riverpod: path: ../../packages/hooks_riverpod json_annotation: ^4.8.0 riverpod: path: ../../packages/riverpod riverpod_annotation: path: ../../packages/riverpod_annotation dev_dependencies: build_runner: ^2.3.3 custom_lint: ^0.5.2 flutter_test: sdk: flutter freezed: ^2.3.2 json_serializable: ^6.6.1 riverpod_generator: path: ../../packages/riverpod_generator riverpod_lint: path: ../../packages/riverpod_lint dependency_overrides: flutter_riverpod: path: ../../packages/flutter_riverpod hooks_riverpod: path: ../../packages/hooks_riverpod riverpod: path: ../../packages/riverpod flutter: uses-material-design: true
riverpod/examples/counter/pubspec.yaml/0
{'file_path': 'riverpod/examples/counter/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 418}
import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'common.dart'; part 'tag.freezed.dart'; @freezed class TagTheme with _$TagTheme { const factory TagTheme({ required TextStyle style, required EdgeInsets padding, required Color backgroundColor, required BorderRadius borderRadius, }) = _TagTheme; } final tagThemeProvider = Provider<TagTheme>( (ref) { final theme = ref.watch(themeProvider); return TagTheme( padding: EdgeInsets.symmetric( horizontal: theme.textTheme.bodyLarge!.fontSize! * 0.5, vertical: theme.textTheme.bodyLarge!.fontSize! * 0.4, ), style: theme.textTheme.bodyMedium!.copyWith( color: const Color(0xff9cc3db), ), borderRadius: BorderRadius.circular(3), backgroundColor: const Color(0xFF3e4a52), ); }, dependencies: [themeProvider], ); class Tag extends HookConsumerWidget { const Tag({super.key, required this.tag}); final String tag; @override Widget build(BuildContext context, WidgetRef ref) { final tagTheme = ref.watch(tagThemeProvider); return Container( decoration: BoxDecoration( borderRadius: tagTheme.borderRadius, color: tagTheme.backgroundColor, ), padding: tagTheme.padding, child: Text(tag, style: tagTheme.style), ); } }
riverpod/examples/stackoverflow/lib/tag.dart/0
{'file_path': 'riverpod/examples/stackoverflow/lib/tag.dart', 'repo_id': 'riverpod', 'token_count': 534}
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:todos/main.dart'; const firstItemText = 'Buy cookies'; const secondItemText = 'Star Riverpod'; const thirdItemText = 'Have a walk'; void main() { final addTodoInput = find.byKey(addTodoKey); final activeFilterButton = find.byKey(activeFilterKey); final firstItem = find.byKey(const Key('todo-0')); final firstCheckbox = find.descendant( of: firstItem, matching: find.byType(Checkbox), ); final secondItem = find.byKey(const Key('todo-1')); final secondCheckbox = find.descendant( of: secondItem, matching: find.byType(Checkbox), ); final thirdItem = find.byKey(const Key('todo-2')); final thirdCheckbox = find.descendant( of: thirdItem, matching: find.byType(Checkbox), ); testWidgets( 'Render the default todos', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect( find.descendant(of: firstItem, matching: find.text(firstItemText)), findsOneWidget, ); expect( tester.widget(firstCheckbox), isA<Checkbox>().having((s) => s.value, 'value', false), ); expect( find.descendant(of: secondItem, matching: find.text(secondItemText)), findsOneWidget, ); expect( tester.widget(secondCheckbox), isA<Checkbox>().having((s) => s.value, 'value', false), ); expect( find.descendant(of: thirdItem, matching: find.text(thirdItemText)), findsOneWidget, ); expect( tester.widget(thirdCheckbox), isA<Checkbox>().having((s) => s.value, 'value', false), ); await expectLater( find.byType(MyApp), matchesGoldenFile('initial_state.png'), ); }, skip: !Platform.isMacOS, ); testWidgets('Clicking on checkbox toggles the todo', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect( tester.widget(firstCheckbox), isA<Checkbox>().having((s) => s.value, 'value', false), ); expect(find.text('3 items left'), findsOneWidget); expect(find.text('2 items left'), findsNothing); await tester.tap(firstCheckbox); await tester.pump(); expect( tester.widget(firstCheckbox), isA<Checkbox>().having((s) => s.value, 'value', true), ); expect(find.text('2 items left'), findsOneWidget); expect(find.text('3 items left'), findsNothing); }); testWidgets('Editing the todo on unfocus', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect( find.descendant(of: firstItem, matching: find.text(firstItemText)), findsOneWidget, ); await tester.tap(firstItem); // wait for the textfield to appear await tester.pump(); // don't use tester.enterText to check that the textfield is auto-focused tester.testTextInput.enterText('new description'); tester.testTextInput.closeConnection(); await tester.pump(); expect( find.descendant(of: firstItem, matching: find.text(firstItemText)), findsNothing, ); expect( find.descendant(of: firstItem, matching: find.text('new description')), findsOneWidget, ); }); testWidgets('Editing the todo on done', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect( find.descendant(of: firstItem, matching: find.text(firstItemText)), findsOneWidget, ); await tester.tap(firstItem); // wait for the textfield to appear await tester.pump(); // don't use tester.enterText to check that the textfield is auto-focused tester.testTextInput.enterText('new description'); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); expect( find.descendant(of: firstItem, matching: find.text(firstItemText)), findsNothing, ); expect( find.descendant(of: firstItem, matching: find.text('new description')), findsOneWidget, ); }); testWidgets('Dismissing the todo', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect(firstItem, findsOneWidget); // dismiss the item await tester.drag(firstItem, const Offset(1000, 0)); // wait for animation to finish await tester.pumpAndSettle(); expect(firstItem, findsNothing); }); testWidgets('Clicking on Active shows only incomplete todos', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect(firstItem, findsOneWidget); expect(secondItem, findsOneWidget); expect(thirdItem, findsOneWidget); await tester.tap(firstCheckbox); await tester.tap(activeFilterButton); await tester.pump(); expect(firstItem, findsNothing); expect(secondItem, findsOneWidget); expect(thirdItem, findsOneWidget); }); testWidgets( 'The input allows adding todos', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyApp())); expect(find.text('Newly added todo'), findsNothing); expect(find.text('3 items left'), findsOneWidget); expect(find.text('4 items left'), findsNothing); await tester.enterText(addTodoInput, 'Newly added todo'); expect( find.descendant( of: addTodoInput, matching: find.text('Newly added todo'), ), findsOneWidget, ); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); // clears the input expect( find.descendant( of: addTodoInput, matching: find.text('Newly added todo'), ), findsNothing, ); await expectLater( find.byType(MyApp), matchesGoldenFile('new_todo.png'), ); expect(find.text('Newly added todo'), findsOneWidget); expect(find.text('4 items left'), findsOneWidget); expect(find.text('3 items left'), findsNothing); }, skip: !Platform.isMacOS, ); }
riverpod/examples/todos/test/widget_test.dart/0
{'file_path': 'riverpod/examples/todos/test/widget_test.dart', 'repo_id': 'riverpod', 'token_count': 2499}
// ignore_for_file: invalid_use_of_internal_member part of '../change_notifier_provider.dart'; /// {@macro riverpod.provider_ref_base} abstract class AutoDisposeChangeNotifierProviderRef< NotifierT extends ChangeNotifier?> extends ChangeNotifierProviderRef<NotifierT> implements AutoDisposeRef<NotifierT> {} // ignore: subtype_of_sealed_class /// {@macro riverpod.change_notifier_provider} class AutoDisposeChangeNotifierProvider<NotifierT extends ChangeNotifier?> extends _ChangeNotifierProviderBase<NotifierT> { /// {@macro riverpod.change_notifier_provider} AutoDisposeChangeNotifierProvider( this._createFn, { super.name, super.dependencies, @Deprecated('Will be removed in 3.0.0') super.from, @Deprecated('Will be removed in 3.0.0') super.argument, @Deprecated('Will be removed in 3.0.0') super.debugGetCreateSourceHash, }) : super( allTransitiveDependencies: computeAllTransitiveDependencies(dependencies), ); /// An implementation detail of Riverpod @internal AutoDisposeChangeNotifierProvider.internal( this._createFn, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, super.from, super.argument, }); /// {@macro riverpod.family} static const family = AutoDisposeChangeNotifierProviderFamily.new; final NotifierT Function(AutoDisposeChangeNotifierProviderRef<NotifierT> ref) _createFn; @override NotifierT _create(AutoDisposeChangeNotifierProviderElement<NotifierT> ref) { return _createFn(ref); } @override AutoDisposeChangeNotifierProviderElement<NotifierT> createElement() { return AutoDisposeChangeNotifierProviderElement<NotifierT>._(this); } @override late final Refreshable<NotifierT> notifier = _notifier<NotifierT>(this); /// {@macro riverpod.override_with} Override overrideWith( Create<NotifierT, AutoDisposeChangeNotifierProviderRef<NotifierT>> create, ) { return ProviderOverride( origin: this, override: AutoDisposeChangeNotifierProvider<NotifierT>.internal( create, from: from, argument: argument, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ), ); } } /// The element of [AutoDisposeChangeNotifierProvider]. class AutoDisposeChangeNotifierProviderElement< NotifierT extends ChangeNotifier?> extends ChangeNotifierProviderElement<NotifierT> with AutoDisposeProviderElementMixin<NotifierT> implements AutoDisposeChangeNotifierProviderRef<NotifierT> { /// The [ProviderElementBase] for [ChangeNotifier] AutoDisposeChangeNotifierProviderElement._( AutoDisposeChangeNotifierProvider<NotifierT> super._provider, ) : super._(); } // ignore: subtype_of_sealed_class /// The [Family] of [AutoDisposeChangeNotifierProvider]. class AutoDisposeChangeNotifierProviderFamily<NotifierT extends ChangeNotifier?, Arg> extends AutoDisposeFamilyBase< AutoDisposeChangeNotifierProviderRef<NotifierT>, NotifierT, Arg, NotifierT, AutoDisposeChangeNotifierProvider<NotifierT>> { /// The [Family] of [AutoDisposeChangeNotifierProvider]. AutoDisposeChangeNotifierProviderFamily( super._createFn, { super.name, super.dependencies, }) : super( providerFactory: AutoDisposeChangeNotifierProvider.internal, debugGetCreateSourceHash: null, allTransitiveDependencies: computeAllTransitiveDependencies(dependencies), ); /// {@macro riverpod.override_with} Override overrideWith( NotifierT Function( AutoDisposeChangeNotifierProviderRef<NotifierT> ref, Arg arg, ) create, ) { return FamilyOverrideImpl<NotifierT, Arg, AutoDisposeChangeNotifierProvider<NotifierT>>( this, (arg) => AutoDisposeChangeNotifierProvider<NotifierT>.internal( (ref) => create(ref, arg), from: from, argument: arg, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ), ); } }
riverpod/packages/flutter_riverpod/lib/src/change_notifier_provider/auto_dispose.dart/0
{'file_path': 'riverpod/packages/flutter_riverpod/lib/src/change_notifier_provider/auto_dispose.dart', 'repo_id': 'riverpod', 'token_count': 1553}
// ignore_for_file: invalid_use_of_internal_member import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/src/internals.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../utils.dart'; void main() { group('ChangeNotifierProvider.autoDispose.family', () { test('specifies `from` and `argument` for related providers', () { final provider = ChangeNotifierProvider.autoDispose.family<ValueNotifier<int>, int>( (ref, _) => ValueNotifier(42), ); expect(provider(0).from, provider); expect(provider(0).argument, 0); }); test('support null ChangeNotifier', () { final container = createContainer(); final provider = ChangeNotifierProvider.family.autoDispose<ValueNotifier<int>?, int>( (ref, _) => null, ); expect(container.read(provider(0)), null); expect(container.read(provider(0).notifier), null); container.dispose(); }); group('scoping an override overrides all the associated subproviders', () { test('when passing the provider itself', () async { final provider = ChangeNotifierProvider.autoDispose .family<ValueNotifier<int>, int>((ref, _) => ValueNotifier(0)); final root = createContainer(); final container = createContainer(parent: root, overrides: [provider]); expect(container.read(provider(0).notifier).value, 0); expect(container.read(provider(0)).value, 0); expect( container.getAllProviderElementsInOrder(), unorderedEquals(<Object?>[ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]), ); expect(root.getAllProviderElementsInOrder(), isEmpty); }); test('ChangeNotifier can be auto-scoped', () async { final dep = Provider((ref) => 0); final provider = ChangeNotifierProvider.autoDispose.family<ValueNotifier<int>, int>( (ref, i) => ValueNotifier(ref.watch(dep) + i), dependencies: [dep], ); final root = createContainer(); final container = createContainer( parent: root, overrides: [dep.overrideWithValue(42)], ); expect(container.read(provider(10)).value, 52); expect(container.read(provider(10).notifier).value, 52); expect(root.getAllProviderElements(), isEmpty); }); test('when using provider.overrideWithProvider', () async { final provider = ChangeNotifierProvider.autoDispose .family<ValueNotifier<int>, int>((ref, _) => ValueNotifier(0)); final root = createContainer(); final container = createContainer( parent: root, overrides: [ provider.overrideWithProvider( (value) => ChangeNotifierProvider.autoDispose( (ref) => ValueNotifier(42), ), ), ], ); expect(container.read(provider(0).notifier).value, 42); expect(container.read(provider(0)).value, 42); expect(root.getAllProviderElementsInOrder(), isEmpty); expect( container.getAllProviderElementsInOrder(), unorderedEquals(<Object?>[ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]), ); }); }); }); }
riverpod/packages/flutter_riverpod/test/providers/change_notifier/family_auto_dispose_change_notifier_provider_test.dart/0
{'file_path': 'riverpod/packages/flutter_riverpod/test/providers/change_notifier/family_auto_dispose_change_notifier_provider_test.dart', 'repo_id': 'riverpod', 'token_count': 1460}
export 'package:flutter_riverpod/src/internals.dart';
riverpod/packages/hooks_riverpod/lib/src/internals.dart/0
{'file_path': 'riverpod/packages/hooks_riverpod/lib/src/internals.dart', 'repo_id': 'riverpod', 'token_count': 19}
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint part of 'models.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$ConfigurationImpl _$$ConfigurationImplFromJson(Map<String, dynamic> json) => _$ConfigurationImpl( publicKey: json['public_key'] as String, privateKey: json['private_key'] as String, ); Map<String, dynamic> _$$ConfigurationImplToJson(_$ConfigurationImpl instance) => <String, dynamic>{ 'public_key': instance.publicKey, 'private_key': instance.privateKey, }; _$MarvelResponseImpl _$$MarvelResponseImplFromJson(Map<String, dynamic> json) => _$MarvelResponseImpl( MarvelData.fromJson(json['data'] as Map<String, dynamic>), ); Map<String, dynamic> _$$MarvelResponseImplToJson( _$MarvelResponseImpl instance) => <String, dynamic>{ 'data': instance.data, }; _$MarvelDataImpl _$$MarvelDataImplFromJson(Map<String, dynamic> json) => _$MarvelDataImpl( (json['results'] as List<dynamic>) .map((e) => e as Map<String, dynamic>) .toList(), ); Map<String, dynamic> _$$MarvelDataImplToJson(_$MarvelDataImpl instance) => <String, dynamic>{ 'results': instance.results, }; _$ComicImpl _$$ComicImplFromJson(Map<String, dynamic> json) => _$ComicImpl( id: json['id'] as int, title: json['title'] as String, ); Map<String, dynamic> _$$ComicImplToJson(_$ComicImpl instance) => <String, dynamic>{ 'id': instance.id, 'title': instance.title, };
riverpod/packages/riverpod/example/lib/models.g.dart/0
{'file_path': 'riverpod/packages/riverpod/example/lib/models.g.dart', 'repo_id': 'riverpod', 'token_count': 605}
part of '../notifier.dart'; /// An [AutoDisposeNotifier] base class shared between family and non-family notifiers. /// /// Not meant for public consumption outside of riverpod_generator @internal abstract class BuildlessAutoDisposeNotifier<State> extends NotifierBase<State> { @override late final AutoDisposeNotifierProviderElement<NotifierBase<State>, State> _element; @override void _setElement(ProviderElementBase<State> element) { _element = element as AutoDisposeNotifierProviderElement<NotifierBase<State>, State>; } @override AutoDisposeNotifierProviderRef<State> get ref => _element; } /// {@macro riverpod.notifier} /// /// {@macro riverpod.notifier_provider_modifier} abstract class AutoDisposeNotifier<State> extends BuildlessAutoDisposeNotifier<State> { /// {@macro riverpod.async_notifier.build} @visibleForOverriding State build(); } /// {@macro riverpod.provider_ref_base} abstract class AutoDisposeNotifierProviderRef<T> implements NotifierProviderRef<T>, AutoDisposeRef<T> {} /// {@macro riverpod.notifier_provider} /// /// {@macro riverpod.notifier_provider_modifier} typedef AutoDisposeNotifierProvider<NotifierT extends AutoDisposeNotifier<T>, T> = AutoDisposeNotifierProviderImpl<NotifierT, T>; /// The implementation of [AutoDisposeNotifierProvider] but with loosened type constraints /// that can be shared with [NotifierProvider]. /// /// This enables tests to execute on both [AutoDisposeNotifierProvider] and /// [NotifierProvider] at the same time. @internal class AutoDisposeNotifierProviderImpl<NotifierT extends NotifierBase<T>, T> extends NotifierProviderBase<NotifierT, T> { /// {@macro riverpod.notifier_provider} /// /// {@macro riverpod.notifier_provider_modifier} AutoDisposeNotifierProviderImpl( super._createNotifier, { super.name, super.dependencies, @Deprecated('Will be removed in 3.0.0') super.from, @Deprecated('Will be removed in 3.0.0') super.argument, @Deprecated('Will be removed in 3.0.0') super.debugGetCreateSourceHash, }) : super( allTransitiveDependencies: computeAllTransitiveDependencies(dependencies), ); /// An implementation detail of Riverpod @internal AutoDisposeNotifierProviderImpl.internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, super.from, super.argument, }); /// {@macro riverpod.family} static const family = AutoDisposeNotifierProviderFamily.new; @override late final Refreshable<NotifierT> notifier = _notifier<NotifierT, T>(this); @override AutoDisposeNotifierProviderElement<NotifierT, T> createElement() { return AutoDisposeNotifierProviderElement(this); } @override @mustBeOverridden T runNotifierBuild(NotifierBase<T> notifier) { return (notifier as AutoDisposeNotifier<T>).build(); } /// {@macro riverpod.override_with} @mustBeOverridden Override overrideWith(NotifierT Function() create) { return ProviderOverride( origin: this, override: AutoDisposeNotifierProviderImpl<NotifierT, T>.internal( create, from: from, argument: argument, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, name: null, ), ); } } /// The element of [AutoDisposeNotifierProvider] class AutoDisposeNotifierProviderElement<NotifierT extends NotifierBase<T>, T> extends NotifierProviderElement<NotifierT, T> with AutoDisposeProviderElementMixin<T> implements AutoDisposeNotifierProviderRef<T> { /// The [ProviderElementBase] for [NotifierProvider] @internal AutoDisposeNotifierProviderElement(super._provider); }
riverpod/packages/riverpod/lib/src/notifier/auto_dispose.dart/0
{'file_path': 'riverpod/packages/riverpod/lib/src/notifier/auto_dispose.dart', 'repo_id': 'riverpod', 'token_count': 1289}
part of '../state_provider.dart'; /// {@macro riverpod.provider_ref_base} /// - [controller], the [StateController] currently exposed by this provider. abstract class AutoDisposeStateProviderRef<State> extends StateProviderRef<State> implements AutoDisposeRef<State> {} /// {@macro riverpod.stateprovider} class AutoDisposeStateProvider<T> extends _StateProviderBase<T> { /// {@macro riverpod.stateprovider} AutoDisposeStateProvider( this._createFn, { super.name, super.dependencies, @Deprecated('Will be removed in 3.0.0') super.from, @Deprecated('Will be removed in 3.0.0') super.argument, @Deprecated('Will be removed in 3.0.0') super.debugGetCreateSourceHash, }) : super( allTransitiveDependencies: computeAllTransitiveDependencies(dependencies), ); /// An implementation detail of Riverpod @internal AutoDisposeStateProvider.internal( this._createFn, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, super.from, super.argument, }); /// {@macro riverpod.family} static const family = AutoDisposeStateProviderFamily.new; final T Function(AutoDisposeStateProviderRef<T> ref) _createFn; @override T _create(AutoDisposeStateProviderElement<T> ref) => _createFn(ref); @override AutoDisposeStateProviderElement<T> createElement() { return AutoDisposeStateProviderElement._(this); } @override late final Refreshable<StateController<T>> notifier = _notifier(this); @Deprecated( 'Will be removed in 3.0.0. ' 'Use either `ref.watch(provider)` or `ref.read(provider.notifier)` instead', ) @override late final Refreshable<StateController<T>> state = _state(this); /// {@macro riverpod.override_with} Override overrideWith( Create<T, AutoDisposeStateProviderRef<T>> create, ) { return ProviderOverride( origin: this, override: AutoDisposeStateProvider<T>.internal( create, from: from, argument: argument, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, name: null, ), ); } } /// The element of [StateProvider]. class AutoDisposeStateProviderElement<T> extends StateProviderElement<T> with AutoDisposeProviderElementMixin<T> implements AutoDisposeStateProviderRef<T> { /// The [ProviderElementBase] for [StateProvider] AutoDisposeStateProviderElement._(AutoDisposeStateProvider<T> super._provider) : super._(); } /// The [Family] of [StateProvider]. class AutoDisposeStateProviderFamily<R, Arg> extends AutoDisposeFamilyBase< AutoDisposeStateProviderRef<R>, R, Arg, R, AutoDisposeStateProvider<R>> { /// The [Family] of [StateProvider]. AutoDisposeStateProviderFamily( super._createFn, { super.name, super.dependencies, }) : super( providerFactory: AutoDisposeStateProvider.internal, debugGetCreateSourceHash: null, allTransitiveDependencies: computeAllTransitiveDependencies(dependencies), ); /// {@macro riverpod.override_with} Override overrideWith( R Function(AutoDisposeStateProviderRef<R> ref, Arg arg) create, ) { return FamilyOverrideImpl<R, Arg, AutoDisposeStateProvider<R>>( this, (arg) => AutoDisposeStateProvider<R>.internal( (ref) => create(ref, arg), from: from, argument: arg, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, name: null, ), ); } }
riverpod/packages/riverpod/lib/src/state_provider/auto_dispose.dart/0
{'file_path': 'riverpod/packages/riverpod/lib/src/state_provider/auto_dispose.dart', 'repo_id': 'riverpod', 'token_count': 1328}
// ignore_for_file: prefer_const_constructors import 'package:riverpod/riverpod.dart'; import 'package:riverpod/src/builders.dart'; import 'package:test/test.dart'; void main() { test('builders', () { expect(Provider.autoDispose.family, Provider.family.autoDispose); expect( StateNotifierProvider.autoDispose.family, StateNotifierProvider.family.autoDispose, ); expect( StreamProvider.autoDispose.family, StreamProvider.family.autoDispose, ); }); test('FutureProvider', () { final futureProviderBuilder = FutureProviderBuilder(); FutureProviderFamilyBuilder(); AutoDisposeFutureProviderBuilder(); AutoDisposeFutureProviderFamilyBuilder(); expect( FutureProvider.family, const FutureProviderFamilyBuilder(), ); expect( FutureProvider.autoDispose, const AutoDisposeFutureProviderBuilder(), ); expect( FutureProvider.autoDispose.family, FutureProvider.family.autoDispose, ); expect( futureProviderBuilder.autoDispose, FutureProvider.autoDispose, ); expect( futureProviderBuilder.family, FutureProvider.family, ); expect( futureProviderBuilder((ref) async => 42, name: 'foo'), isA<FutureProvider<int>>().having((s) => s.name, 'name', 'foo'), ); }); test('StreamProvider', () { final streamProviderBuilder = StreamProviderBuilder(); StreamProviderFamilyBuilder(); AutoDisposeStreamProviderBuilder(); AutoDisposeStreamProviderFamilyBuilder(); expect( StreamProvider.family, const StreamProviderFamilyBuilder(), ); expect( StreamProvider.autoDispose, const AutoDisposeStreamProviderBuilder(), ); expect( StreamProvider.autoDispose.family, StreamProvider.family.autoDispose, ); expect( streamProviderBuilder.autoDispose, StreamProvider.autoDispose, ); expect( streamProviderBuilder.family, StreamProvider.family, ); expect( streamProviderBuilder((ref) => Stream.value(42), name: 'foo'), isA<StreamProvider<int>>().having((s) => s.name, 'name', 'foo'), ); }); test('StateNotifierProvider', () { final stateNotifierProviderBuilder = StateNotifierProviderBuilder(); StateNotifierProviderFamilyBuilder(); AutoDisposeStateNotifierProviderBuilder(); AutoDisposeStateNotifierProviderFamilyBuilder(); expect( StateNotifierProvider.family, const StateNotifierProviderFamilyBuilder(), ); expect( StateNotifierProvider.autoDispose, const AutoDisposeStateNotifierProviderBuilder(), ); expect( StateNotifierProvider.autoDispose.family, StateNotifierProvider.family.autoDispose, ); expect( stateNotifierProviderBuilder.autoDispose, StateNotifierProvider.autoDispose, ); expect( stateNotifierProviderBuilder.family, StateNotifierProvider.family, ); expect( stateNotifierProviderBuilder<StateController<int>, int>( (ref) => StateController(42), name: 'foo', ), isA<StateNotifierProvider<StateController<int>, int>>() .having((s) => s.name, 'name', 'foo'), ); }); test('Provider', () { final providerBuilder = ProviderBuilder(); ProviderFamilyBuilder(); AutoDisposeProviderBuilder(); AutoDisposeProviderFamilyBuilder(); expect( Provider.family, const ProviderFamilyBuilder(), ); expect( Provider.autoDispose, const AutoDisposeProviderBuilder(), ); expect( Provider.autoDispose.family, Provider.family.autoDispose, ); expect( providerBuilder.autoDispose, Provider.autoDispose, ); expect( providerBuilder.family, Provider.family, ); expect( providerBuilder((ref) => StateController(42), name: 'foo'), isA<Provider<StateController<int>>>() .having((s) => s.name, 'name', 'foo'), ); }); test('StateProvider', () { final stateProviderBuilder = StateProviderBuilder(); StateProviderFamilyBuilder(); expect( StateProvider.family, const StateProviderFamilyBuilder(), ); expect( stateProviderBuilder.family, StateProvider.family, ); expect( stateProviderBuilder((ref) => StateController(42), name: 'foo'), isA<StateProvider<StateController<int>>>() .having((s) => s.name, 'name', 'foo'), ); }); }
riverpod/packages/riverpod/test/framework/modifiers_test.dart/0
{'file_path': 'riverpod/packages/riverpod/test/framework/modifiers_test.dart', 'repo_id': 'riverpod', 'token_count': 1664}
import 'dart:async'; import 'package:riverpod/src/internals.dart'; typedef AsyncNotifierProviderFactoryType = AsyncNotifierProviderBase<NotifierT, T> Function<NotifierT extends AsyncNotifierBase<T>, T>( NotifierT Function() create, { Object? argument, Iterable<ProviderOrFamily>? dependencies, Family<Object?>? from, String? name, }); typedef AsyncNotifierFactoryType = AsyncTestNotifierBase<T> Function<T>( FutureOr<T> Function(AsyncNotifierProviderRef<T>), { bool Function(AsyncValue<T>, AsyncValue<T>)? updateShouldNotify, }); typedef SimpleTestProviderFactoryType = AsyncNotifierProviderBase<AsyncTestNotifierBase<T>, T> Function<T>( FutureOr<T> Function(AsyncNotifierProviderRef<T> ref) init, { bool Function(AsyncValue<T> prev, AsyncValue<T> next)? updateShouldNotify, }); typedef TestProviderFactoryType = AsyncNotifierProviderBase<AsyncTestNotifierBase<T>, T> Function<T>( AsyncTestNotifierBase<T> Function() createNotifier, ); List<AsyncNotifierFactory> matrix({ bool alwaysAlive = true, bool autoDispose = true, }) { return <AsyncNotifierFactory>[ if (alwaysAlive) AsyncNotifierFactory( label: 'AsyncNotifierProvider', isAutoDispose: false, provider: AsyncNotifierProviderImpl.new, notifier: AsyncTestNotifier.new, testProvider: <T>(createNotifier) { return AsyncNotifierProviderImpl<AsyncTestNotifierBase<T>, T>( createNotifier, ); }, simpleTestProvider: <T>(init, {updateShouldNotify}) { return AsyncNotifierProvider<AsyncTestNotifier<T>, T>( () => AsyncTestNotifier( init, updateShouldNotify: updateShouldNotify, ), ); }, ), if (alwaysAlive) AsyncNotifierFactory( label: 'AsyncNotifierProviderFamily', isAutoDispose: false, provider: <NotifierT extends AsyncNotifierBase<T>, T>( create, { argument, dependencies, from, name, }) { return FamilyAsyncNotifierProviderImpl<NotifierT, T, int>.internal( create, argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, notifier: AsyncTestNotifierFamily.new, testProvider: <T>(createNotifier) { return FamilyAsyncNotifierProviderImpl<AsyncTestNotifierFamily<T>, T, int>.internal( () => createNotifier() as AsyncTestNotifierFamily<T>, argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, simpleTestProvider: <T>(init, {updateShouldNotify}) { return FamilyAsyncNotifierProviderImpl<AsyncTestNotifierFamily<T>, T, int>.internal( () => AsyncTestNotifierFamily<T>( init, updateShouldNotify: updateShouldNotify, ), argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, ), if (autoDispose) AsyncNotifierFactory( label: 'AutoDisposeAsyncNotifierProvider', isAutoDispose: true, provider: AutoDisposeAsyncNotifierProviderImpl.new, notifier: AutoDisposeAsyncTestNotifier.new, testProvider: <T>(createNotifier) { return AutoDisposeAsyncNotifierProviderImpl< AutoDisposeAsyncTestNotifier<T>, T>( () => createNotifier() as AutoDisposeAsyncTestNotifier<T>, ); }, simpleTestProvider: <T>(init, {updateShouldNotify}) { return AutoDisposeAsyncNotifierProvider< AutoDisposeAsyncTestNotifier<T>, T>( () => AutoDisposeAsyncTestNotifier( init, updateShouldNotify: updateShouldNotify, ), ); }, ), if (autoDispose) AsyncNotifierFactory( label: 'AutoDisposeAsyncNotifierProviderFamily', isAutoDispose: true, provider: <NotifierT extends AsyncNotifierBase<T>, T>( create, { argument, dependencies, from, name, }) { return AutoDisposeFamilyAsyncNotifierProviderImpl<NotifierT, T, int>.internal( create, argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, notifier: AutoDisposeAsyncTestNotifierFamily.new, testProvider: <T>(createNotifier) { return AutoDisposeFamilyAsyncNotifierProviderImpl< AutoDisposeAsyncTestNotifierFamily<T>, T, int>.internal( () => createNotifier() as AutoDisposeAsyncTestNotifierFamily<T>, argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, simpleTestProvider: <T>(init, {updateShouldNotify}) { return AutoDisposeFamilyAsyncNotifierProviderImpl< AutoDisposeAsyncTestNotifierFamily<T>, T, int>.internal( () => AutoDisposeAsyncTestNotifierFamily<T>( init, updateShouldNotify: updateShouldNotify, ), argument: 0, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, ); }, ), ]; } class AsyncNotifierFactory { const AsyncNotifierFactory({ required this.label, required this.provider, required this.notifier, required this.isAutoDispose, required this.testProvider, required this.simpleTestProvider, }); final String label; final bool isAutoDispose; final AsyncNotifierProviderFactoryType provider; final AsyncNotifierFactoryType notifier; final TestProviderFactoryType testProvider; final SimpleTestProviderFactoryType simpleTestProvider; } abstract class AsyncTestNotifierBase<T> extends AsyncNotifierBase<T> { // overriding to remove the @protected @override Future<T> update( FutureOr<T> Function(T p1) cb, { FutureOr<T> Function(Object err, StackTrace stackTrace)? onError, }) { return super.update(cb); } } class AsyncTestNotifier<T> extends AsyncNotifier<T> implements AsyncTestNotifierBase<T> { AsyncTestNotifier( this._init, { bool Function(AsyncValue<T> prev, AsyncValue<T> next)? updateShouldNotify, }) : _updateShouldNotify = updateShouldNotify; final FutureOr<T> Function(AsyncNotifierProviderRef<T> ref) _init; final bool Function(AsyncValue<T> prev, AsyncValue<T> next)? _updateShouldNotify; @override FutureOr<T> build() => _init(ref); @override bool updateShouldNotify(AsyncValue<T> prev, AsyncValue<T> next) { return _updateShouldNotify?.call(prev, next) ?? super.updateShouldNotify(prev, next); } @override String toString() { return 'AsyncTestNotifier<$T>#$hashCode'; } } class AsyncTestNotifierFamily<T> extends FamilyAsyncNotifier<T, int> implements AsyncTestNotifierBase<T> { AsyncTestNotifierFamily( this._init, { bool Function(AsyncValue<T> prev, AsyncValue<T> next)? updateShouldNotify, }) : _updateShouldNotify = updateShouldNotify; final FutureOr<T> Function(AsyncNotifierProviderRef<T> ref) _init; final bool Function(AsyncValue<T> prev, AsyncValue<T> next)? _updateShouldNotify; @override FutureOr<T> build(int arg) => _init(ref); @override bool updateShouldNotify(AsyncValue<T> prev, AsyncValue<T> next) { return _updateShouldNotify?.call(prev, next) ?? super.updateShouldNotify(prev, next); } @override String toString() { return 'AsyncTestNotifierFamily<$T>#$hashCode'; } } class AutoDisposeAsyncTestNotifier<T> extends AutoDisposeAsyncNotifier<T> implements AsyncTestNotifierBase<T> { AutoDisposeAsyncTestNotifier( this._init2, { bool Function(AsyncValue<T> prev, AsyncValue<T> next)? updateShouldNotify, }) : _updateShouldNotify = updateShouldNotify; final FutureOr<T> Function(AutoDisposeAsyncNotifierProviderRef<T> ref) _init2; final bool Function(AsyncValue<T> prev, AsyncValue<T> next)? _updateShouldNotify; @override FutureOr<T> build() => _init2(ref); @override bool updateShouldNotify(AsyncValue<T> prev, AsyncValue<T> next) { return _updateShouldNotify?.call(prev, next) ?? super.updateShouldNotify(prev, next); } @override String toString() { return 'AutoDisposeAsyncTestNotifier<$T>#$hashCode'; } } class AutoDisposeAsyncTestNotifierFamily<T> extends AutoDisposeFamilyAsyncNotifier<T, int> implements AsyncTestNotifierBase<T> { AutoDisposeAsyncTestNotifierFamily( this._init2, { bool Function(AsyncValue<T> prev, AsyncValue<T> next)? updateShouldNotify, }) : _updateShouldNotify = updateShouldNotify; final FutureOr<T> Function(AutoDisposeAsyncNotifierProviderRef<T> ref) _init2; final bool Function(AsyncValue<T> prev, AsyncValue<T> next)? _updateShouldNotify; @override FutureOr<T> build(int arg) => _init2(ref); @override bool updateShouldNotify(AsyncValue<T> prev, AsyncValue<T> next) { return _updateShouldNotify?.call(prev, next) ?? super.updateShouldNotify(prev, next); } @override String toString() { return 'AutoDisposeAsyncTestNotifierFamily<$T, int>#$hashCode'; } }
riverpod/packages/riverpod/test/providers/async_notifier/factory.dart/0
{'file_path': 'riverpod/packages/riverpod/test/providers/async_notifier/factory.dart', 'repo_id': 'riverpod', 'token_count': 4098}
import 'package:riverpod/riverpod.dart'; import 'package:test/test.dart'; void main() { group('StateController', () { test('update allows changing the state from the previous state', () { final controller = StateController(0); addTearDown(controller.dispose); expect(controller.state, 0); final result = controller.update((state) => state + 1); expect(result, 1); expect(controller.state, 1); }); }); }
riverpod/packages/riverpod/test/providers/state_provider/state_controller_test.dart/0
{'file_path': 'riverpod/packages/riverpod/test/providers/state_provider/state_controller_test.dart', 'repo_id': 'riverpod', 'token_count': 159}
include: ../../analysis_options.yaml linter: rules: # TODO enable later public_member_api_docs: false
riverpod/packages/riverpod_analyzer_utils/analysis_options.yaml/0
{'file_path': 'riverpod/packages/riverpod_analyzer_utils/analysis_options.yaml', 'repo_id': 'riverpod', 'token_count': 41}
part of '../riverpod_ast.dart'; abstract class RiverpodAstVisitor { void visitProviderOverrideList( ProviderOverrideList overrideList, ); void visitProviderOverrideExpression( ProviderOverrideExpression expression, ); void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result); void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression container, ); void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ); void visitRiverpodAnnotation( RiverpodAnnotation annotation, ); void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ); void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ); void visitLegacyProviderDeclaration( LegacyProviderDeclaration declaration, ); void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ); void visitLegacyProviderDependency( LegacyProviderDependency dependency, ); void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ); void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ); void visitProviderListenableExpression( ProviderListenableExpression expression, ); void visitRefWatchInvocation(RefWatchInvocation invocation); void visitRefListenInvocation(RefListenInvocation invocation); void visitRefReadInvocation(RefReadInvocation invocation); void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation); void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation); void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation); void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ); void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration); void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ); void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ); void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ); void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration); } class RecursiveRiverpodAstVisitor extends RiverpodAstVisitor { @override void visitProviderOverrideList( ProviderOverrideList overrideList, ) { overrideList.visitChildren(this); } @override void visitProviderOverrideExpression( ProviderOverrideExpression expression, ) { expression.visitChildren(this); } @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression container, ) { container.visitChildren(this); } @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ) { expression.visitChildren(this); } @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) { declaration.visitChildren(this); } @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) { declaration.visitChildren(this); } @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) { declaration.visitChildren(this); } @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) { dependencies.visitChildren(this); } @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) { dependency.visitChildren(this); } @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) { expression.visitChildren(this); } @override void visitRefListenInvocation(RefListenInvocation invocation) { invocation.visitChildren(this); } @override void visitRefReadInvocation(RefReadInvocation invocation) { invocation.visitChildren(this); } @override void visitRefWatchInvocation(RefWatchInvocation invocation) { invocation.visitChildren(this); } @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) { result.visitChildren(this); } @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) { annotation.visitChildren(this); } @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) { dependency.visitChildren(this); } @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) { dependencies.visitChildren(this); } @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) { declaration.visitChildren(this); } @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) { declaration.visitChildren(this); } @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) { declaration.visitChildren(this); } @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) { invocation.visitChildren(this); } @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) { invocation.visitChildren(this); } @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) { invocation.visitChildren(this); } @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) { invocation.visitChildren(this); } @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) { declaration.visitChildren(this); } @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) { declaration.visitChildren(this); } } class SimpleRiverpodAstVisitor extends RiverpodAstVisitor { @override void visitProviderOverrideList( ProviderOverrideList overrideList, ) {} @override void visitProviderOverrideExpression( ProviderOverrideExpression expression, ) {} @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression container, ) {} @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ) {} @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) {} @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) {} @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) {} @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) {} @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) {} @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) {} @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) {} @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) {} @override void visitRefListenInvocation(RefListenInvocation invocation) {} @override void visitRefReadInvocation(RefReadInvocation invocation) {} @override void visitRefWatchInvocation(RefWatchInvocation invocation) {} @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) {} @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) {} @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) {} @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) {} @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) {} @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) {} @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) {} @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) {} @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) {} @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) {} @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) {} } class UnimplementedRiverpodAstVisitor extends RiverpodAstVisitor { @override void visitProviderOverrideList( ProviderOverrideList overrideList, ) { throw UnimplementedError( 'implement visitProviderOverrideList', ); } @override void visitProviderOverrideExpression( ProviderOverrideExpression expression, ) { throw UnimplementedError( 'implement visitProviderOverrideExpression', ); } @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression container, ) { throw UnimplementedError( 'implement visitProviderScopeInstanceCreationExpression', ); } @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ) { throw UnimplementedError( 'implement visitProviderContainerInstanceCreationExpression', ); } @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) { throw UnimplementedError('implement visitConsumerStateDeclaration'); } @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) { throw UnimplementedError( 'implement visitConsumerStatefulWidgetDeclaration', ); } @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) { throw UnimplementedError('implement visitConsumerWidgetDeclaration'); } @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) { throw UnimplementedError('implement visitHookConsumerWidgetDeclaration'); } @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) { throw UnimplementedError('implement visitLegacyProviderDeclaration'); } @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) { throw UnimplementedError('implement visitLegacyProviderDependencies'); } @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) { throw UnimplementedError('implement visitLegacyProviderDependency'); } @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) { throw UnimplementedError('implement visitProviderListenableExpression'); } @override void visitRefListenInvocation(RefListenInvocation invocation) { throw UnimplementedError('implement visitRefListenInvocation'); } @override void visitRefReadInvocation(RefReadInvocation invocation) { throw UnimplementedError('implement visitRefReadInvocation'); } @override void visitRefWatchInvocation(RefWatchInvocation invocation) { throw UnimplementedError('implement visitRefWatchInvocation'); } @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) { throw UnimplementedError('implement visitResolvedRiverpodUnit'); } @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) { throw UnimplementedError('implement visitRiverpodAnnotation'); } @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) { throw UnimplementedError('implement visitRiverpodAnnotationDependency'); } @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) { throw UnimplementedError('implement visitRiverpodAnnotationDependencies'); } @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) { throw UnimplementedError( 'implement visitStatefulHookConsumerWidgetDeclaration', ); } @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) { throw UnimplementedError('implement visitClassBasedProviderDeclaration'); } @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) { throw UnimplementedError('implement visitFunctionalProviderDeclaration'); } @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) { throw UnimplementedError('implement visitWidgetRefListenInvocation'); } @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) { throw UnimplementedError('implement visitWidgetRefListenManualInvocation'); } @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) { throw UnimplementedError('implement visitWidgetRefReadInvocation'); } @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) { throw UnimplementedError('implement visitWidgetRefWatchInvocation'); } } class RiverpodAstRegistry { void run(RiverpodAst node) { node.accept(_RiverpodAstRegistryVisitor(this)); } // misc final _onResolvedRiverpodUnit = <void Function(ResolvedRiverpodLibraryResult)>[]; void addRiverpodUnit(void Function(ResolvedRiverpodLibraryResult) cb) { _onResolvedRiverpodUnit.add(cb); } // Both generator and legacy visitors void addProviderDeclaration(void Function(ProviderDeclaration) cb) { addGeneratorProviderDeclaration(cb); addLegacyProviderDeclaration(cb); } // Generator-specific visitors void addGeneratorProviderDeclaration( void Function(GeneratorProviderDeclaration) cb, ) { addClassBasedProviderDeclaration(cb); addFunctionalProviderDeclaration(cb); } final _onClassBasedProviderDeclaration = <void Function(ClassBasedProviderDeclaration)>[]; void addClassBasedProviderDeclaration( void Function(ClassBasedProviderDeclaration) cb, ) { _onClassBasedProviderDeclaration.add(cb); } final _onFunctionalProviderDeclaration = <void Function(FunctionalProviderDeclaration)>[]; void addFunctionalProviderDeclaration( void Function(FunctionalProviderDeclaration) cb, ) { _onFunctionalProviderDeclaration.add(cb); } final _onRiverpodAnnotation = <void Function(RiverpodAnnotation)>[]; void addRiverpodAnnotation( void Function(RiverpodAnnotation) cb, ) { _onRiverpodAnnotation.add(cb); } final _onRiverpodAnnotationDependency = <void Function(RiverpodAnnotationDependency)>[]; void addRiverpodAnnotationDependency( void Function(RiverpodAnnotationDependency) cb, ) { _onRiverpodAnnotationDependency.add(cb); } final _onRiverpodAnnotationDependencies = <void Function(RiverpodAnnotationDependencies)>[]; void addRiverpodAnnotationDependencies( void Function(RiverpodAnnotationDependencies) cb, ) { _onRiverpodAnnotationDependencies.add(cb); } // Legacy-specific visitors final _onLegacyProviderDeclaration = <void Function(LegacyProviderDeclaration)>[]; void addLegacyProviderDeclaration( void Function(LegacyProviderDeclaration) cb, ) { _onLegacyProviderDeclaration.add(cb); } final _onLegacyProviderDependencies = <void Function(LegacyProviderDependencies)>[]; void addLegacyProviderDependencies( void Function(LegacyProviderDependencies) cb, ) { _onLegacyProviderDependencies.add(cb); } final _onLegacyProviderDependency = <void Function(LegacyProviderDependency)>[]; void addLegacyProviderDependency( void Function(LegacyProviderDependency) cb, ) { _onLegacyProviderDependency.add(cb); } // Ref life-cycle visitors final _onRefInvocation = <void Function(RefInvocation)>[]; void addRefInvocation( void Function(RefInvocation) cb, ) { _onRefInvocation.add(cb); } final _onRefWatchInvocation = <void Function(RefWatchInvocation)>[]; void addRefWatchInvocation( void Function(RefWatchInvocation) cb, ) { _onRefWatchInvocation.add(cb); } final _onRefListenInvocation = <void Function(RefListenInvocation)>[]; void addRefListenInvocation( void Function(RefListenInvocation) cb, ) { _onRefListenInvocation.add(cb); } final _onRefReadInvocation = <void Function(RefReadInvocation)>[]; void addRefReadInvocation( void Function(RefReadInvocation) cb, ) { _onRefReadInvocation.add(cb); } // WidgetRef life-cycle visitors final _onWidgetRefInvocation = <void Function(WidgetRefInvocation)>[]; void addWidgetRefInvocation( void Function(WidgetRefInvocation) cb, ) { _onWidgetRefInvocation.add(cb); } final _onWidgetRefWatchInvocation = <void Function(WidgetRefWatchInvocation)>[]; void addWidgetRefWatchInvocation( void Function(WidgetRefWatchInvocation) cb, ) { _onWidgetRefWatchInvocation.add(cb); } final _onWidgetRefReadInvocation = <void Function(WidgetRefReadInvocation)>[]; void addWidgetRefReadInvocation( void Function(WidgetRefReadInvocation) cb, ) { _onWidgetRefReadInvocation.add(cb); } final _onWidgetRefListenInvocation = <void Function(WidgetRefListenInvocation)>[]; void addWidgetRefListenInvocation( void Function(WidgetRefListenInvocation) cb, ) { _onWidgetRefListenInvocation.add(cb); } final _onWidgetRefListenManualInvocation = <void Function(WidgetRefListenManualInvocation)>[]; void addWidgetRefListenManualInvocation( void Function(WidgetRefListenManualInvocation) cb, ) { _onWidgetRefListenManualInvocation.add(cb); } // Ref misc final _onProviderListenableExpression = <void Function(ProviderListenableExpression)>[]; void addProviderListenableExpression( void Function(ProviderListenableExpression) cb, ) { _onProviderListenableExpression.add(cb); } // Consumers final _onConsumerWidgetDeclaration = <void Function(ConsumerWidgetDeclaration)>[]; void addConsumerWidgetDeclaration( void Function(ConsumerWidgetDeclaration) cb, ) { _onConsumerWidgetDeclaration.add(cb); } final _onHookConsumerWidgetDeclaration = <void Function(HookConsumerWidgetDeclaration)>[]; void addHookConsumerWidgetDeclaration( void Function(HookConsumerWidgetDeclaration) cb, ) { _onHookConsumerWidgetDeclaration.add(cb); } final _onStatefulHookConsumerWidgetDeclaration = <void Function(StatefulHookConsumerWidgetDeclaration)>[]; void addStatefulHookConsumerWidgetDeclaration( void Function(StatefulHookConsumerWidgetDeclaration) cb, ) { _onStatefulHookConsumerWidgetDeclaration.add(cb); } final _onConsumerStatefulWidgetDeclaration = <void Function(ConsumerStatefulWidgetDeclaration)>[]; void addConsumerStatefulWidgetDeclaration( void Function(ConsumerStatefulWidgetDeclaration) cb, ) { _onConsumerStatefulWidgetDeclaration.add(cb); } final _onConsumerStateDeclaration = <void Function(ConsumerStateDeclaration)>[]; void addConsumerStateDeclaration( void Function(ConsumerStateDeclaration) cb, ) { _onConsumerStateDeclaration.add(cb); } final _onProviderScopeInstanceCreationExpression = <void Function(ProviderScopeInstanceCreationExpression)>[]; void addProviderScopeInstanceCreationExpression( void Function(ProviderScopeInstanceCreationExpression) cb, ) { _onProviderScopeInstanceCreationExpression.add(cb); } final _onProviderContainerInstanceCreationExpression = <void Function(ProviderContainerInstanceCreationExpression)>[]; void addProviderContainerInstanceCreationExpression( void Function(ProviderContainerInstanceCreationExpression) cb, ) { _onProviderContainerInstanceCreationExpression.add(cb); } final _onProviderOverrideExpression = <void Function(ProviderOverrideExpression)>[]; void addProviderOverrideExpression( void Function(ProviderOverrideExpression) cb, ) { _onProviderOverrideExpression.add(cb); } final _onProviderOverrideList = <void Function(ProviderOverrideList)>[]; void addProviderOverrideList(void Function(ProviderOverrideList) cb) { _onProviderOverrideList.add(cb); } } // Voluntarily not extenting RiverpodAstVisitor to trigger a compilation error // when new nodes are added. class _RiverpodAstRegistryVisitor extends RiverpodAstVisitor { _RiverpodAstRegistryVisitor(this._registry); final RiverpodAstRegistry _registry; @override void visitProviderOverrideList( ProviderOverrideList overrideList, ) { overrideList.visitChildren(this); _runSubscriptions( overrideList, _registry._onProviderOverrideList, ); } @override void visitProviderOverrideExpression( ProviderOverrideExpression expression, ) { expression.visitChildren(this); _runSubscriptions( expression, _registry._onProviderOverrideExpression, ); } @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression container, ) { container.visitChildren(this); _runSubscriptions( container, _registry._onProviderScopeInstanceCreationExpression, ); } @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ) { expression.visitChildren(this); _runSubscriptions( expression, _registry._onProviderContainerInstanceCreationExpression, ); } @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) { declaration.visitChildren(this); _runSubscriptions(declaration, _registry._onConsumerStateDeclaration); } @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) { declaration.visitChildren(this); _runSubscriptions(declaration, _registry._onConsumerWidgetDeclaration); } @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) { declaration.visitChildren(this); _runSubscriptions(declaration, _registry._onLegacyProviderDeclaration); } @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) { dependencies.visitChildren(this); _runSubscriptions(dependencies, _registry._onLegacyProviderDependencies); } @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) { dependency.visitChildren(this); _runSubscriptions(dependency, _registry._onLegacyProviderDependency); } @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) { expression.visitChildren(this); _runSubscriptions(expression, _registry._onProviderListenableExpression); } @override void visitRefListenInvocation(RefListenInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onRefListenInvocation); } @override void visitRefReadInvocation(RefReadInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onRefReadInvocation); } @override void visitRefWatchInvocation(RefWatchInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onRefWatchInvocation); } @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) { result.visitChildren(this); _runSubscriptions(result, _registry._onResolvedRiverpodUnit); } @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) { annotation.visitChildren(this); _runSubscriptions(annotation, _registry._onRiverpodAnnotation); } @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) { dependency.visitChildren(this); _runSubscriptions(dependency, _registry._onRiverpodAnnotationDependency); } @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) { dependencies.visitChildren(this); _runSubscriptions( dependencies, _registry._onRiverpodAnnotationDependencies, ); } @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) { declaration.visitChildren(this); _runSubscriptions( declaration, _registry._onConsumerStatefulWidgetDeclaration, ); } @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) { declaration.visitChildren(this); _runSubscriptions(declaration, _registry._onClassBasedProviderDeclaration); } @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) { declaration.visitChildren(this); _runSubscriptions( declaration, _registry._onFunctionalProviderDeclaration, ); } @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onWidgetRefListenInvocation); } @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onWidgetRefListenManualInvocation); } @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onWidgetRefReadInvocation); } @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) { invocation.visitChildren(this); _runSubscriptions(invocation, _registry._onWidgetRefWatchInvocation); } void _runSubscriptions<R>( R value, List<void Function(R)> subscriptions, ) { for (final sub in subscriptions) { try { sub(value); } catch (e, stack) { Zone.current.handleUncaughtError(e, stack); } } } @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) { declaration.visitChildren(this); _runSubscriptions(declaration, _registry._onHookConsumerWidgetDeclaration); } @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) { declaration.visitChildren(this); _runSubscriptions( declaration, _registry._onStatefulHookConsumerWidgetDeclaration, ); } }
riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/visitor.dart/0
{'file_path': 'riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/visitor.dart', 'repo_id': 'riverpod', 'token_count': 8268}
import 'package:test/test.dart'; import 'analyzer_test_utils.dart'; void main() { testSource('Decode watch expressions with syntax errors', source: ''' import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; @ProviderFor(gibberish) final gibberishProvider = Provider((ref) => 0); class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(gibberishProvider); return Container(); } } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult( ignoreErrors: true, ); expect(result.widgetRefWatchInvocations, hasLength(1)); expect(result.widgetRefInvocations.single.function.toSource(), 'watch'); expect( result.widgetRefInvocations.single.node.toSource(), 'ref.watch(gibberishProvider)', ); expect( result.widgetRefWatchInvocations.single.provider.familyArguments, null, ); expect( result.widgetRefWatchInvocations.single.provider.node.toSource(), 'gibberishProvider', ); expect( result.widgetRefWatchInvocations.single.provider.provider?.toSource(), 'gibberishProvider', ); expect( result.widgetRefWatchInvocations.single.provider.providerElement, null, ); }); testSource('Decodes ..watch', runGenerator: true, source: r''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; final dep = FutureProvider((ref) => 0); @Riverpod(keepAlive: true) Future<int> dep2(Dep2Ref ref) async => 0; @Riverpod(keepAlive: true) class Dep3 extends _$Dep3 { @override Future<int> build() async => 0; } class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref ..watch(dep) ..watch(dep2Provider) ..watch(dep3Provider); return Container(); } } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefWatchInvocations, hasLength(3)); expect(result.widgetRefInvocations, result.widgetRefWatchInvocations); expect( result.widgetRefWatchInvocations[0].node.toSource(), '..watch(dep)', ); expect(result.widgetRefWatchInvocations[0].function.toSource(), 'watch'); expect(result.widgetRefWatchInvocations[0].provider.node.toSource(), 'dep'); expect(result.widgetRefWatchInvocations[0].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[0].provider.provider?.toSource(), 'dep', ); expect( result.widgetRefWatchInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefWatchInvocations[1].node.toSource(), '..watch(dep2Provider)', ); expect(result.widgetRefWatchInvocations[1].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[1].provider.node.toSource(), 'dep2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.provider?.toSource(), 'dep2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.providerElement, same( result.functionalProviderDeclarations .findByName('dep2') .providerElement, ), ); expect(result.widgetRefWatchInvocations[1].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[2].node.toSource(), '..watch(dep3Provider)', ); expect(result.widgetRefWatchInvocations[2].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[2].provider.node.toSource(), 'dep3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.provider?.toSource(), 'dep3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.providerElement, same( result.classBasedProviderDeclarations .findByName('Dep3') .providerElement, ), ); expect(result.widgetRefWatchInvocations[2].provider.familyArguments, null); }); testSource('Decodes simple ref.watch usages', runGenerator: true, source: r''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; extension on WidgetRef { void fn() {} } final dep = FutureProvider((ref) => 0); @Riverpod(keepAlive: true) Future<int> dep2(Dep2Ref ref) async => 0; @Riverpod(keepAlive: true) class Dep3 extends _$Dep3 { @override Future<int> build() async => 0; } class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(dep); ref.watch(dep2Provider); ref.watch(dep3Provider); ref.fn(); return Container(); } } class _Ref { void watch(ProviderBase provider) {} } void fn(_Ref ref) { ref.watch(dep); } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefWatchInvocations, hasLength(3)); expect(result.widgetRefInvocations, result.widgetRefWatchInvocations); expect( result.widgetRefWatchInvocations[0].node.toSource(), 'ref.watch(dep)', ); expect(result.widgetRefWatchInvocations[0].function.toSource(), 'watch'); expect(result.widgetRefWatchInvocations[0].provider.node.toSource(), 'dep'); expect(result.widgetRefWatchInvocations[0].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[0].provider.provider?.toSource(), 'dep', ); expect( result.widgetRefWatchInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefWatchInvocations[1].node.toSource(), 'ref.watch(dep2Provider)', ); expect(result.widgetRefWatchInvocations[1].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[1].provider.node.toSource(), 'dep2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.provider?.toSource(), 'dep2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.providerElement, same( result.functionalProviderDeclarations .findByName('dep2') .providerElement, ), ); expect(result.widgetRefWatchInvocations[1].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[2].node.toSource(), 'ref.watch(dep3Provider)', ); expect(result.widgetRefWatchInvocations[2].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[2].provider.node.toSource(), 'dep3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.provider?.toSource(), 'dep3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.providerElement, same( result.classBasedProviderDeclarations .findByName('Dep3') .providerElement, ), ); expect(result.widgetRefWatchInvocations[2].provider.familyArguments, null); }); testSource('Decodes unknown ref usages', source: ''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; final dep = FutureProvider((ref) => 0); final dep2 = FutureProvider((ref) => 0); void fn(WidgetRef ref) { ref.read(dep); ref.read(dep2); } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); final libraryResult = result.resolvedRiverpodLibraryResults.single; expect(libraryResult.unknownWidgetRefInvocations, hasLength(2)); expect( result.widgetRefReadInvocations, libraryResult.unknownWidgetRefInvocations, ); expect(result.widgetRefInvocations, result.widgetRefReadInvocations); expect(result.widgetRefReadInvocations[0].node.toSource(), 'ref.read(dep)'); expect(result.widgetRefReadInvocations[0].function.toSource(), 'read'); expect( result.widgetRefReadInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefReadInvocations[1].node.toSource(), 'ref.read(dep2)', ); expect(result.widgetRefReadInvocations[1].function.toSource(), 'read'); expect( result.widgetRefReadInvocations[1].provider.providerElement, same( result.legacyProviderDeclarations.findByName('dep2').providerElement, ), ); }); testSource('Decodes ref.listen usages', runGenerator: true, source: ''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; final dep = FutureProvider((ref) => 0); class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.listen<AsyncValue<int>>(dep, (prev, next) {}); return Container(); } } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefListenInvocations, hasLength(1)); expect(result.widgetRefInvocations, result.widgetRefListenInvocations); expect( result.widgetRefListenInvocations[0].node.toSource(), 'ref.listen<AsyncValue<int>>(dep, (prev, next) {})', ); expect(result.widgetRefListenInvocations[0].function.toSource(), 'listen'); expect( result.widgetRefListenInvocations[0].listener.toSource(), '(prev, next) {}', ); expect( result.widgetRefListenInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); }); testSource('Decodes ref.listenManual usages', runGenerator: true, source: ''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; final dep = FutureProvider((ref) => 0); class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.listenManual<AsyncValue<int>>(dep, (prev, next) {}); ref.listenManual<AsyncValue<int>>(dep, (prev, next) {}, fireImmediately: true); ref.listenManual<AsyncValue<int>>(fireImmediately: true, dep, (prev, next) {}); return Container(); } } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefListenManualInvocations, hasLength(3)); expect( result.widgetRefInvocations, result.widgetRefListenManualInvocations, ); expect( result.widgetRefListenManualInvocations[0].node.toSource(), 'ref.listenManual<AsyncValue<int>>(dep, (prev, next) {})', ); expect( result.widgetRefListenManualInvocations[0].function.toSource(), 'listenManual', ); expect( result.widgetRefListenManualInvocations[0].listener.toSource(), '(prev, next) {}', ); expect( result.widgetRefListenManualInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefListenManualInvocations[1].node.toSource(), 'ref.listenManual<AsyncValue<int>>(dep, (prev, next) {}, fireImmediately: true)', ); expect( result.widgetRefListenManualInvocations[1].function.toSource(), 'listenManual', ); expect( result.widgetRefListenManualInvocations[1].listener.toSource(), '(prev, next) {}', ); expect( result.widgetRefListenManualInvocations[1].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefListenManualInvocations[2].node.toSource(), 'ref.listenManual<AsyncValue<int>>(fireImmediately: true, dep, (prev, next) {})', ); expect( result.widgetRefListenManualInvocations[2].function.toSource(), 'listenManual', ); expect( result.widgetRefListenManualInvocations[2].listener.toSource(), '(prev, next) {}', ); expect( result.widgetRefListenManualInvocations[2].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); }); testSource('Decodes ref.read usages', runGenerator: true, source: ''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; final dep = FutureProvider((ref) => 0); final dep2 = FutureProvider((ref) => 0); class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.read(dep); ref.read(dep2); return Container(); } } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefReadInvocations, hasLength(2)); expect(result.widgetRefInvocations, result.widgetRefReadInvocations); expect(result.widgetRefReadInvocations[0].node.toSource(), 'ref.read(dep)'); expect(result.widgetRefReadInvocations[0].function.toSource(), 'read'); expect( result.widgetRefReadInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefReadInvocations[1].node.toSource(), 'ref.read(dep2)', ); expect(result.widgetRefReadInvocations[1].function.toSource(), 'read'); expect( result.widgetRefReadInvocations[1].provider.providerElement, same( result.legacyProviderDeclarations.findByName('dep2').providerElement, ), ); }); testSource('Decodes family ref.watch usages', runGenerator: true, source: r''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; extension on WidgetRef { void fn() {} } final family = FutureProvider.family<int, int>((ref, id) => 0); @Riverpod(keepAlive: true) Future<int> family2(Family2Ref ref, {required int id}) async => 0; @Riverpod(keepAlive: true) class Family3 extends _$Family3 { @override Future<int> build({required int id}) async => 0; } class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(family(0)); ref.watch(family2Provider(id: 0)); ref.watch(family3Provider(id: 0)); return Container(); } } class _Ref { void watch(ProviderBase provider) {} } void fn(_Ref ref) { ref.watch(family(0)); } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); final libraryResult = result.resolvedRiverpodLibraryResults.single; expect(libraryResult.unknownRefInvocations, isEmpty); expect(libraryResult.unknownWidgetRefInvocations, isEmpty); final providerRefInvocations = libraryResult.consumerWidgetDeclarations.single.widgetRefInvocations; expect(result.widgetRefWatchInvocations, hasLength(3)); expect(result.widgetRefInvocations, result.widgetRefWatchInvocations); expect(result.widgetRefInvocations, providerRefInvocations); expect( result.widgetRefWatchInvocations[0].node.toSource(), 'ref.watch(family(0))', ); expect(result.widgetRefWatchInvocations[0].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[0].provider.node.toSource(), 'family(0)', ); expect( result.widgetRefWatchInvocations[0].provider.provider?.toSource(), 'family', ); expect( result.widgetRefWatchInvocations[0].provider.providerElement, same( result.legacyProviderDeclarations.findByName('family').providerElement, ), ); expect( result.widgetRefWatchInvocations[0].provider.familyArguments?.toSource(), '(0)', ); expect( result.widgetRefWatchInvocations[1].node.toSource(), 'ref.watch(family2Provider(id: 0))', ); expect(result.widgetRefWatchInvocations[1].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[1].provider.node.toSource(), 'family2Provider(id: 0)', ); expect( result.widgetRefWatchInvocations[1].provider.provider?.toSource(), 'family2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.providerElement, same( result.functionalProviderDeclarations .findByName('family2') .providerElement, ), ); expect( result.widgetRefWatchInvocations[1].provider.familyArguments?.toSource(), '(id: 0)', ); expect( result.widgetRefWatchInvocations[2].node.toSource(), 'ref.watch(family3Provider(id: 0))', ); expect(result.widgetRefWatchInvocations[2].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[2].provider.node.toSource(), 'family3Provider(id: 0)', ); expect( result.widgetRefWatchInvocations[2].provider.provider?.toSource(), 'family3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.providerElement, same( result.classBasedProviderDeclarations .findByName('Family3') .providerElement, ), ); expect( result.widgetRefWatchInvocations[2].provider.familyArguments?.toSource(), '(id: 0)', ); }); testSource('Decodes provider.query ref.watch usages', runGenerator: true, source: r''' import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; part 'foo.g.dart'; extension on WidgetRef { void fn() {} } final dep = FutureProvider((ref) => 0); @Riverpod(keepAlive: true) Future<int> dep2(Dep2Ref ref) async => 0; @Riverpod(keepAlive: true) class Dep3 extends _$Dep3 { @override Future<int> build() async => 0; } @Riverpod(keepAlive: true) class Family extends _$Family { @override Future<int> build({required int id}) async => 0; } class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(dep.select((e) => e)); ref.watch(dep2Provider.select((e) => e)); ref.watch(dep3Provider.select((e) => e)); ref.watch(familyProvider(id: 42).notifier.select((e) => e).getter.method()[0]); return Container(); } } extension<T> on T { T get getter => this; T method() => this; T operator[](Object key) => this; } class _Ref { void watch(ProviderBase provider) {} } void fn(_Ref ref) { ref.watch(dep); } ''', (resolver) async { final result = await resolver.resolveRiverpodAnalysisResult(); expect(result.widgetRefWatchInvocations, hasLength(4)); expect(result.widgetRefInvocations, result.widgetRefWatchInvocations); expect( result.widgetRefWatchInvocations[0].node.toSource(), 'ref.watch(dep.select((e) => e))', ); expect(result.widgetRefWatchInvocations[0].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[0].provider.node.toSource(), 'dep.select((e) => e)', ); expect(result.widgetRefWatchInvocations[0].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[0].provider.provider?.toSource(), 'dep', ); expect( result.widgetRefWatchInvocations[0].provider.providerElement, same(result.legacyProviderDeclarations.findByName('dep').providerElement), ); expect( result.widgetRefWatchInvocations[1].node.toSource(), 'ref.watch(dep2Provider.select((e) => e))', ); expect(result.widgetRefWatchInvocations[1].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[1].provider.node.toSource(), 'dep2Provider.select((e) => e)', ); expect(result.widgetRefWatchInvocations[1].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[1].provider.provider?.toSource(), 'dep2Provider', ); expect( result.widgetRefWatchInvocations[1].provider.providerElement, same( result.functionalProviderDeclarations .findByName('dep2') .providerElement, ), ); expect( result.widgetRefWatchInvocations[2].node.toSource(), 'ref.watch(dep3Provider.select((e) => e))', ); expect(result.widgetRefWatchInvocations[2].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[2].provider.node.toSource(), 'dep3Provider.select((e) => e)', ); expect(result.widgetRefWatchInvocations[2].provider.familyArguments, null); expect( result.widgetRefWatchInvocations[2].provider.provider?.toSource(), 'dep3Provider', ); expect( result.widgetRefWatchInvocations[2].provider.providerElement, same( result.classBasedProviderDeclarations .findByName('Dep3') .providerElement, ), ); expect( result.widgetRefWatchInvocations[3].node.toSource(), 'ref.watch(familyProvider(id: 42).notifier.select((e) => e).getter.method()[0])', ); expect(result.widgetRefWatchInvocations[3].function.toSource(), 'watch'); expect( result.widgetRefWatchInvocations[3].provider.node.toSource(), 'familyProvider(id: 42).notifier.select((e) => e).getter.method()[0]', ); expect( result.widgetRefWatchInvocations[3].provider.familyArguments?.toSource(), '(id: 42)', ); expect( result.widgetRefWatchInvocations[3].provider.provider?.toSource(), 'familyProvider', ); expect( result.widgetRefWatchInvocations[3].provider.providerElement, same( result.classBasedProviderDeclarations .findByName('Family') .providerElement, ), ); }); }
riverpod/packages/riverpod_analyzer_utils_tests/test/widget_ref_invocation_test.dart/0
{'file_path': 'riverpod/packages/riverpod_analyzer_utils_tests/test/widget_ref_invocation_test.dart', 'repo_id': 'riverpod', 'token_count': 8778}
name: codemod_riverpod_test_notifiers_golden description: Test riverpod codemods publish_to: none environment: sdk: ">=2.17.0-0 <3.0.0" dependencies: flutter: sdk: flutter flutter_hooks: flutter_riverpod: hooks_riverpod: riverpod:
riverpod/packages/riverpod_cli/fixtures/notifiers/golden/pubspec.yaml/0
{'file_path': 'riverpod/packages/riverpod_cli/fixtures/notifiers/golden/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 106}
import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:codemod/codemod.dart'; import 'package:glob/glob.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'migrate/errors.dart'; import 'migrate/imports.dart'; import 'migrate/notifiers.dart'; import 'migrate/unified_syntax.dart'; import 'migrate/version.dart'; class MigrateCommand extends Command<void> { MigrateCommand() { argParser ..addFlag( 'verbose', abbr: 'v', negatable: false, help: 'Outputs all logging to stdout/stderr.', ) ..addFlag( 'yes-to-all', negatable: false, help: 'Forces all patches accepted without prompting the user. ' 'Useful for scripts.', ) ..addFlag( 'fail-on-changes', negatable: false, help: 'Returns a non-zero exit code if there are changes to be made. ' 'Will not make any changes (i.e. this is a dry-run).', ) ..addFlag( 'stderr-assume-tty', negatable: false, help: 'Forces ansi color highlighting of stderr. Useful for debugging.', ); } @override String get name => 'migrate'; @override String get description => 'Analyze a project using Riverpod and migrate it to the latest version available'; @override Future<void> run() async { final pubspecFile = File('pubspec.yaml'); if (!pubspecFile.existsSync()) { stderr.writeln( 'Pubspec not found! Are you in the root directory of your package / app?', ); exit(-1); } final pubspec = Pubspec.parse(pubspecFile.readAsStringSync()); final dep = pubspec.dependencies['hooks_riverpod'] ?? pubspec.dependencies['flutter_riverpod'] ?? pubspec.dependencies['riverpod']; if (dep is! HostedDependency) { stderr.writeln( 'Migrating git and path dependencies can cause issues because of ' 'trying to understand riverpod versioning, please depend on an official package', ); exit(-1); } if (dep.version.allows(latestVersion)) { stderr.writeln( 'It seems like your project already has Riverpod $latestVersion installed.\n' 'The migration tool will not work if your project already uses the new ' 'version. To fix, downgrade the version of Riverpod then try again.', ); exit(-1); } await runInteractiveCodemodSequence( filePathsFromGlob(Glob('**.dart', recursive: true)), [ aggregate( [ RiverpodImportAllMigrationSuggestor().call, RiverpodNotifierChangesMigrationSuggestor(dep.version).call, ], ), RiverpodProviderUsageInfo(dep.version).call, RiverpodUnifiedSyntaxChangesMigrationSuggestor(dep.version).call, ], args: argResults?.arguments ?? [], ); await runInteractiveCodemod( filePathsFromGlob(Glob('pubspec.yaml', recursive: true)), versionMigrationSuggestor, args: argResults?.arguments ?? [], ); if (errorOccurredDuringMigration) { printErrorLogs(); } else { stdout.writeln( 'Migration finished successfully please run `flutter pub upgrade`', ); } } }
riverpod/packages/riverpod_cli/lib/src/migrate.dart/0
{'file_path': 'riverpod/packages/riverpod_cli/lib/src/migrate.dart', 'repo_id': 'riverpod', 'token_count': 1335}
include: ../../analysis_options.yaml linter: rules: # We don't really have public API public_member_api_docs: false
riverpod/packages/riverpod_generator/analysis_options.yaml/0
{'file_path': 'riverpod/packages/riverpod_generator/analysis_options.yaml', 'repo_id': 'riverpod', 'token_count': 45}
import 'package:riverpod/riverpod.dart'; /// standard example Counter class class Counter { /// docs Counter({this.value = 0}); /// counter value late final int value; /// immutable increment Counter increment() { return Counter(value: value + 1); } } /// ///Extract from example /// class MarvelRepository { // ignore: public_member_api_docs MarvelRepository( this.ref, { int Function()? getCurrentTimestamp, }) : _getCurrentTimestamp = getCurrentTimestamp ?? (() => DateTime.now().millisecondsSinceEpoch); /// final Ref ref; /// final int Function() _getCurrentTimestamp; } /// taken from the marvel example /// referenced in marvelTearOffConsumer final marvelRefdProvider = Provider(MarvelRepository.new); /// not ref'd anywhere final marvelLostProvider = Provider(MarvelRepository.new); /// This provider will **not** be picked up by the analyzer. /// /// analyze.dart docs say: Providers must be either top level element or static element of classes. class MarvelLostProviderContainer { /// creating a reference static final marvelLostProviderInContainer = Provider(MarvelRepository.new); } /// read/watch/listen seem to be required to bring this in scope for analysis /// just references are not enough final marvelTearOffConsumer = Provider((ref) { // ignore: unused_element void doSomething() { // ignore: unused_local_variable final theTime = ref.read(marvelRefdProvider)._getCurrentTimestamp; } });
riverpod/packages/riverpod_graph/test/integration/addition/golden/lib/constructor_providers.dart/0
{'file_path': 'riverpod/packages/riverpod_graph/test/integration/addition/golden/lib/constructor_providers.dart', 'repo_id': 'riverpod', 'token_count': 429}
import 'package:custom_lint_builder/custom_lint_builder.dart'; import 'src/assists/class_based_to_functional_provider.dart'; import 'src/assists/convert_to_stateful_base_widget.dart'; import 'src/assists/convert_to_stateless_base_widget.dart'; import 'src/assists/convert_to_widget_utils.dart'; import 'src/assists/functional_to_class_based_provider.dart'; import 'src/assists/wrap_with_consumer.dart'; import 'src/assists/wrap_with_provider_scope.dart'; import 'src/lints/async_value_nullable_pattern.dart'; import 'src/lints/avoid_build_context_in_providers.dart'; import 'src/lints/avoid_manual_providers_as_generated_provider_dependency.dart'; import 'src/lints/avoid_public_notifier_properties.dart'; import 'src/lints/avoid_ref_inside_state_dispose.dart'; import 'src/lints/functional_ref.dart'; import 'src/lints/missing_provider_scope.dart'; import 'src/lints/notifier_build.dart'; import 'src/lints/notifier_extends.dart'; import 'src/lints/protected_notifier_properties.dart'; import 'src/lints/provider_dependencies.dart'; import 'src/lints/provider_parameters.dart'; import 'src/lints/scoped_providers_should_specify_dependencies.dart'; import 'src/lints/unsupported_provider_value.dart'; PluginBase createPlugin() => _RiverpodPlugin(); class _RiverpodPlugin extends PluginBase { @override List<LintRule> getLintRules(CustomLintConfigs configs) => [ const AvoidBuildContextInProviders(), const AvoidPublicNotifierProperties(), const FunctionalRef(), const MissingProviderScope(), const ProviderParameters(), const NotifierExtends(), const ProviderDependencies(), const AvoidManualProvidersAsGeneratedProviderDependency(), const ScopedProvidersShouldSpecifyDependencies(), const UnsupportedProviderValue(), const AvoidRefInsideStateDispose(), const NotifierBuild(), const AsyncValueNullablePattern(), const ProtectedNotifierProperties(), ]; @override List<Assist> getAssists() => [ WrapWithConsumer(), WrapWithProviderScope(), ...StatelessBaseWidgetType.values.map( (targetWidget) => ConvertToStatelessBaseWidget( targetWidget: targetWidget, ), ), ...StatefulBaseWidgetType.values.map( (targetWidget) => ConvertToStatefulBaseWidget( targetWidget: targetWidget, ), ), FunctionalToClassBasedProvider(), ClassBasedToFunctionalProvider(), ]; }
riverpod/packages/riverpod_lint/lib/riverpod_lint.dart/0
{'file_path': 'riverpod/packages/riverpod_lint/lib/riverpod_lint.dart', 'repo_id': 'riverpod', 'token_count': 958}
import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:custom_lint_builder/custom_lint_builder.dart'; import 'package:riverpod_analyzer_utils/riverpod_analyzer_utils.dart'; import '../riverpod_custom_lint.dart'; class AsyncValueNullablePattern extends RiverpodLintRule { const AsyncValueNullablePattern() : super(code: _code); static const _code = LintCode( name: 'async_value_nullable_pattern', problemMessage: 'Using AsyncValue(:final value?) on possibly nullable value is unsafe. ' 'Use AsyncValue(:final value, hasValue: true) instead.', errorSeverity: ErrorSeverity.WARNING, ); @override void run( CustomLintResolver resolver, ErrorReporter reporter, CustomLintContext context, ) { context.registry.addNullCheckPattern((node) { // We are looking for "case AsyncValue(:final value?)" // We found the ? pattern final parent = node.parent; // Parent isn't a "final value" pattern if (parent is! PatternField || parent.effectiveName != 'value') return; final grandParent = parent.parent; // GrandParent isn't a "AsyncValue(...)" if (grandParent is! ObjectPattern) return; final grandParentType = grandParent.type.type; const asyncValueTypesToCheck = TypeChecker.any([ asyncValueType, asyncLoadingType, asyncErrorType, // No AsyncData in here as "hasValue" will always be true ]); // GrandParent isn't a "AsyncValue<T>" if (grandParentType == null || !asyncValueTypesToCheck.isExactlyType(grandParentType)) { return; } grandParentType as InterfaceType; var genericType = grandParentType.typeArguments.first; // If the AsyncValue's type is a generic type, we check the generic's constraint if (genericType is TypeParameterType) { final unit = node.thisOrAncestorOfType<CompilationUnit>()!; genericType = genericType.element.bound ?? unit.declaredElement!.library.typeProvider.dynamicType; } if (genericType is! DynamicType && genericType.nullabilitySuffix != NullabilitySuffix.question) { return; } reporter.reportErrorForNode(_code, node); }); } @override List<DartFix> getFixes() => [_AddHasDataFix()]; } class _AddHasDataFix extends DartFix { @override void run( CustomLintResolver resolver, ChangeReporter reporter, CustomLintContext context, AnalysisError analysisError, List<AnalysisError> others, ) { context.registry.addNullCheckPattern((node) { if (!node.sourceRange.intersects(analysisError.sourceRange)) return; final changeBuilder = reporter.createChangeBuilder( message: 'Use "hasValue: true" instead', priority: 100, ); changeBuilder.addDartFileEdit((builder) { builder.addDeletion(node.operator.sourceRange); builder.addSimpleInsertion(node.operator.end, ', hasValue: true'); }); }); } }
riverpod/packages/riverpod_lint/lib/src/lints/async_value_nullable_pattern.dart/0
{'file_path': 'riverpod/packages/riverpod_lint/lib/src/lints/async_value_nullable_pattern.dart', 'repo_id': 'riverpod', 'token_count': 1196}
import 'package:analyzer/error/listener.dart'; import 'package:custom_lint_builder/custom_lint_builder.dart'; import 'package:riverpod_analyzer_utils/riverpod_analyzer_utils.dart'; import '../riverpod_custom_lint.dart'; extension on ClassBasedProviderDeclaration { /// Returns whether the value exposed by the provider is the newly created /// Notifier itself. bool get returnsSelf { return valueTypeNode?.type == node.declaredElement?.thisType; } } class UnsupportedProviderValue extends RiverpodLintRule { const UnsupportedProviderValue() : super(code: _code); static const _code = LintCode( name: 'unsupported_provider_value', problemMessage: 'The riverpod_generator package does not support {0} values.', correctionMessage: 'If using {0} even though riverpod_generator does not support it, ' 'you can wrap the type in "Raw" to silence the warning. For example by returning Raw<{0}>.', ); @override void run( CustomLintResolver resolver, ErrorReporter reporter, CustomLintContext context, ) { void checkCreatedType(GeneratorProviderDeclaration declaration) { final valueType = declaration.valueTypeNode?.type; if (valueType == null || valueType.isRaw) return; String? invalidValueName; if (notifierBaseType.isAssignableFromType(valueType)) { invalidValueName = 'Notifier'; } else if (asyncNotifierBaseType.isAssignableFromType(valueType)) { invalidValueName = 'AsyncNotifier'; } /// If a provider returns itself, we allow it. This is to enable /// ChangeNotifier-like mutable state. if (invalidValueName != null && declaration is ClassBasedProviderDeclaration && declaration.returnsSelf) { return; } if (stateNotifierType.isAssignableFromType(valueType)) { invalidValueName = 'StateNotifier'; } else if (changeNotifierType.isAssignableFromType(valueType)) { invalidValueName = 'ChangeNotifier'; } if (invalidValueName != null) { reporter.reportErrorForToken( _code, declaration.name, [invalidValueName], ); } } riverpodRegistry(context) ..addFunctionalProviderDeclaration(checkCreatedType) ..addClassBasedProviderDeclaration(checkCreatedType); } }
riverpod/packages/riverpod_lint/lib/src/lints/unsupported_provider_value.dart/0
{'file_path': 'riverpod/packages/riverpod_lint/lib/src/lints/unsupported_provider_value.dart', 'repo_id': 'riverpod', 'token_count': 853}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; void main() { // expect_lint: missing_provider_scope runApp( MyApp(), ); runApp(ProviderScope(child: MyApp())); runApp( UncontrolledProviderScope( container: ProviderContainer(), child: MyApp(), ), ); } void definitelyNotAMain() { // expect_lint: missing_provider_scope runApp( MyApp(), ); runApp(ProviderScope(child: MyApp())); runApp( UncontrolledProviderScope( container: ProviderContainer(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const Placeholder(); } }
riverpod/packages/riverpod_lint_flutter_test/test/lints/missing_provider_scope.dart/0
{'file_path': 'riverpod/packages/riverpod_lint_flutter_test/test/lints/missing_provider_scope.dart', 'repo_id': 'riverpod', 'token_count': 276}
// ignore_for_file: prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'dropdown.dart'; import 'sort_provider.dart'; Widget build(BuildContext context, WidgetRef ref) { return AppBar(actions: [ /* SNIPPET START */ DropdownButton<ProductSortType>( // Cuando cambia el tipo de clasificación, esto reconstruirá el dropdown // para actualizar el icono que se muestra. value: ref.watch(productSortTypeProvider), // Cuando el usuario interactúa con el dropdown, actualizamos el estado del provider. onChanged: (value) => ref.read(productSortTypeProvider.notifier).state = value!, items: [ // ... ], ), /* SNIPPET END */ ]); }
riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/state_provider/connected_dropdown.dart/0
{'file_path': 'riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/state_provider/connected_dropdown.dart', 'repo_id': 'riverpod', 'token_count': 261}
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'reading_counter.dart'; /* SNIPPET START */ class HomeView extends HookConsumerWidget { const HomeView({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { // HookConsumerWidget permet d'utiliser des hooks dans la méthode de build. final state = useState(0); // On peut également utiliser le paramètre ref pour écouter les providers. final counter = ref.watch(counterProvider); return Text('$counter'); } }
riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook_widget.dart/0
{'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook_widget.dart', 'repo_id': 'riverpod', 'token_count': 217}
name: my_app_name environment: sdk: ">=2.17.0 <3.0.0" dependencies: riverpod: ^2.1.1 riverpod_annotation: ^1.0.6 dev_dependencies: build_runner: riverpod_generator: ^1.0.6
riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/getting_started/dart_pubspec/codegen.yaml/0
{'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/getting_started/dart_pubspec/codegen.yaml', 'repo_id': 'riverpod', 'token_count': 87}
// ignore_for_file: unused_local_variable import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'codegen.g.dart'; late WidgetRef ref; /* SNIPPET START */ @riverpod String label(LabelRef ref, String userName) { return 'Hello $userName'; } // ... void onTap() { // Invalida tutte le possibili combinazioni di paramatri di questo provider. ref.invalidate(labelProvider); // Invalida una sola specifica combinazione ref.invalidate(labelProvider('John')); } /* SNIPPET END */
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_family_example/codegen.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_family_example/codegen.dart', 'repo_id': 'riverpod', 'token_count': 196}
// ignore_for_file: omit_local_variable_types, prefer_const_constructors, unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'activity.dart'; import 'provider.dart'; /* SNIPPET START */ /// Estendiamo "ConsumerWidget" al posto di "StatelessWidget". /// Ciò è equivalente a creare uno "StatelessWidget" e ritornare un widget "Consumer". class Home extends ConsumerWidget { const Home({super.key}); @override // Si noti come il metodo "build" ora riceve un extra parametro: "ref" Widget build(BuildContext context, WidgetRef ref) { // Possiamo usare "ref.watch" dentro il nostro widget come facevamo con "Consumer" final AsyncValue<Activity> activity = ref.watch(activityProvider); // Il codice dell'interfaccia grafica rimane la stesso return Center(/* ... */); } }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/first_request/raw/consumer_widget.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/first_request/raw/consumer_widget.dart', 'repo_id': 'riverpod', 'token_count': 289}
// ignore_for_file: omit_local_variable_types, unused_local_variable, prefer_final_locals import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import '../../first_request/raw/activity.dart'; /* SNIPPET START */ // Definiamo un record che rappresenta gli argomenti che vogliamo passare al provider. // Renderlo un typedef è opzionale ma può rendere il codice più leggibile. typedef ActivityParameters = ({String type, int maxPrice}); final activityProvider = FutureProvider.autoDispose // Possiamo usare il record definito prima come tipo degli argomenti. .family<Activity, ActivityParameters>((ref, arguments) async { final response = await http.get( Uri( scheme: 'https', host: 'boredapi.com', path: '/api/activity', queryParameters: { // Infine, possiamo usare gli argomenti per aggiornare i nostri parametri di query. 'type': arguments.type, 'price': arguments.maxPrice, }, ), ); final json = jsonDecode(response.body) as Map<String, dynamic>; return Activity.fromJson(json); });
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/tuple_family.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/tuple_family.dart', 'repo_id': 'riverpod', 'token_count': 411}
// ignore_for_file: unused_local_variable import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'create_container.dart'; import 'full_widget_test.dart'; import 'provider_to_mock/raw.dart'; void main() { testWidgets('Some description', (tester) async { await tester.pumpWidget( const ProviderScope(child: YourWidgetYouWantToTest()), ); /* SNIPPET START */ // Nei test unitari, riutilizzando la nostra precedente utilità "createContainer". final container = createContainer( // Possiamo specificare una lista di provider da emulare: overrides: [ // In questo caso, stiamo imitando "exampleProvider". exampleProvider.overrideWith((ref) { // Questa funzione è la tipica funzione di inizializzazione di un provider. // Qui è dove normalmente chiamaresti "ref.watch" e restituiresti lo stato iniziale. // Sostituiamo il valore di default "Hello world" con un valore custom. // Infine, quando interagiremo con `exampleProvider`, ci ritornerà questo valore. return 'Hello from tests'; }), ], ); // Possiamo anche fare lo stesso nei test di widget usando ProviderScope: await tester.pumpWidget( ProviderScope( // I ProviderScope hanno lo stesso esatto parametro "overrides" overrides: [ // Uguale a prima exampleProvider.overrideWith((ref) => 'Hello from tests'), ], child: const YourWidgetYouWantToTest(), ), ); /* SNIPPET END */ }); }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/testing/mock_provider.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/testing/mock_provider.dart', 'repo_id': 'riverpod', 'token_count': 639}
// ignore_for_file: omit_local_variable_types, prefer_final_locals, use_key_in_widget_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'raw_usage.g.dart'; /* SNIPPET START */ @riverpod Raw<Stream<int>> rawStream(RawStreamRef ref) { // "Raw" è un typedef. Non c'è bisogno di wrappare // il valore di ritorno in un costruttore "Raw". return const Stream<int>.empty(); } class Consumer extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { // Il valore non è più convertito in AsyncValue // e lo stream creato è ritornato come tale. Stream<int> stream = ref.watch(rawStreamProvider); return StreamBuilder<int>( stream: stream, builder: (context, snapshot) { return Text('${snapshot.data}'); }, ); } }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/websockets_sync/raw_usage.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/websockets_sync/raw_usage.dart', 'repo_id': 'riverpod', 'token_count': 338}
// ignore_for_file: avoid_print /* SNIPPET START */ import 'package:riverpod/riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'main.g.dart'; // Creiamo un "provider", che conterrà un valore (qui "Hello, world"). // Utilizzando un provider, ciò ci consente di simulare/sostituire il valore esposto. @riverpod String helloWorld(HelloWorldRef ref) { return 'Hello world'; } void main() { // Questo oggetto è dove lo stato dei nostri provider sarà salvato. final container = ProviderContainer(); // Grazie a "container", possiamo leggere il nostro provider. final value = container.read(helloWorldProvider); print(value); // Hello world }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/introduction/getting_started/dart_hello_world/main.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/introduction/getting_started/dart_hello_world/main.dart', 'repo_id': 'riverpod', 'token_count': 232}
import 'dart:async'; import 'package:dio/dio.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../utils.dart'; part 'old_lifecycles.g.dart'; final repositoryProvider = Provider<_MyRepo>((ref) { return _MyRepo(); }); class _MyRepo { Future<void> update(int i, {CancelToken? token}) async {} } /* SNIPPET START */ @riverpod class MyNotifier extends _$MyNotifier { @override int build() { // Basta leggere/scrivere il codice qui, in un posto final period = ref.watch(durationProvider); final timer = Timer.periodic(period, (t) => update()); ref.onDispose(timer.cancel); return 0; } Future<void> update() async { await ref.read(repositoryProvider).update(state + 1); // `mounted` non è più necessario! state++; // This might throw. } }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles/old_lifecycles.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles/old_lifecycles.dart', 'repo_id': 'riverpod', 'token_count': 309}
import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; /* SNIPPET START */ // StateNotifier のステート(状態)はイミュータブル(不変)である必要があります。 // ここは Freezed のようなパッケージを利用してイミュータブルにしても OK です。 @immutable class Todo { const Todo({required this.id, required this.description, required this.completed}); // イミュータブルなクラスのプロパティはすべて `final` にする必要があります。 final String id; final String description; final bool completed; // Todo はイミュータブルであり、内容を直接変更できないためコピーを作る必要があります。 // これはオブジェクトの各プロパティの内容をコピーして新たな Todo を返すメソッドです。 Todo copyWith({String? id, String? description, bool? completed}) { return Todo( id: id ?? this.id, description: description ?? this.description, completed: completed ?? this.completed, ); } } // StateNotifierProvider に渡すことになる StateNotifier クラスです。 // このクラスではステートを `state` プロパティの外に公開しません。 // つまり、ステートに関しては public なゲッターやプロパティは作らないということです。 // public メソッドを通じて UI 側にステートの操作を許可します。 class TodosNotifier extends StateNotifier<List<Todo>> { // Todo リストを空のリストとして初期化します。 TodosNotifier(): super([]); // Todo の追加 void addTodo(Todo todo) { // ステート自体もイミュータブルなため、`state.add(todo)` // のような操作はできません。 // 代わりに、既存 Todo と新規 Todo を含む新しいリストを作成します。 // Dart のスプレッド演算子を使うと便利ですよ! state = [...state, todo]; // `notifyListeners` などのメソッドを呼ぶ必要はありません。 // `state =` により必要なときに UI側 に通知が届き、ウィジェットが更新されます。 } // Todo の削除 void removeTodo(String todoId) { // しつこいですが、ステートはイミュータブルです。 // そのため既存リストを変更するのではなく、新しくリストを作成する必要があります。 state = [ for (final todo in state) if (todo.id != todoId) todo, ]; } // Todo の完了ステータスの変更 void toggle(String todoId) { state = [ for (final todo in state) // ID がマッチした Todo のみ、完了ステータスを変更します。 if (todo.id == todoId) // またまたしつこいですが、ステートはイミュータブルなので // Todo クラスに実装した `copyWith` メソッドを使用して // Todo オブジェクトのコピーを作る必要があります。 todo.copyWith(completed: !todo.completed) else // ID が一致しない Todo は変更しません。 todo, ]; } } // 最後に TodosNotifier のインスタンスを値に持つ StateNotifierProvider を作成し、 // UI 側から Todo リストを操作することを可能にします。 final todosProvider = StateNotifierProvider<TodosNotifier, List<Todo>>((ref) { return TodosNotifier(); });
riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos.dart/0
{'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos.dart', 'repo_id': 'riverpod', 'token_count': 1479}
// ignore_for_file: unused_local_variable, avoid_print import 'package:flutter_test/flutter_test.dart'; import 'package:riverpod/riverpod.dart'; import 'create_container.dart'; final provider = Provider((_) => 'Hello world'); void main() { test('Some description', () { final container = createContainer(); /* SNIPPET START */ final subscription = container.listen<String>(provider, (_, __) {}); expect( // `container.read(provider)`와 동일합니다. // 그러나 "subscription"이 disposed되지 않는 한 provider는 disposed되지 않습니다. subscription.read(), 'Some value', ); /* SNIPPET END */ }); }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/auto_dispose_listen.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/auto_dispose_listen.dart', 'repo_id': 'riverpod', 'token_count': 271}
// ignore_for_file: use_key_in_widget_constructors import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; /* SNIPPET START */ // Счетчик, реализованный и протестированный с использованием Flutter // Объявляем провайдер глобально. // Используем этот провайдер в двух тестах, чтобы проверить, правильно ли // состояние сбрасывается до нуля между тестами. final counterProvider = StateProvider((ref) => 0); // Отрисовывает текущее состояние и кнопку для увеличения счетчика class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Consumer(builder: (context, ref, _) { final counter = ref.watch(counterProvider); return ElevatedButton( onPressed: () => ref.read(counterProvider.notifier).state++, child: Text('$counter'), ); }), ); } } void main() { testWidgets('update the UI when incrementing the state', (tester) async { await tester.pumpWidget(ProviderScope(child: MyApp())); // `0` - значение по умолчанию, как это было объявлено в провайдере expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Увеличение счетчика и переотрисовка await tester.tap(find.byType(ElevatedButton)); await tester.pump(); // Состояние счетчика действительно увеличилось expect(find.text('1'), findsOneWidget); expect(find.text('0'), findsNothing); }); testWidgets('the counter state is not shared between tests', (tester) async { await tester.pumpWidget(ProviderScope(child: MyApp())); // Состояние счетчика снова стало равно `0` // без использования tearDown/setUp expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); }); }
riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/cookbooks/testing_original_test_flutter.dart/0
{'file_path': 'riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/cookbooks/testing_original_test_flutter.dart', 'repo_id': 'riverpod', 'token_count': 1033}
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'todo.dart'; /* SNIPPET START */ final completedTodosProvider = Provider<List<Todo>>((ref) { // Получаем список всех задач из todosProvider final todos = ref.watch(todosProvider); // Возвращаем только выполненные задачи return todos.where((todo) => todo.isCompleted).toList(); });
riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/provider/completed_todos.dart/0
{'file_path': 'riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/provider/completed_todos.dart', 'repo_id': 'riverpod', 'token_count': 180}
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; /* SNIPPET START */ extension DebounceAndCancelExtension on Ref { /// 等待 [duration](默认为 500ms), /// 然后返回一个 [http.Client],用于发出请求。 /// /// 当提供者程序被处置时,该客户端将自动关闭。 Future<http.Client> getDebouncedHttpClient([Duration? duration]) async { // 首先,我们要处理去抖问题。 var didDispose = false; onDispose(() => didDispose = true); // 我们将请求延迟 500 毫秒,以等待用户停止刷新。 await Future<void>.delayed(duration ?? const Duration(milliseconds: 500)); // 如果在延迟期间处理了提供者程序,则意味着用户再次刷新了请求。 // 我们会抛出一个异常来取消请求。 // 在这里使用异常是安全的,因为它会被 Riverpod 捕捉到。 if (didDispose) { throw Exception('Cancelled'); } // 现在我们创建客户端,并在处理提供者程序时关闭客户端。 final client = http.Client(); onDispose(client.close); // 最后,我们返回客户端,让我们的提供者程序提出请求。 return client; } }
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/case_studies/cancel/extension.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/case_studies/cancel/extension.dart', 'repo_id': 'riverpod', 'token_count': 677}
// ignore_for_file: unused_local_variable import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'codegen.g.dart'; @riverpod int other(OtherRef ref) => 0; /* SNIPPET START */ @riverpod class Example extends _$Example { @override int build() { // "Ref" 可以在这里用来阅读其他提供者程序 final otherValue = ref.watch(otherProvider); return 0; } } /* SNIPPET END */
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/combining_requests/notifier_ref/codegen.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/combining_requests/notifier_ref/codegen.dart', 'repo_id': 'riverpod', 'token_count': 170}
// ignore_for_file: avoid_print import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../first_request/codegen/activity.dart'; // Necessary for code-generation to work part 'provider.g.dart'; FutureOr<Activity> fetchActivity() => throw UnimplementedError(); /* SNIPPET START */ // “函数型”提供者程序 @riverpod Future<Activity> activity(ActivityRef ref) async { // TODO: 执行网络请求以获取活动 return fetchActivity(); } // 或者替代方案,“通知者程序” @riverpod class ActivityNotifier2 extends _$ActivityNotifier2 { /// 通知者程序参数在构建方法上指定。 /// 可以有任意数量的通知者程序参数,可以是任意的变量名称,甚至可以是可选/命名的参数。 @override Future<Activity> build(String activityType) async { // 参数也可通过 "this.<argumentName>" 使用 print(this.activityType); // TODO: 执行网络请求以获取活动 return fetchActivity(); } }
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/codegen/provider.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/codegen/provider.dart', 'repo_id': 'riverpod', 'token_count': 461}
import 'dart:async'; import 'package:dio/dio.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../utils.dart'; final repositoryProvider = Provider<_MyRepo>((ref) { return _MyRepo(); }); class _MyRepo { Future<void> update(int i, {CancelToken? token}) async {} } /* SNIPPET START */ class MyNotifier extends Notifier<int> { @override int build() { // 只需在此处读取/写入代码,一目了然 final period = ref.watch(durationProvider); final timer = Timer.periodic(period, (t) => update()); ref.onDispose(timer.cancel); return 0; } Future<void> update() async { final cancelToken = CancelToken(); ref.onDispose(cancelToken.cancel); await ref.read(repositoryProvider).update(state + 1, token: cancelToken); // 调用 `cancelToken.cancel` 时,会抛出一个自定义异常 state++; } } final myNotifierProvider = NotifierProvider<MyNotifier, int>(MyNotifier.new);
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles_final/raw.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles_final/raw.dart', 'repo_id': 'riverpod', 'token_count': 386}
import 'package:flame/game.dart'; import 'package:flame/gestures.dart'; import 'package:flame/time.dart'; import 'package:flame/components/timer_component.dart'; import 'package:flutter/material.dart'; import './components/player_component.dart'; import './components/enemy_creator.dart'; import './components/star_background_creator.dart'; import './components/score_component.dart'; import './audio.dart'; class SpaceShooterGame extends BaseGame with PanDetector { PlayerComponent player; StarBackGroundCreator starBackGroundCreator; int score = 0; bool _musicStarted = false; SpaceShooterGame(Size size) { this.size = size; _initPlayer(); add(EnemyCreator()); add(starBackGroundCreator = StarBackGroundCreator(size)); starBackGroundCreator.init(); add(ScoreComponent()); } void _initPlayer() { add(player = PlayerComponent()); } @override void onPanStart(_) { if (!_musicStarted) { _musicStarted = true; Audio.backgroundMusic(); } player?.beginFire(); } @override void onPanEnd(_) { player?.stopFire(); } @override void onPanCancel() { player?.stopFire(); } @override void onPanUpdate(DragUpdateDetails details) { player?.move(details.delta.dx, details.delta.dy); } void increaseScore() { score++; } void playerTakeHit() { player.takeHit(); player = null; score = 0; add( TimerComponent( Timer(1, callback: _initPlayer) ..start() ) ); } }
rogue_shooter/game/lib/game.dart/0
{'file_path': 'rogue_shooter/game/lib/game.dart', 'repo_id': 'rogue_shooter', 'token_count': 582}