text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
import 'dart:math';
import 'dart:ui';
import 'package:flame/cache.dart';
import 'package:flame/extensions.dart';
import 'package:flame/widgets.dart';
import 'package:flutter/material.dart';
import 'package:io_flip_ui/gen/assets.gen.dart';
import 'package:provider/provider.dart';
/// {@template flip_countdown}
/// A widget that renders a [SpriteAnimation] for the card flip countdown.
/// {@endtemplate}
class FlipCountdown extends StatelessWidget {
/// {@macro flip_countdown}
const FlipCountdown({
super.key,
this.height = 500,
this.width = 500,
this.onComplete,
});
/// The height of the widget.
///
/// Defaults to `500`.
final double height;
/// The width of the widget.
///
/// Defaults to `500`.
final double width;
/// Optional callback to be called when the animation is complete.
final VoidCallback? onComplete;
@override
Widget build(BuildContext context) {
final platform = Theme.of(context).platform;
final isMobile =
platform == TargetPlatform.iOS || platform == TargetPlatform.android;
return SizedBox(
height: height,
width: width,
child: isMobile
? _MobileFlipCountdown(
key: const Key('flipCountdown_mobile'),
onComplete: onComplete,
)
: _DesktopFlipCountdown(
onComplete: onComplete,
),
);
}
}
class _MobileFlipCountdown extends StatefulWidget {
const _MobileFlipCountdown({required this.onComplete, super.key});
final VoidCallback? onComplete;
@override
State<_MobileFlipCountdown> createState() => _MobileFlipCountdownState();
}
class _MobileFlipCountdownState extends State<_MobileFlipCountdown>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
final threePhase = CurveTween(
curve: const Interval(0, 1 / 4, curve: Curves.easeOutBack),
);
final twoPhase = CurveTween(
curve: const Interval(1 / 4, 2 / 4, curve: Curves.easeOutBack),
);
final onePhase = CurveTween(
curve: const Interval(2 / 4, 3 / 4, curve: Curves.easeOutBack),
);
final flipPhase = CurveTween(
curve: const Interval(3 / 4, 1, curve: Curves.easeOutBack),
);
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
widget.onComplete?.call();
}
})
..forward(from: 0);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final t3 = threePhase.evaluate(_controller);
final t2 = twoPhase.evaluate(_controller);
final t1 = onePhase.evaluate(_controller);
final tFlip = flipPhase.evaluate(_controller);
return Stack(
alignment: Alignment.center,
children: [
Offstage(
offstage: _controller.value > 1 / 4,
child: _MobileFlipCountdownPhase(
t: t3,
image: Assets.images.flipCountdown.mobile.flipCountdown3
.image(width: 200),
),
),
Offstage(
offstage: _controller.value <= 1 / 4 || _controller.value > 2 / 4,
child: _MobileFlipCountdownPhase(
t: t2,
image: Assets.images.flipCountdown.mobile.flipCountdown2
.image(width: 200),
),
),
Offstage(
offstage: _controller.value <= 2 / 4 || _controller.value > 3 / 4,
child: _MobileFlipCountdownPhase(
t: t1,
image: Assets.images.flipCountdown.mobile.flipCountdown1
.image(width: 200),
),
),
Offstage(
offstage: _controller.value <= 3 / 4 || _controller.value == 1,
child: _MobileFlipCountdownPhase(
t: tFlip,
image: Assets.images.flipCountdown.mobile.flipCountdownFlip
.image(width: 500),
),
),
],
);
},
);
}
}
class _MobileFlipCountdownPhase extends StatelessWidget {
const _MobileFlipCountdownPhase({
required this.t,
required this.image,
});
final double t;
final Widget image;
@override
Widget build(BuildContext context) {
return Transform(
alignment: Alignment.center,
transform: Matrix4.identity()
..rotateZ(lerpDouble(-pi / 12, 0, t)!)
..scale(lerpDouble(0.75, 1, t)),
child: image,
);
}
}
class _DesktopFlipCountdown extends StatefulWidget {
const _DesktopFlipCountdown({required this.onComplete});
final VoidCallback? onComplete;
@override
State<_DesktopFlipCountdown> createState() => _DesktopFlipCountdownState();
}
class _DesktopFlipCountdownState extends State<_DesktopFlipCountdown> {
late final ValueNotifier<SpriteAnimationWidget> _animationNotifier;
@override
void initState() {
super.initState();
_createAnimationWidget();
}
void _createAnimationWidget() {
final images = context.read<Images>();
_animationNotifier = ValueNotifier<SpriteAnimationWidget>(
SpriteAnimationWidget.asset(
path: Assets.images.flipCountdown.desktop.flipCountdown.keyName,
images: images,
anchor: Anchor.center,
onComplete: widget.onComplete,
data: SpriteAnimationData.sequenced(
amount: 60,
amountPerRow: 6,
textureSize: Vector2(1100, 750),
stepTime: 0.04,
loop: false,
),
),
);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<SpriteAnimationWidget>(
valueListenable: _animationNotifier,
builder: (_, animation, __) => animation,
);
}
}
| io_flip/packages/io_flip_ui/lib/src/widgets/flip_countdown.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/flip_countdown.dart",
"repo_id": "io_flip",
"token_count": 2551
} | 854 |
#version 300 es
#extension GL_EXT_shader_non_constant_global_initializers:enable
precision highp float;
const float STRENGTH = 0.4; // 0.0 = no effect, 1.0 = full effect
const float SATURATION = 0.9; // Color saturation (0.0 = grayscale, 1.0 = full color)
const float LIGHTNESS = 0.65; // Color lightness (0.0 = black, 1.0 = white)
uniform vec2 resolution; // Size of the canvas
uniform vec2 offset; // Additional offset of the effect
uniform sampler2D tSource; // Input texture (the application canvas)
out vec4 fragColor;
vec4 rainbowEffect(vec2 uv) {
vec4 srcColor = texture(tSource, uv);
float hue = uv.x / (1.75 + abs(offset.x)) + offset.x / 3.0;
float lightness = LIGHTNESS + 0.25 * (0.5 + offset.y * (0.5 - uv.y));
hue = fract(hue);
float c = (1.0 - abs(2.0 * lightness - 1.0)) * SATURATION;
float x = c * (1.0 - abs(mod(hue / (1.0 / 6.0), 2.0) - 1.0));
float m = LIGHTNESS - c / 2.0;
vec3 rainbowPrime;
if (hue < 1.0 / 6.0) {
rainbowPrime = vec3(c, x, 0.0);
} else if (hue < 1.0 / 3.0) {
rainbowPrime = vec3(x, c, 0.0);
} else if (hue < 0.5) {
rainbowPrime = vec3(0.0, c, x);
} else if (hue < 2.0 / 3.0) {
rainbowPrime = vec3(0.0, x, c);
} else if (hue < 5.0 / 6.0) {
rainbowPrime = vec3(x, 0.0, c);
} else {
rainbowPrime = vec3(c, 0.0, x);
}
vec3 rainbow = rainbowPrime + m;
return mix(srcColor, vec4(rainbow, srcColor.a), STRENGTH);
}
vec4 chromaticAberration(vec2 uv) {
vec4 srcColor = rainbowEffect(uv);
vec2 shift = offset * vec2(3.0, 5.0) / 1000.0;
vec4 leftColor = rainbowEffect(uv - shift);
vec4 rightColor = rainbowEffect(uv + shift);
return vec4(rightColor.r, srcColor.g, leftColor.b, srcColor.a);
}
void main() {
vec2 pos = gl_FragCoord.xy;
vec2 uv = pos / resolution;
fragColor = chromaticAberration(uv);
}
| io_flip/packages/io_flip_ui/shaders/foil.frag/0 | {
"file_path": "io_flip/packages/io_flip_ui/shaders/foil.frag",
"repo_id": "io_flip",
"token_count": 826
} | 855 |
import 'package:flame/cache.dart';
import 'package:flame/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:mocktail/mocktail.dart';
import 'package:provider/provider.dart';
class _MockImages extends Mock implements Images {}
void main() {
group('VictoryChargeBack', () {
late Images images;
setUp(() {
images = _MockImages();
});
testWidgets('renders SpriteAnimationWidget', (tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Provider.value(
value: images,
child: const VictoryChargeBack(
'',
assetSize: AssetSize.large,
size: GameCardSize.md(),
animationColor: Colors.white,
),
),
),
);
expect(find.byType(SpriteAnimationWidget), findsOneWidget);
});
});
}
| io_flip/packages/io_flip_ui/test/src/widgets/damages/victory_charge_back_test.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/test/src/widgets/damages/victory_charge_back_test.dart",
"repo_id": "io_flip",
"token_count": 443
} | 856 |
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip_ui/gen/assets.gen.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
void main() {
group('SuitIcons', () {
test('use their corresponding asset', () {
expect(
SuitIcon.fire().asset,
equals(Assets.images.suits.onboarding.fire),
);
expect(
SuitIcon.air().asset,
equals(Assets.images.suits.onboarding.air),
);
expect(
SuitIcon.metal().asset,
equals(Assets.images.suits.onboarding.metal),
);
expect(
SuitIcon.earth().asset,
equals(Assets.images.suits.onboarding.earth),
);
expect(
SuitIcon.water().asset,
equals(Assets.images.suits.onboarding.water),
);
});
testWidgets('renders size correctly', (tester) async {
await tester.pumpWidget(SuitIcon.fire(scale: 2));
expect(
tester.widget(find.byType(SuitIcon)),
isA<SuitIcon>().having((i) => i.size, 'size', 192),
);
});
});
}
| io_flip/packages/io_flip_ui/test/src/widgets/suit_icons_test.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/test/src/widgets/suit_icons_test.dart",
"repo_id": "io_flip",
"token_count": 482
} | 857 |
#!/bin/bash
ENCRYPTION_KEY=$1
ENCRYPTION_IV=$2
RECAPTCHA_KEY=$3
flutter build web \
-t lib/main_production.dart \
--web-renderer canvaskit \
--dart-define SHARING_ENABLED=true \
--dart-define ENCRYPTION_KEY=$ENCRYPTION_KEY \
--dart-define ENCRYPTION_IV=$ENCRYPTION_IV \
--dart-define RECAPTCHA_KEY=$RECAPTCHA_KEY \
--dart-define ALLOW_PRIVATE_MATCHES=false
| io_flip/scripts/build_production_game.sh/0 | {
"file_path": "io_flip/scripts/build_production_game.sh",
"repo_id": "io_flip",
"token_count": 169
} | 858 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:io_flip/draft/draft.dart';
void main() {
group('DeckRequested', () {
test('can be instantiated', () {
expect(
DeckRequested(Prompt()),
isNotNull,
);
});
test('supports equality', () {
expect(
DeckRequested(Prompt()),
equals(DeckRequested(Prompt())),
);
});
});
group('PreviousCard', () {
test('can be instantiated', () {
expect(
PreviousCard(),
isNotNull,
);
});
test('supports equality', () {
expect(
PreviousCard(),
equals(PreviousCard()),
);
});
});
group('NextCard', () {
test('can be instantiated', () {
expect(
NextCard(),
isNotNull,
);
});
test('supports equality', () {
expect(
NextCard(),
equals(NextCard()),
);
});
});
group('CardSwiped', () {
test('can be instantiated', () {
expect(
CardSwiped(),
isNotNull,
);
});
test('supports equality', () {
expect(
CardSwiped(),
equals(CardSwiped()),
);
});
});
group('CardSwipeStarted', () {
test('can be instantiated', () {
expect(
CardSwipeStarted(0),
isNotNull,
);
});
test('supports equality', () {
expect(
CardSwipeStarted(.8),
equals(CardSwipeStarted(.8)),
);
expect(
CardSwipeStarted(.8),
isNot(equals(CardSwipeStarted(.9))),
);
});
});
group('SelectCard', () {
test('can be instantiated', () {
expect(
SelectCard(0),
isNotNull,
);
});
test('supports equality', () {
expect(
SelectCard(0),
equals(SelectCard(0)),
);
expect(
SelectCard(0),
isNot(equals(SelectCard(1))),
);
});
});
group('PlayerDeckRequested', () {
test('can be instantiated', () {
expect(
PlayerDeckRequested(const ['id1', 'id2', 'id3']),
isNotNull,
);
});
test('supports equality', () {
expect(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
createPrivateMatch: true,
privateMatchInviteCode: 'code',
),
equals(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
createPrivateMatch: true,
privateMatchInviteCode: 'code',
),
),
);
expect(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
createPrivateMatch: true,
privateMatchInviteCode: 'code',
),
isNot(
equals(
PlayerDeckRequested(
const ['id1', 'id2', 'id4'],
createPrivateMatch: true,
privateMatchInviteCode: 'code',
),
),
),
);
expect(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
),
isNot(
equals(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
createPrivateMatch: true,
),
),
),
);
expect(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
),
isNot(
equals(
PlayerDeckRequested(
const ['id1', 'id2', 'id3'],
privateMatchInviteCode: 'code',
),
),
),
);
});
});
}
| io_flip/test/draft/bloc/draft_event_test.dart/0 | {
"file_path": "io_flip/test/draft/bloc/draft_event_test.dart",
"repo_id": "io_flip",
"token_count": 1899
} | 859 |
import 'package:api_client/api_client.dart';
import 'package:authentication_repository/authentication_repository.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:config_repository/config_repository.dart';
import 'package:connection_repository/connection_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flame/cache.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:game_script_machine/game_script_machine.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/audio/audio_controller.dart';
import 'package:io_flip/l10n/l10n.dart';
import 'package:io_flip/settings/settings.dart';
import 'package:io_flip/style/snack_bar.dart';
import 'package:io_flip/terms_of_use/terms_of_use.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:match_maker_repository/match_maker_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:provider/provider.dart';
import 'helpers.dart';
class _MockSettingsController extends Mock implements SettingsController {}
class _MockGameResource extends Mock implements GameResource {}
class _MockShareResource extends Mock implements ShareResource {}
class _MockPromptResource extends Mock implements PromptResource {}
class _MockScriptsResource extends Mock implements ScriptsResource {}
class _MockLeaderboardResource extends Mock implements LeaderboardResource {}
class _MockMatchMakerRepository extends Mock implements MatchMakerRepository {}
class _MockConfigRepository extends Mock implements ConfigRepository {}
class _MockConnectionRepository extends Mock implements ConnectionRepository {}
class _MockMatchSolver extends Mock implements MatchSolver {}
class _MockGameScriptMachine extends Mock implements GameScriptMachine {}
class _MockAudioController extends Mock implements AudioController {}
class _MockUser extends Mock implements User {}
class _MockUISoundAdapter extends Mock implements UISoundAdapter {}
class _MockGoRouter extends Mock implements GoRouter {}
class _MockImages extends Mock implements Images {}
class _MockTermsOfUseCubit extends MockCubit<bool> implements TermsOfUseCubit {}
UISoundAdapter _createUISoundAdapter() {
final adapter = _MockUISoundAdapter();
when(() => adapter.playButtonSound).thenReturn(() {});
return adapter;
}
extension PumpApp on WidgetTester {
Future<void> pumpApp(
Widget widget, {
SettingsController? settingsController,
GameResource? gameResource,
ShareResource? shareResource,
ScriptsResource? scriptsResource,
PromptResource? promptResource,
LeaderboardResource? leaderboardResource,
MatchMakerRepository? matchMakerRepository,
ConfigRepository? configRepository,
AudioController? audioController,
ConnectionRepository? connectionRepository,
MatchSolver? matchSolver,
GameScriptMachine? gameScriptMachine,
UISoundAdapter? uiSoundAdapter,
User? user,
GoRouter? router,
Images? images,
}) {
return pumpWidget(
MultiProvider(
providers: [
Provider.value(
value: settingsController ?? _MockSettingsController(),
),
Provider.value(
value: gameResource ?? _MockGameResource(),
),
Provider.value(
value: shareResource ?? _MockShareResource(),
),
Provider.value(
value: scriptsResource ?? _MockScriptsResource(),
),
Provider.value(
value: promptResource ?? _MockPromptResource(),
),
Provider.value(
value: leaderboardResource ?? _MockLeaderboardResource(),
),
Provider.value(
value: matchMakerRepository ?? _MockMatchMakerRepository(),
),
Provider.value(
value: configRepository ?? _MockConfigRepository(),
),
Provider.value(
value: audioController ?? _MockAudioController(),
),
Provider.value(
value: connectionRepository ?? _MockConnectionRepository(),
),
Provider.value(
value: matchSolver ?? _MockMatchSolver(),
),
Provider.value(
value: uiSoundAdapter ?? _createUISoundAdapter(),
),
Provider.value(
value: gameScriptMachine ?? _MockGameScriptMachine(),
),
Provider.value(
value: user ?? _MockUser(),
),
Provider.value(
value: images ?? _MockImages(),
)
],
child: MockGoRouterProvider(
goRouter: router ?? _MockGoRouter(),
child: MaterialApp(
scaffoldMessengerKey: scaffoldMessengerKey,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: widget,
),
),
),
);
}
}
extension PumpAppWithRouter on WidgetTester {
Future<void> pumpAppWithRouter<T extends Bloc<Equatable, Equatable>>(
GoRouter router, {
SettingsController? settingsController,
GameResource? gameResource,
ShareResource? shareResource,
ScriptsResource? scriptsResource,
PromptResource? promptResource,
LeaderboardResource? leaderboardResource,
MatchMakerRepository? matchMakerRepository,
ConfigRepository? configRepository,
AudioController? audioController,
ConnectionRepository? connectionRepository,
MatchSolver? matchSolver,
GameScriptMachine? gameScriptMachine,
UISoundAdapter? uiSoundAdapter,
User? user,
Images? images,
T? bloc,
TermsOfUseCubit? termsOfUseCubit,
}) {
return pumpWidget(
MultiProvider(
providers: [
Provider.value(
value: settingsController ?? _MockSettingsController(),
),
Provider.value(
value: gameResource ?? _MockGameResource(),
),
Provider.value(
value: shareResource ?? _MockShareResource(),
),
Provider.value(
value: scriptsResource ?? _MockScriptsResource(),
),
Provider.value(
value: promptResource ?? _MockPromptResource(),
),
Provider.value(
value: leaderboardResource ?? _MockLeaderboardResource(),
),
Provider.value(
value: matchMakerRepository ?? _MockMatchMakerRepository(),
),
Provider.value(
value: configRepository ?? _MockConfigRepository(),
),
Provider.value(
value: audioController ?? _MockAudioController(),
),
Provider.value(
value: connectionRepository ?? _MockConnectionRepository(),
),
Provider.value(
value: matchSolver ?? _MockMatchSolver(),
),
Provider.value(
value: uiSoundAdapter ?? _createUISoundAdapter(),
),
Provider.value(
value: gameScriptMachine ?? _MockGameScriptMachine(),
),
Provider.value(
value: user ?? _MockUser(),
),
Provider.value(
value: images ?? _MockImages(),
)
],
child: MultiBlocProvider(
providers: [
if (bloc != null) BlocProvider<T>.value(value: bloc),
BlocProvider<TermsOfUseCubit>.value(
value: termsOfUseCubit ?? _MockTermsOfUseCubit(),
),
],
child: MaterialApp.router(
scaffoldMessengerKey: scaffoldMessengerKey,
routeInformationProvider: router.routeInformationProvider,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
),
),
),
);
}
}
| io_flip/test/helpers/pump_app.dart/0 | {
"file_path": "io_flip/test/helpers/pump_app.dart",
"repo_id": "io_flip",
"token_count": 3248
} | 860 |
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/leaderboard/initials_form/initials_form.dart';
void main() {
group('InitialsFormState', () {
group('copyWith', () {
test('does not update omitted params', () {
const state = InitialsFormState(initials: ['A', 'B', 'C']);
expect(state.copyWith(), equals(state));
});
});
});
}
| io_flip/test/leaderboard/initials_form/bloc/initials_form_state_test.dart/0 | {
"file_path": "io_flip/test/leaderboard/initials_form/bloc/initials_form_state_test.dart",
"repo_id": "io_flip",
"token_count": 153
} | 861 |
import 'package:api_client/api_client.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:io_flip/prompt/prompt.dart';
import 'package:mocktail/mocktail.dart';
import 'package:provider/provider.dart';
import '../../helpers/helpers.dart';
class _MockPromptResource extends Mock implements PromptResource {}
void main() {
late PromptResource promptResource;
setUpAll(() {
registerFallbackValue(PromptTermType.characterClass);
});
setUp(() {
promptResource = _MockPromptResource();
when(() => promptResource.getPromptTerms(any()))
.thenAnswer((_) => Future.value(['']));
});
group('PromptPage', () {
testWidgets('renders prompt page', (tester) async {
await tester.pumpSubject(promptResource);
expect(find.byType(PromptView), findsOneWidget);
});
});
}
extension PromptPageTest on WidgetTester {
Future<void> pumpSubject(PromptResource resource) {
return pumpApp(
Provider.value(
value: resource,
child: const PromptPage(),
),
);
}
}
| io_flip/test/prompt/view/prompt_page_test.dart/0 | {
"file_path": "io_flip/test/prompt/view/prompt_page_test.dart",
"repo_id": "io_flip",
"token_count": 405
} | 862 |
import 'package:api_client/api_client.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/audio/widgets/widgets.dart';
import 'package:io_flip/info/info.dart';
import 'package:io_flip/settings/settings.dart';
import 'package:io_flip/share/views/views.dart';
import 'package:io_flip/share/widgets/widgets.dart';
import 'package:io_flip/utils/utils.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:mocktail/mocktail.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../../helpers/helpers.dart';
class _MockGoRouterState extends Mock implements GoRouterState {}
class _MockSettingsController extends Mock implements SettingsController {}
class _MockGoRouter extends Mock implements GoRouter {}
class _MockShareResource extends Mock implements ShareResource {}
class _MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
class _FakeLaunchOptions extends Fake implements LaunchOptions {}
const card = Card(
id: '',
name: 'name',
description: 'description',
image: '',
rarity: false,
power: 1,
suit: Suit.air,
);
const pageData = ShareHandPageData(
initials: 'AAA',
wins: 0,
deck: Deck(id: '', userId: '', cards: []),
);
void main() {
late GoRouterState goRouterState;
late UrlLauncherPlatform urlLauncher;
setUp(() {
goRouterState = _MockGoRouterState();
when(() => goRouterState.extra).thenReturn(pageData);
when(() => goRouterState.queryParams).thenReturn({});
urlLauncher = _MockUrlLauncher();
when(
() => urlLauncher.canLaunch(any()),
).thenAnswer((_) async => true);
when(
() => urlLauncher.launchUrl(any(), any()),
).thenAnswer((_) async => true);
UrlLauncherPlatform.instance = urlLauncher;
});
setUpAll(() {
registerFallbackValue(_FakeLaunchOptions());
});
group('ShareHandPage', () {
test('routeBuilder returns a ShareHandPage', () {
expect(
ShareHandPage.routeBuilder(null, goRouterState),
isA<ShareHandPage>()
.having((page) => page.deck, 'deck', pageData.deck)
.having((page) => page.wins, 'wins', pageData.wins)
.having((page) => page.initials, 'initials', pageData.initials),
);
});
testWidgets('renders', (tester) async {
await tester.pumpSubject();
expect(find.byType(ShareHandPage), findsOneWidget);
});
testWidgets('renders a IoFlipLogo widget', (tester) async {
await tester.pumpSubject();
expect(find.byType(IoFlipLogo), findsOneWidget);
});
testWidgets('renders a CardFan widget', (tester) async {
await tester.pumpSubject();
expect(find.byType(CardFan), findsOneWidget);
});
testWidgets('renders the users wins and initials', (tester) async {
await tester.pumpSubject();
expect(find.text('5 ${tester.l10n.winStreakLabel}'), findsOneWidget);
expect(find.text('AAA'), findsOneWidget);
});
testWidgets('renders the title', (tester) async {
await tester.pumpSubject();
expect(find.text(tester.l10n.shareTeamTitle), findsOneWidget);
});
testWidgets('renders a menu button', (tester) async {
await tester.pumpSubject();
expect(find.text(tester.l10n.mainMenuButtonLabel), findsOneWidget);
});
testWidgets('renders a routes to main menu on button tapped',
(tester) async {
final goRouter = _MockGoRouter();
when(() => goRouter.go('/')).thenAnswer((_) {});
await tester.pumpSubject(
router: goRouter,
);
await tester.tap(find.text(tester.l10n.mainMenuButtonLabel));
verify(() => goRouter.go('/')).called(1);
});
testWidgets('renders a share button', (tester) async {
await tester.pumpSubject();
expect(find.text(tester.l10n.shareButtonLabel), findsOneWidget);
});
testWidgets('renders a dialog on share button tapped', (tester) async {
final shareResource = _MockShareResource();
when(() => shareResource.facebookShareHandUrl(any())).thenReturn('');
when(() => shareResource.twitterShareHandUrl(any())).thenReturn('');
await tester.pumpSubject(
shareResource: shareResource,
);
await tester.tap(find.text(tester.l10n.shareButtonLabel));
await tester.pumpAndSettle();
expect(find.byType(ShareHandDialog), findsOneWidget);
});
testWidgets('renders a music button', (tester) async {
await tester.pumpSubject();
expect(find.byType(AudioToggleButton), findsOneWidget);
});
testWidgets('renders a dialog on info button tapped', (tester) async {
final shareResource = _MockShareResource();
when(() => shareResource.facebookShareHandUrl(any())).thenReturn('');
when(() => shareResource.twitterShareHandUrl(any())).thenReturn('');
await tester.pumpSubject(
shareResource: shareResource,
);
await tester.tap(find.byKey(const Key('share_page_info_button')));
await tester.pumpAndSettle();
expect(find.byType(InfoView), findsOneWidget);
});
testWidgets('tapping io link opens io', (tester) async {
await tester.pumpSubject();
await tester.tap(find.text(tester.l10n.ioLinkLabel));
verify(
() => urlLauncher.launchUrl(ExternalLinks.googleIO, any()),
).called(1);
});
testWidgets('tapping how its made link opens how its made', (tester) async {
await tester.pumpSubject();
await tester.tap(find.text(tester.l10n.howItsMadeLinkLabel));
verify(
() => urlLauncher.launchUrl(ExternalLinks.howItsMade, any()),
).called(1);
});
});
}
extension ShareCardDialogTest on WidgetTester {
Future<void> pumpSubject({
ShareResource? shareResource,
GoRouter? router,
}) async {
final SettingsController settingsController = _MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
await mockNetworkImages(() {
return pumpApp(
const ShareHandPage(
wins: 5,
initials: 'AAA',
deck: Deck(id: '', userId: '', cards: [card, card, card]),
),
shareResource: shareResource,
router: router,
settingsController: settingsController,
);
});
}
}
| io_flip/test/share/views/share_hand_page_test.dart/0 | {
"file_path": "io_flip/test/share/views/share_hand_page_test.dart",
"repo_id": "io_flip",
"token_count": 2527
} | 863 |
---
sidebar_position: 5
description: Learn how to configure analytics in your Flutter news application.
---
# Analytics
Google Analytics is an app measurement solution, available at no charge, that provides insight on app usage and user engagement.
This project uses the `firebase_analytics` package to track user activity within the app. To use `firebase_analytics`, you must have a Firebase project setup correctly. For instructions on how to add Firebase to your flutter app, check out [Add Firebase to your Flutter app](https://firebase.google.com/docs/flutter/setup).
The [AnalyticsRepository](https://github.com/flutter/news_toolkit/blob/main/flutter_news_example/packages/analytics_repository/lib/src/analytics_repository.dart#L38) handles event tracking and can be accessed globally within the app using `BuildContext`:
```dart
class AnalyticsRepository {
const AnalyticsRepository(FirebaseAnalytics analytics)
: _analytics = analytics;
final FirebaseAnalytics _analytics;
/// Tracks the provided [AnalyticsEvent].
Future<void> track(AnalyticsEvent event) async {
try {
await _analytics.logEvent(
name: event.name,
parameters: event.properties,
);
} catch (error, stackTrace) {
Error.throwWithStackTrace(TrackEventFailure(error), stackTrace);
}
}
...
```
| news_toolkit/docs/docs/flutter_development/analytics.md/0 | {
"file_path": "news_toolkit/docs/docs/flutter_development/analytics.md",
"repo_id": "news_toolkit",
"token_count": 398
} | 864 |
---
sidebar_position: 2
description: Learn how to configure your Firebase project.
---
# Firebase setup
You must specify Firebase configuration information for your app flavors and platforms. Please use the following instructions to create your own Firebase projects and configure your apps.
:::note
Although the Flutter News Toolkit is pre-configured to work with Firebase, you're welcome to customize your codebase to leverage other services in your project.
:::
We recommend that you define at least two application environments (also known as flavors): _development_ and _production_. Each environment defines a different configuration of deep links, ads, and authentication, along with a different entry point to the application (such as `main_development.dart`).
By default, your codebase should support a production and development flavor. However, you might have created additional flavors when generating your project from mason.
Before you can run your generated app, you must configure Firebase.
:::note
The [flutterfire-cli](https://firebase.google.com/docs/flutter/setup#configure-firebase) doesn't yet [support multiple flavors](https://github.com/invertase/flutterfire_cli/issues/14).
Since your project supports multiple flavors, you must manually configure Firebase.
:::
Go to the [Firebase Console](https://console.firebase.google.com), sign in with your Google account, and create a separate Firebase project for each flavor that your project supports (such as development and production).
In each Firebase project, create an Android and iOS app with the corresponding application IDs. Make sure that the application ID includes the correct suffix (such as "dev" for the development flavor).
Download the Google Services file for each app from the **Project Settings** page in the Firebase Console. Then, go to the source code of your generated app and look for the following `TODOs` for each flavor:
**Android**
```
// Replace with google-services.json from the Firebase Console //
```
**iOS**
```
<!-- Replace with GoogleService-Info.plist from the Firebase Console -->
```
Replace this message (for every flavor of the app) with the contents of the `google-services.json` and `GoogleServiceInfo.plist` files that you just downloaded from the Firebase Console.
Lastly, for iOS only, you must open `ios/Runner.xcodeproj/project.pbxproj` and replace the following placeholder with the corresponding `reversed_client_id` from the `GoogleServiceInfo.plist` file:
```
REVERSED_CLIENT_ID = "<PASTE-REVERSED-CLIENT-ID-HERE>";
```
When searching for this placeholder, the number of results depend on the number of flavors configured for your project. For each configured flavor, there are two configuration sections (`debug` and `release`).
For example, if you set up `development` and `production` as your project's flavors, you will find the following configuration sections:
- **Debug-development** (build development flavor in debug mode)
- **Release-development** (build development flavor in release mode)
- **Debug-production** (build production flavor in debug mode)
- **Release-production** (build production flavor in release mode)
Your `ios/Runner.xcodeproj/project.pbxproj` should have the following format:
```bash
/* Begin XCBuildConfiguration section */
# Release-production
0CMNTMSTYJKWAP508TXPJJN5 /* Release-production */ = {
...
buildSettings = {
...
REVERSED_CLIENT_ID = "<PASTE-REVERSED-CLIENT-ID-HERE>";
...
};
name = "Release-production";
};
...
# Debug-development
1ON144SZQH163C0TE8AP2QLM /* Debug-development */ = {
...
buildSettings = {
...
REVERSED_CLIENT_ID = "<PASTE-REVERSED-CLIENT-ID-HERE>";
...
};
name = "Debug-development";
};
...
# Release-development
53ZSJWL4HHR1DK5C45O2YEZ5 /* Release-development */ = {
...
buildSettings = {
...
REVERSED_CLIENT_ID = "<PASTE-REVERSED-CLIENT-ID-HERE>";
...
};
name = "Release-development";
};
...
# Debug-production
HLDEZL79XQNUTPT4UM4UEEL7 /* Debug-production */ = {
...
buildSettings = {
...
REVERSED_CLIENT_ID = "<PASTE-REVERSED-CLIENT-ID-HERE>";
...
};
name = "Debug-production";
};
...
/* End XCBuildConfiguration section */
```
If your `GoogleServiceInfo.plist` for the development flavor looks like:
```
<plist version="1.0">
<dict>
...
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.737894073936-ccvknt0jpr1nk3uhftg14k8duirosg9t</string>
...
</dict>
</plist>
```
then in `ios/Runner.xcodeproj/project.pbxproj` you must replace the `reversed_client_id` inside the **Debug-development** and **Release-development** configuration sections.
This process must also be repeated with the `GoogleServiceInfo.plist` of the other existing flavors on your app (such as _production_), inside the respective configuration sections of the `project.pbxproj` file.
| news_toolkit/docs/docs/project_configuration/firebase.md/0 | {
"file_path": "news_toolkit/docs/docs/project_configuration/firebase.md",
"repo_id": "news_toolkit",
"token_count": 1475
} | 865 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="gallery" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/packages/app_ui/gallery/lib/main.dart" />
<method v="2" />
</configuration>
</component> | news_toolkit/flutter_news_example/.idea/runConfigurations/gallery.xml/0 | {
"file_path": "news_toolkit/flutter_news_example/.idea/runConfigurations/gallery.xml",
"repo_id": "news_toolkit",
"token_count": 93
} | 866 |
export 'package:news_blocks/news_blocks.dart' show Category;
export 'article.dart';
export 'feed.dart';
export 'news_item.dart';
export 'related_articles.dart';
export 'subscription.dart';
export 'user.dart';
| news_toolkit/flutter_news_example/api/lib/src/data/models/models.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/data/models/models.dart",
"repo_id": "news_toolkit",
"token_count": 72
} | 867 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'categories_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CategoriesResponse _$CategoriesResponseFromJson(Map<String, dynamic> json) =>
CategoriesResponse(
categories: (json['categories'] as List<dynamic>)
.map((e) => $enumDecode(_$CategoryEnumMap, e))
.toList(),
);
Map<String, dynamic> _$CategoriesResponseToJson(CategoriesResponse instance) =>
<String, dynamic>{
'categories':
instance.categories.map((e) => _$CategoryEnumMap[e]!).toList(),
};
const _$CategoryEnumMap = {
Category.business: 'business',
Category.entertainment: 'entertainment',
Category.top: 'top',
Category.health: 'health',
Category.science: 'science',
Category.sports: 'sports',
Category.technology: 'technology',
};
| news_toolkit/flutter_news_example/api/lib/src/models/categories_response/categories_response.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/models/categories_response/categories_response.g.dart",
"repo_id": "news_toolkit",
"token_count": 308
} | 868 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/api/packages/news_blocks/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 869 |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: cast_nullable_to_non_nullable, implicit_dynamic_parameter, lines_longer_than_80_chars, prefer_const_constructors, require_trailing_commas
part of 'image_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ImageBlock _$ImageBlockFromJson(Map<String, dynamic> json) => $checkedCreate(
'ImageBlock',
json,
($checkedConvert) {
final val = ImageBlock(
imageUrl: $checkedConvert('image_url', (v) => v as String),
type: $checkedConvert(
'type', (v) => v as String? ?? ImageBlock.identifier),
);
return val;
},
fieldKeyMap: const {'imageUrl': 'image_url'},
);
Map<String, dynamic> _$ImageBlockToJson(ImageBlock instance) =>
<String, dynamic>{
'image_url': instance.imageUrl,
'type': instance.type,
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/image_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/image_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 370
} | 870 |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: cast_nullable_to_non_nullable, implicit_dynamic_parameter, lines_longer_than_80_chars, prefer_const_constructors, require_trailing_commas
part of 'text_lead_paragraph_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
TextLeadParagraphBlock _$TextLeadParagraphBlockFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'TextLeadParagraphBlock',
json,
($checkedConvert) {
final val = TextLeadParagraphBlock(
text: $checkedConvert('text', (v) => v as String),
type: $checkedConvert(
'type', (v) => v as String? ?? TextLeadParagraphBlock.identifier),
);
return val;
},
);
Map<String, dynamic> _$TextLeadParagraphBlockToJson(
TextLeadParagraphBlock instance) =>
<String, dynamic>{
'text': instance.text,
'type': instance.type,
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_lead_paragraph_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_lead_paragraph_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 387
} | 871 |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('Category', () {
group('fromString', () {
test('returns business', () {
expect(
Category.fromString('business'),
equals(Category.business),
);
});
test('returns business', () {
expect(
Category.fromString('entertainment'),
equals(Category.entertainment),
);
});
test('returns top', () {
expect(
Category.fromString('top'),
equals(Category.top),
);
});
test('returns health', () {
expect(
Category.fromString('health'),
equals(Category.health),
);
});
test('returns science', () {
expect(
Category.fromString('science'),
equals(Category.science),
);
});
test('returns sports', () {
expect(
Category.fromString('sports'),
equals(Category.sports),
);
});
test('returns technology', () {
expect(
Category.fromString('technology'),
equals(Category.technology),
);
});
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/category_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/category_test.dart",
"repo_id": "news_toolkit",
"token_count": 578
} | 872 |
// ignore_for_file: prefer_const_constructors
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('SlideshowIntroductionBlock', () {
test('can be (de)serialized', () {
final block = SlideshowIntroductionBlock(
title: 'title',
coverImageUrl: 'coverImageUrl',
);
expect(
SlideshowIntroductionBlock.fromJson(block.toJson()),
equals(block),
);
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slideshow_introduction_block_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/slideshow_introduction_block_test.dart",
"repo_id": "news_toolkit",
"token_count": 187
} | 873 |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
Future<Response> onRequest(RequestContext context) async {
if (context.request.method != HttpMethod.get) {
return Response(statusCode: HttpStatus.methodNotAllowed);
}
final queryParams = context.request.url.queryParameters;
final categoryQueryParam = queryParams['category'];
final category = Category.values.firstWhere(
(category) => category.name == categoryQueryParam,
orElse: () => Category.top,
);
final limit = int.tryParse(queryParams['limit'] ?? '') ?? 20;
final offset = int.tryParse(queryParams['offset'] ?? '') ?? 0;
final feed = await context
.read<NewsDataSource>()
.getFeed(category: category, limit: limit, offset: offset);
final response = FeedResponse(
feed: feed.blocks,
totalCount: feed.totalBlocks,
);
return Response.json(body: response);
}
| news_toolkit/flutter_news_example/api/routes/api/v1/feed/index.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/routes/api/v1/feed/index.dart",
"repo_id": "news_toolkit",
"token_count": 309
} | 874 |
// ignore_for_file: prefer_const_constructors
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../../routes/api/v1/subscriptions/index.dart' as route;
class _MockRequestContext extends Mock implements RequestContext {}
class _MockNewsDataSource extends Mock implements NewsDataSource {}
class _MockRequestUser extends Mock implements RequestUser {}
void main() {
late NewsDataSource newsDataSource;
setUp(() {
newsDataSource = _MockNewsDataSource();
});
group('GET /api/v1/subscriptions', () {
test('returns a 200 on success', () async {
final subscription = Subscription(
id: 'a',
name: SubscriptionPlan.plus,
cost: SubscriptionCost(
annual: 4200,
monthly: 1200,
),
benefits: const ['benefitA'],
);
when(
() => newsDataSource.getSubscriptions(),
).thenAnswer((_) async => [subscription]);
final expected = SubscriptionsResponse(subscriptions: [subscription]);
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
final response = await route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.ok));
expect(response.json(), completion(equals(expected.toJson())));
verify(() => newsDataSource.getSubscriptions()).called(1);
});
});
group('POST /api/v1/subscriptions', () {
test('responds with a 400 when user is anonymous.', () async {
final request = Request('POST', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
final response = await route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.badRequest));
});
test('responds with a 400 when subscriptionId is missing.', () async {
final request = Request('POST', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
final response = await route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.badRequest));
});
test('responds with a 201 on success.', () async {
const userId = '__userId__';
const subscriptionId = '__subscription_id__';
final request = Request(
'POST',
Uri.parse('http://127.0.0.1/').replace(
queryParameters: <String, String>{
'subscriptionId': subscriptionId,
},
),
);
final user = _MockRequestUser();
when(() => user.id).thenReturn(userId);
when(() => user.isAnonymous).thenReturn(false);
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(user);
when(
() => newsDataSource.createSubscription(
userId: any(named: 'userId'),
subscriptionId: any(named: 'subscriptionId'),
),
).thenAnswer((_) async {});
final response = await route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.created));
verify(
() => newsDataSource.createSubscription(
userId: userId,
subscriptionId: subscriptionId,
),
).called(1);
});
});
test('responds with 405 when method is not POST.', () async {
final request = Request('PUT', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
final response = await route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.methodNotAllowed));
});
}
| news_toolkit/flutter_news_example/api/test/routes/subscriptions/index_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/test/routes/subscriptions/index_test.dart",
"repo_id": "news_toolkit",
"token_count": 1565
} | 875 |
# Uncomment this line to define a global platform for your project
platform :ios, '13.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
pod 'FirebaseFirestore/WithLeveldb', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '10.3.0'
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |build_configuration|
# GoogleSignIn does not support arm64 simulators.
# https://github.com/flutter/flutter/issues/85713
build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
# You can enable the permissions needed here. For example to enable camera
# permission, just remove the `#` character in front so it looks like this:
#
# ## dart: PermissionGroup.camera
# 'PERMISSION_CAMERA=1'
#
# Preprocessor definitions can be found in: https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
build_configuration.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.calendar
# 'PERMISSION_EVENTS=1',
## dart: PermissionGroup.reminders
# 'PERMISSION_REMINDERS=1',
## dart: PermissionGroup.contacts
# 'PERMISSION_CONTACTS=1',
## dart: PermissionGroup.camera
# 'PERMISSION_CAMERA=1',
## dart: PermissionGroup.microphone
# 'PERMISSION_MICROPHONE=1',
## dart: PermissionGroup.speech
# 'PERMISSION_SPEECH_RECOGNIZER=1',
## dart: PermissionGroup.photos
# 'PERMISSION_PHOTOS=1',
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
# 'PERMISSION_LOCATION=1',
## dart: PermissionGroup.notification
'PERMISSION_NOTIFICATIONS=1',
## dart: PermissionGroup.mediaLibrary
# 'PERMISSION_MEDIA_LIBRARY=1',
## dart: PermissionGroup.sensors
# 'PERMISSION_SENSORS=1',
## dart: PermissionGroup.bluetooth
# 'PERMISSION_BLUETOOTH=1',
## dart: PermissionGroup.appTrackingTransparency
# 'PERMISSION_APP_TRACKING_TRANSPARENCY=1',
## dart: PermissionGroup.criticalAlerts
# 'PERMISSION_CRITICAL_ALERTS=1'
]
end
end
end
| news_toolkit/flutter_news_example/ios/Podfile/0 | {
"file_path": "news_toolkit/flutter_news_example/ios/Podfile",
"repo_id": "news_toolkit",
"token_count": 1400
} | 876 |
export 'package:analytics_repository/analytics_repository.dart'
show
ArticleCommentEvent,
ArticleMilestoneEvent,
LoginEvent,
NewsletterEvent,
PaywallPromptEvent,
PaywallPromptImpression,
PushNotificationSubscriptionEvent,
RegistrationEvent,
SocialShareEvent,
UserSubscriptionConversionEvent;
export 'bloc/analytics_bloc.dart';
| news_toolkit/flutter_news_example/lib/analytics/analytics.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/analytics/analytics.dart",
"repo_id": "news_toolkit",
"token_count": 172
} | 877 |
part of 'article_bloc.dart';
enum ArticleStatus {
initial,
loading,
populated,
failure,
shareFailure,
rewardedAdWatchedFailure,
}
@JsonSerializable()
class ArticleState extends Equatable {
const ArticleState({
required this.status,
this.title,
this.content = const [],
this.contentTotalCount,
this.contentSeenCount = 0,
this.relatedArticles = const [],
this.hasMoreContent = true,
this.uri,
this.hasReachedArticleViewsLimit = false,
this.isPreview = false,
this.isPremium = false,
this.showInterstitialAd = false,
});
factory ArticleState.fromJson(Map<String, dynamic> json) =>
_$ArticleStateFromJson(json);
const ArticleState.initial()
: this(
status: ArticleStatus.initial,
);
final ArticleStatus status;
final String? title;
final List<NewsBlock> content;
final int? contentTotalCount;
final int contentSeenCount;
final List<NewsBlock> relatedArticles;
final bool hasMoreContent;
final Uri? uri;
final bool hasReachedArticleViewsLimit;
final bool isPreview;
final bool isPremium;
final bool showInterstitialAd;
int get contentMilestone => contentTotalCount != null && !isPreview
? _getContentMilestoneForPercentage(contentSeenCount / contentTotalCount!)
: 0;
@override
List<Object?> get props => [
status,
title,
content,
relatedArticles,
hasMoreContent,
uri,
hasReachedArticleViewsLimit,
isPreview,
isPremium,
contentTotalCount,
contentSeenCount,
showInterstitialAd,
];
ArticleState copyWith({
ArticleStatus? status,
String? title,
List<NewsBlock>? content,
int? contentTotalCount,
int? contentSeenCount,
List<NewsBlock>? relatedArticles,
bool? hasMoreContent,
Uri? uri,
bool? hasReachedArticleViewsLimit,
bool? isPreview,
bool? isPremium,
bool? showInterstitialAd,
}) {
return ArticleState(
status: status ?? this.status,
title: title ?? this.title,
content: content ?? this.content,
contentTotalCount: contentTotalCount ?? this.contentTotalCount,
contentSeenCount: contentSeenCount ?? this.contentSeenCount,
relatedArticles: relatedArticles ?? this.relatedArticles,
hasMoreContent: hasMoreContent ?? this.hasMoreContent,
uri: uri ?? this.uri,
hasReachedArticleViewsLimit:
hasReachedArticleViewsLimit ?? this.hasReachedArticleViewsLimit,
isPreview: isPreview ?? this.isPreview,
isPremium: isPremium ?? this.isPremium,
showInterstitialAd: showInterstitialAd ?? this.showInterstitialAd,
);
}
Map<String, dynamic> toJson() => _$ArticleStateToJson(this);
}
int _getContentMilestoneForPercentage(double percentage) {
if (percentage == 1.0) {
return 100;
} else if (percentage >= 0.75) {
return 75;
} else if (percentage >= 0.5) {
return 50;
} else if (percentage >= 0.25) {
return 25;
} else {
return 0;
}
}
| news_toolkit/flutter_news_example/lib/article/bloc/article_state.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/article/bloc/article_state.dart",
"repo_id": "news_toolkit",
"token_count": 1133
} | 878 |
export 'categories_tab_bar.dart';
| news_toolkit/flutter_news_example/lib/categories/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/categories/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 13
} | 879 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/home/home.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/navigation/navigation.dart';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_news_example/user_profile/user_profile.dart';
class HomeView extends StatelessWidget {
const HomeView({super.key});
@override
Widget build(BuildContext context) {
final selectedTab =
context.select((HomeCubit cubit) => cubit.state.tabIndex);
return MultiBlocListener(
listeners: [
BlocListener<AppBloc, AppState>(
listenWhen: (previous, current) =>
previous.showLoginOverlay != current.showLoginOverlay,
listener: (context, state) {
if (state.showLoginOverlay) {
showAppModal<void>(
context: context,
builder: (context) => const LoginModal(),
routeSettings: const RouteSettings(name: LoginModal.name),
);
}
},
),
BlocListener<HomeCubit, HomeState>(
listener: (context, state) {
FocusManager.instance.primaryFocus?.unfocus();
},
),
],
child: Scaffold(
appBar: AppBar(
title: AppLogo.dark(),
centerTitle: true,
actions: const [UserProfileButton()],
),
drawer: const NavDrawer(),
body: IndexedStack(
index: selectedTab,
children: const [
FeedView(),
SearchPage(),
],
),
bottomNavigationBar: BottomNavBar(
currentIndex: selectedTab,
onTap: (value) => context.read<HomeCubit>().setTab(value),
),
),
);
}
}
| news_toolkit/flutter_news_example/lib/home/view/home_view.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/home/view/home_view.dart",
"repo_id": "news_toolkit",
"token_count": 905
} | 880 |
export 'login_form.dart';
export 'login_with_email_form.dart';
| news_toolkit/flutter_news_example/lib/login/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/login/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 24
} | 881 |
export 'nav_drawer_sections.dart';
export 'nav_drawer_subscribe.dart';
| news_toolkit/flutter_news_example/lib/navigation/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/navigation/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 27
} | 882 |
import 'dart:async';
import 'package:ads_consent_client/ads_consent_client.dart';
import 'package:analytics_repository/analytics_repository.dart';
import 'package:bloc/bloc.dart';
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:equatable/equatable.dart';
import 'package:notifications_repository/notifications_repository.dart';
part 'onboarding_event.dart';
part 'onboarding_state.dart';
class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
OnboardingBloc({
required NotificationsRepository notificationsRepository,
required AdsConsentClient adsConsentClient,
}) : _notificationsRepository = notificationsRepository,
_adsConsentClient = adsConsentClient,
super(const OnboardingInitial()) {
on<EnableAdTrackingRequested>(
_onEnableAdTrackingRequested,
transformer: droppable(),
);
on<EnableNotificationsRequested>(_onEnableNotificationsRequested);
}
final NotificationsRepository _notificationsRepository;
final AdsConsentClient _adsConsentClient;
Future<void> _onEnableAdTrackingRequested(
EnableAdTrackingRequested event,
Emitter<OnboardingState> emit,
) async {
try {
emit(const EnablingAdTracking());
final adsConsentDetermined = await _adsConsentClient.requestConsent();
emit(
adsConsentDetermined
? const EnablingAdTrackingSucceeded()
: const EnablingAdTrackingFailed(),
);
} catch (error, stackTrace) {
emit(const EnablingAdTrackingFailed());
addError(error, stackTrace);
}
}
Future<void> _onEnableNotificationsRequested(
EnableNotificationsRequested event,
Emitter<OnboardingState> emit,
) async {
try {
emit(const EnablingNotifications());
await _notificationsRepository.toggleNotifications(enable: true);
emit(const EnablingNotificationsSucceeded());
} catch (error, stackTrace) {
emit(const EnablingNotificationsFailed());
addError(error, stackTrace);
}
}
}
| news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_bloc.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/onboarding/bloc/onboarding_bloc.dart",
"repo_id": "news_toolkit",
"token_count": 720
} | 883 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
class SearchHeadlineText extends StatelessWidget {
const SearchHeadlineText({required this.headerText, super.key});
final String headerText;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(
AppSpacing.lg,
AppSpacing.sm,
AppSpacing.lg,
AppSpacing.md,
),
child: Text(
headerText.toUpperCase(),
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: AppColors.secondary,
),
),
);
}
}
| news_toolkit/flutter_news_example/lib/search/widgets/search_headline_text.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/search/widgets/search_headline_text.dart",
"repo_id": "news_toolkit",
"token_count": 277
} | 884 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/analytics/analytics.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:visibility_detector/visibility_detector.dart';
@visibleForTesting
class SubscribeModal extends StatefulWidget {
const SubscribeModal({super.key});
@override
State<SubscribeModal> createState() => _SubscribeModalState();
}
class _SubscribeModalState extends State<SubscribeModal> {
bool _modalShown = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
final isLoggedIn = context.select<AppBloc, bool>(
(AppBloc bloc) => bloc.state.status.isLoggedIn,
);
final articleTitle = context.select((ArticleBloc bloc) => bloc.state.title);
return VisibilityDetector(
key: const Key('subscribeModal'),
onVisibilityChanged: _modalShown
? null
: (visibility) {
if (!visibility.visibleBounds.isEmpty) {
context.read<AnalyticsBloc>().add(
TrackAnalyticsEvent(
PaywallPromptEvent.impression(
impression: PaywallPromptImpression.subscription,
articleTitle: articleTitle ?? '',
),
),
);
setState(() => _modalShown = true);
}
},
child: ColoredBox(
color: AppColors.darkBackground,
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: AppSpacing.lg),
Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xlg),
child: Text(
l10n.subscribeModalTitle,
style: theme.textTheme.displaySmall
?.apply(color: AppColors.white),
),
),
const SizedBox(height: AppSpacing.sm + AppSpacing.xxs),
Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xlg),
child: Text(
l10n.subscribeModalSubtitle,
style: theme.textTheme.titleMedium
?.apply(color: AppColors.mediumEmphasisPrimary),
),
),
const SizedBox(height: AppSpacing.lg + AppSpacing.lg),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg + AppSpacing.xxs,
),
child: AppButton.redWine(
key: const Key('subscribeModal_subscribeButton'),
child: Text(l10n.subscribeButtonText),
onPressed: () {
context.read<AnalyticsBloc>().add(
TrackAnalyticsEvent(
PaywallPromptEvent.click(
articleTitle: articleTitle ?? '',
),
),
);
showPurchaseSubscriptionDialog(context: context);
},
),
),
const SizedBox(height: AppSpacing.sm),
if (!isLoggedIn) ...[
const SizedBox(height: AppSpacing.sm),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg + AppSpacing.xxs,
),
child: AppButton.outlinedTransparentWhite(
key: const Key('subscribeModal_logInButton'),
child: Text(l10n.subscribeModalLogInButton),
onPressed: () => showAppModal<void>(
context: context,
builder: (context) => const LoginModal(),
routeSettings: const RouteSettings(name: LoginModal.name),
),
),
),
const SizedBox(height: AppSpacing.sm),
]
],
),
),
),
);
}
}
| news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscribe_modal.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/subscriptions/widgets/subscribe_modal.dart",
"repo_id": "news_toolkit",
"token_count": 2453
} | 885 |
part of 'user_profile_bloc.dart';
abstract class UserProfileEvent extends Equatable {
const UserProfileEvent();
}
class UserProfileUpdated extends UserProfileEvent {
const UserProfileUpdated(this.user) : super();
final User user;
@override
List<Object> get props => [user];
}
class FetchNotificationsEnabled extends UserProfileEvent {
const FetchNotificationsEnabled();
@override
List<Object> get props => [];
}
class ToggleNotifications extends UserProfileEvent {
const ToggleNotifications() : super();
@override
List<Object?> get props => [];
}
| news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/user_profile/bloc/user_profile_event.dart",
"repo_id": "news_toolkit",
"token_count": 163
} | 886 |
export 'src/analytics_repository.dart';
export 'src/models/models.dart';
| news_toolkit/flutter_news_example/packages/analytics_repository/lib/analytics_repository.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/lib/analytics_repository.dart",
"repo_id": "news_toolkit",
"token_count": 27
} | 887 |
<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 1.00201L3 5.00201V11.002C3 16.552 6.84 21.742 12 23.002C17.16 21.742 21 16.552 21 11.002V5.00201L12 1.00201ZM11 7.00201H13V9.00201H11V7.00201ZM11 11.002H13V17.002H11V11.002Z" fill="black" fill-opacity="0.9"/>
</svg>
| news_toolkit/flutter_news_example/packages/app_ui/assets/icons/terms_of_use_icon.svg/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/assets/icons/terms_of_use_icon.svg",
"repo_id": "news_toolkit",
"token_count": 164
} | 888 |
{
"hosting": {
"site": "flutter-news-example-gallery",
"public": "build/web",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
| news_toolkit/flutter_news_example/packages/app_ui/gallery/firebase.json/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/firebase.json",
"repo_id": "news_toolkit",
"token_count": 152
} | 889 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
class AppButtonPage extends StatelessWidget {
const AppButtonPage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => const AppButtonPage());
}
@override
Widget build(BuildContext context) {
const contentSpacing = AppSpacing.lg;
final appButtonList = [
_AppButtonItem(
buttonType: ButtonType.google,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.google.svg(),
const SizedBox(width: AppSpacing.lg),
Padding(
padding: const EdgeInsets.only(top: AppSpacing.xxs),
child: Assets.images.continueWithGoogle.svg(),
),
],
),
),
_AppButtonItem(
buttonType: ButtonType.apple,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.apple.svg(),
const SizedBox(width: AppSpacing.lg),
Padding(
padding: const EdgeInsets.only(top: AppSpacing.xs),
child: Assets.images.continueWithApple.svg(),
),
],
),
),
_AppButtonItem(
buttonType: ButtonType.facebook,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.facebook.svg(),
const SizedBox(width: AppSpacing.lg),
Assets.images.continueWithFacebook.svg(),
],
),
),
_AppButtonItem(
buttonType: ButtonType.twitter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.twitter.svg(),
const SizedBox(width: AppSpacing.lg),
Assets.images.continueWithTwitter.svg(),
],
),
),
_AppButtonItem(
buttonType: ButtonType.email,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.emailOutline.svg(),
const SizedBox(width: AppSpacing.lg),
const Text('Continue with Email'),
],
),
),
const _AppButtonItem(
buttonType: ButtonType.login,
child: Text('Log in'),
),
const _AppButtonItem(
buttonType: ButtonType.subscribe,
child: Text('Subscribe'),
),
const _AppButtonItem(
buttonType: ButtonType.information,
child: Text('Next'),
),
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: _AppButtonItem(
buttonType: ButtonType.trial,
child: Text('Start free trial'),
),
),
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: _AppButtonItem(
buttonType: ButtonType.logout,
child: Text('Logout'),
),
),
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: _AppButtonItem(
buttonType: ButtonType.details,
child: Text('View details'),
),
),
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: _AppButtonItem(
buttonType: ButtonType.cancel,
child: Text('Cancel anytime'),
),
),
const Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: _AppButtonItem(
buttonType: ButtonType.watchVideo,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.video_call_sharp),
SizedBox(width: AppSpacing.sm),
Text('Watch a video to view this article'),
],
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg + contentSpacing,
),
child: Container(
height: 100,
color: AppColors.darkAqua,
child: const _AppButtonItem(
buttonType: ButtonType.watchVideoDark,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.video_call_sharp),
SizedBox(width: AppSpacing.sm),
Text('Watch a video to view this article'),
],
),
),
),
),
const SizedBox(height: AppSpacing.md),
Container(
height: 100,
color: AppColors.darkBackground,
child: const _AppButtonItem(
buttonType: ButtonType.logInSubscribe,
child: Text('Log In'),
),
),
];
return Scaffold(
appBar: AppBar(title: const Text('App Buttons')),
body: ListView(children: appButtonList),
);
}
}
enum ButtonType {
google,
apple,
facebook,
twitter,
email,
login,
subscribe,
information,
trial,
logout,
details,
cancel,
watchVideo,
watchVideoDark,
logInSubscribe
}
class _AppButtonItem extends StatelessWidget {
const _AppButtonItem({required this.buttonType, required this.child});
AppButton get appButton {
switch (buttonType) {
case ButtonType.google:
return AppButton.outlinedWhite(
onPressed: () {},
child: child,
);
case ButtonType.apple:
return AppButton.black(
child: child,
onPressed: () {},
);
case ButtonType.facebook:
return AppButton.blueDress(
child: child,
onPressed: () {},
);
case ButtonType.twitter:
return AppButton.crystalBlue(
onPressed: () {},
child: child,
);
case ButtonType.email:
return AppButton.outlinedTransparentDarkAqua(
onPressed: () {},
child: child,
);
case ButtonType.login:
return AppButton.outlinedTransparentDarkAqua(
onPressed: () {},
child: child,
);
case ButtonType.subscribe:
return AppButton.redWine(
child: child,
onPressed: () {},
);
case ButtonType.information:
return AppButton.darkAqua(
onPressed: () {},
child: child,
);
case ButtonType.trial:
return AppButton.smallRedWine(
onPressed: () {},
child: child,
);
case ButtonType.logout:
return AppButton.smallDarkAqua(
onPressed: () {},
child: child,
);
case ButtonType.details:
return AppButton.smallOutlineTransparent(
onPressed: () {},
child: child,
);
case ButtonType.cancel:
return AppButton.smallTransparent(
onPressed: () {},
child: child,
);
case ButtonType.watchVideo:
return AppButton.transparentDarkAqua(
onPressed: () {},
child: child,
);
case ButtonType.watchVideoDark:
return AppButton.transparentWhite(
onPressed: () {},
child: child,
);
case ButtonType.logInSubscribe:
return AppButton.outlinedTransparentWhite(
onPressed: () {},
child: child,
);
}
}
final Widget child;
final ButtonType buttonType;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.lg,
),
child: appButton,
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_button_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/widgets/app_button_page.dart",
"repo_id": "news_toolkit",
"token_count": 3859
} | 890 |
import 'package:flutter/material.dart';
/// Defines the color palette for the App UI Kit.
abstract class AppColors {
/// Black
static const Color black = Color(0xFF000000);
/// Light black
static const Color lightBlack = Colors.black54;
/// White
static const Color white = Color(0xFFFFFFFF);
/// Transparent
static const Color transparent = Color(0x00000000);
/// The grey primary color and swatch.
static const MaterialColor grey = Colors.grey;
/// The liver color.
static const Color liver = Color(0xFF4D4D4D);
/// The green primary color and swatch.
static const MaterialColor green = Colors.green;
/// The teal primary color and swatch.
static const MaterialColor teal = Colors.teal;
/// The dark aqua color.
static const Color darkAqua = Color(0xFF00677F);
/// The blue primary color and swatch.
static const Color blue = Color(0xFF3898EC);
/// The sky blue color.
static const Color skyBlue = Color(0xFF0175C2);
/// The ocean blue color.
static const Color oceanBlue = Color(0xFF02569B);
/// The light blue color.
static const MaterialColor lightBlue = Colors.lightBlue;
/// The blue dress color.
static const Color blueDress = Color(0xFF1877F2);
/// The crystal blue color.
static const Color crystalBlue = Color(0xFF55ACEE);
/// The light surface2 dress color.
static const Color surface2 = Color(0xFFEBF2F7);
/// The pale sky color.
static const Color paleSky = Color(0xFF73777F);
/// The input hover color.
static const Color inputHover = Color(0xFFE4E4E4);
/// The input focused color.
static const Color inputFocused = Color(0xFFD1D1D1);
/// The input enabled color.
static const Color inputEnabled = Color(0xFFEDEDED);
/// The pastel grey color.
static const Color pastelGrey = Color(0xFFCCCCCC);
/// The bright grey color.
static const Color brightGrey = Color(0xFFEAEAEA);
/// The yellow primary color.
static const MaterialColor yellow = Colors.yellow;
/// The red primary color and swatch.
static const MaterialColor red = Colors.red;
/// The background color.
static const Color background = Color(0xFFFFFFFF);
/// The dark background color.
static const Color darkBackground = Color(0xFF001F28);
/// The on-background color.
static const Color onBackground = Color(0xFF1A1A1A);
/// The primary container color.
static const Color primaryContainer = Color(0xFFB1EBFF);
/// The dark text 1 color.
static const Color darkText1 = Color(0xFFFCFCFC);
/// The red wine color.
static const Color redWine = Color(0xFF9A031E);
/// The rangoonGreen color.
static const Color rangoonGreen = Color(0xFF1B1B1B);
/// The modal background color.
static const Color modalBackground = Color(0xFFEBF2F7);
/// The eerie black color.
static const Color eerieBlack = Color(0xFF191C1D);
/// The medium emphasis primary color.
static const Color mediumEmphasisPrimary = Color(0xBDFFFFFF);
/// The medium emphasis surface color.
static const Color mediumEmphasisSurface = Color(0x99000000);
/// The high emphasis primary color.
static const Color highEmphasisPrimary = Color(0xFCFFFFFF);
/// The high emphasis surface color.
static const Color highEmphasisSurface = Color(0xE6000000);
/// The border outline color.
static const Color borderOutline = Color(0x33000000);
/// The light outline color.
static const Color outlineLight = Color(0x33000000);
/// The outline on dark color.
static const Color outlineOnDark = Color(0x29FFFFFF);
/// The secondary color of application.
static const MaterialColor secondary = MaterialColor(0xFF963F6E, <int, Color>{
50: Color(0xFFFFECF3),
100: Color(0xFFFFD8E9),
200: Color(0xFFFFAFD6),
300: Color(0xFFF28ABE),
400: Color(0xFFD371A3),
500: Color(0xFFB55788),
600: Color(0xFF963F6E),
700: Color(0xFF7A2756),
800: Color(0xFF5F0F40),
900: Color(0xFF3D0026),
});
/// The medium high emphasis primary color.
static const Color mediumHighEmphasisPrimary = Color(0xE6FFFFFF);
/// The medium high emphasis surface color.
static const Color mediumHighEmphasisSurface = Color(0xB3000000);
/// The default disabled foreground color.
static const Color disabledForeground = Color(0x611B1B1B);
/// The default disabled button color.
static const Color disabledButton = Color(0x1F000000);
/// The default disabled surface color.
static const Color disabledSurface = Color(0xFFE0E0E0);
/// The gainsboro color.
static const Color gainsboro = Color(0xFFDADCE0);
/// The orange color.
static const Color orange = Color(0xFFFB8B24);
}
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/colors/app_colors.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/colors/app_colors.dart",
"repo_id": "news_toolkit",
"token_count": 1434
} | 891 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template app_switch}
/// Switch with optional leading text displayed in the application.
/// {@endtemplate}
class AppSwitch extends StatelessWidget {
/// {@macro app_switch}
const AppSwitch({
required this.value,
required this.onChanged,
this.onText = '',
this.offText = '',
super.key,
});
/// Text displayed when this switch is set to true.
///
/// Defaults to an empty string.
final String onText;
/// Text displayed when this switch is set to false.
///
/// Defaults to an empty string.
final String offText;
/// Whether this checkbox is checked.
final bool value;
/// Called when the value of the checkbox should change.
final ValueChanged<bool?> onChanged;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
ContentThemeOverrideBuilder(
builder: (context) => Text(
value ? onText : offText,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: AppColors.eerieBlack,
),
),
),
Padding(
padding: const EdgeInsets.only(
top: AppSpacing.xxs,
),
child: Switch(
value: value,
onChanged: onChanged,
),
),
],
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_switch.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_switch.dart",
"repo_id": "news_toolkit",
"token_count": 587
} | 892 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../helpers/helpers.dart';
void main() {
group('ContentThemeOverrideBuilder', () {
final theme = const AppTheme().themeData;
testWidgets('overrides the text theme to AppTheme.contentTextTheme',
(tester) async {
late BuildContext capturedContext;
await tester.pumpApp(
Builder(
builder: (context) {
capturedContext = context;
return const SizedBox();
},
),
theme: theme,
);
expect(
Theme.of(capturedContext).textTheme.displayLarge,
equals(
AppTheme.uiTextTheme.displayLarge!.copyWith(
inherit: false,
),
),
);
await tester.pumpApp(
ContentThemeOverrideBuilder(
builder: (context) {
capturedContext = context;
return const SizedBox();
},
),
theme: theme,
);
expect(
Theme.of(capturedContext).textTheme.displayLarge,
equals(
AppTheme.contentTextTheme.displayLarge!.copyWith(
inherit: false,
),
),
);
});
});
}
| news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/content_theme_override_builder_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/content_theme_override_builder_test.dart",
"repo_id": "news_toolkit",
"token_count": 594
} | 893 |
import 'dart:async';
import 'package:authentication_client/authentication_client.dart';
/// {@template authentication_exception}
/// Exceptions from the authentication client.
/// {@endtemplate}
abstract class AuthenticationException implements Exception {
/// {@macro authentication_exception}
const AuthenticationException(this.error);
/// The error which was caught.
final Object error;
}
/// {@template send_login_email_link_failure}
/// Thrown during the sending login email link process if a failure occurs.
/// {@endtemplate}
class SendLoginEmailLinkFailure extends AuthenticationException {
/// {@macro send_login_email_link_failure}
const SendLoginEmailLinkFailure(super.error);
}
/// {@template is is_log_in_email_link_failure}
/// Thrown during the validation of the email link process if a failure occurs.
/// {@endtemplate}
class IsLogInWithEmailLinkFailure extends AuthenticationException {
/// {@macro is_log_in_email_link_failure}
const IsLogInWithEmailLinkFailure(super.error);
}
/// {@template log_in_with_email_link_failure}
/// Thrown during the sign in with email link process if a failure occurs.
/// {@endtemplate}
class LogInWithEmailLinkFailure extends AuthenticationException {
/// {@macro log_in_with_email_link_failure}
const LogInWithEmailLinkFailure(super.error);
}
/// {@template log_in_with_apple_failure}
/// Thrown during the sign in with apple process if a failure occurs.
/// {@endtemplate}
class LogInWithAppleFailure extends AuthenticationException {
/// {@macro log_in_with_apple_failure}
const LogInWithAppleFailure(super.error);
}
/// {@template log_in_with_google_failure}
/// Thrown during the sign in with google process if a failure occurs.
/// {@endtemplate}
class LogInWithGoogleFailure extends AuthenticationException {
/// {@macro log_in_with_google_failure}
const LogInWithGoogleFailure(super.error);
}
/// {@template log_in_with_google_canceled}
/// Thrown during the sign in with google process if it's canceled.
/// {@endtemplate}
class LogInWithGoogleCanceled extends AuthenticationException {
/// {@macro log_in_with_google_canceled}
const LogInWithGoogleCanceled(super.error);
}
/// {@template log_in_with_facebook_failure}
/// Thrown during the sign in with Facebook process if a failure occurs.
/// {@endtemplate}
class LogInWithFacebookFailure extends AuthenticationException {
/// {@macro log_in_with_facebook_failure}
const LogInWithFacebookFailure(super.error);
}
/// {@template log_in_with_facebook_canceled}
/// Thrown during the sign in with Facebook process if it's canceled.
/// {@endtemplate}
class LogInWithFacebookCanceled extends AuthenticationException {
/// {@macro log_in_with_facebook_canceled}
const LogInWithFacebookCanceled(super.error);
}
/// {@template log_in_with_twitter_failure}
/// Thrown during the sign in with Twitter process if a failure occurs.
/// {@endtemplate}
class LogInWithTwitterFailure extends AuthenticationException {
/// {@macro log_in_with_twitter_failure}
const LogInWithTwitterFailure(super.error);
}
/// {@template log_in_with_twitter_canceled}
/// Thrown during the sign in with Twitter process if it's canceled.
/// {@endtemplate}
class LogInWithTwitterCanceled extends AuthenticationException {
/// {@macro log_in_with_twitter_canceled}
const LogInWithTwitterCanceled(super.error);
}
/// {@template log_out_failure}
/// Thrown during the logout process if a failure occurs.
/// {@endtemplate}
class LogOutFailure extends AuthenticationException {
/// {@macro log_out_failure}
const LogOutFailure(super.error);
}
/// A generic Authentication Client Interface.
abstract class AuthenticationClient {
/// Stream of [AuthenticationUser] which will emit the current user when
/// the authentication state changes.
///
/// Emits [AuthenticationUser.anonymous] if the user is not authenticated.
Stream<AuthenticationUser> get user;
/// Starts the Sign In with Apple Flow.
///
/// Throws a [LogInWithAppleFailure] if an exception occurs.
Future<void> logInWithApple();
/// Starts the Sign In with Google Flow.
///
/// Throws a [LogInWithGoogleFailure] if an exception occurs.
Future<void> logInWithGoogle();
/// Starts the Sign In with Facebook Flow.
///
/// Throws a [LogInWithFacebookFailure] if an exception occurs.
Future<void> logInWithFacebook();
/// Starts the Sign In with Twitter Flow.
///
/// Throws a [LogInWithTwitterFailure] if an exception occurs.
Future<void> logInWithTwitter();
/// Sends an authentication link to the provided [email].
///
/// Opening the link should redirect to the app with [appPackageName]
/// and authenticate the user based on the provided email link.
///
/// Throws a [SendLoginEmailLinkFailure] if an exception occurs.
Future<void> sendLoginEmailLink({
required String email,
required String appPackageName,
});
/// Checks if an incoming [emailLink] is a sign-in with email link.
///
/// Throws a [IsLogInWithEmailLinkFailure] if an exception occurs.
bool isLogInWithEmailLink({
required String emailLink,
});
/// Signs in with the provided [email] and [emailLink].
///
/// Throws a [LogInWithEmailLinkFailure] if an exception occurs.
Future<void> logInWithEmailLink({
required String email,
required String emailLink,
});
/// Signs out the current user which will emit
/// [AuthenticationUser.anonymous] from the [user] Stream.
///
/// Throws a [LogOutFailure] if an exception occurs.
Future<void> logOut();
}
| news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/authentication_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/authentication_client/lib/src/authentication_client.dart",
"repo_id": "news_toolkit",
"token_count": 1591
} | 894 |
/// {@template token_storage}
/// Token storage for the authentication client.
/// {@endtemplate}
abstract class TokenStorage {
/// Returns the current token.
Future<String?> readToken();
/// Saves the current token.
Future<void> saveToken(String token);
/// Clears the current token.
Future<void> clearToken();
}
/// {@template in_memory_token_storage}
/// In-memory token storage for the authentication client.
/// {@endtemplate}
class InMemoryTokenStorage implements TokenStorage {
String? _token;
@override
Future<String?> readToken() async => _token;
@override
Future<void> saveToken(String token) async => _token = token;
@override
Future<void> clearToken() async => _token = null;
}
| news_toolkit/flutter_news_example/packages/authentication_client/token_storage/lib/src/token_storage.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/token_storage/lib/src/token_storage.dart",
"repo_id": "news_toolkit",
"token_count": 208
} | 895 |
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
/// {@template mock_url_launcher}
/// Class to mock the methods related to url_launcher package.
///{@endtemplate}
class MockUrlLauncher extends Fake
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {
/// The string url.
String? canLaunchUrl;
/// Bool to know if is used Safari.
bool? useSafariVC;
/// Bool to know if is used a web view.
bool? useWebView;
/// Bool to know if javascript is enabled.
bool? enableJavaScript;
/// Bool to know if dom storage is enabled.
bool? enableDomStorage;
/// Map of headers.
Map<String, String>? headers;
/// String of the web only window name.
String? webOnlyWindowName;
/// Bool to know the response of the method.
bool? response;
/// Bool to close the web view.
bool closeWebViewCalled = false;
/// Bool to know if a URI can be launch.
bool canLaunchCalled = false;
/// Bool to know if the URI was launched.
bool launchCalled = false;
/// The launch options.
LaunchOptions? options;
/// Sets needed variables to use the `launch` method.
void setLaunchExpectations({
required String url,
required bool? useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
required String? webOnlyWindowName,
}) {
canLaunchUrl = url;
this.useSafariVC = useSafariVC;
this.useWebView = useWebView;
this.enableJavaScript = enableJavaScript;
this.enableDomStorage = enableDomStorage;
this.headers = headers;
this.webOnlyWindowName = webOnlyWindowName;
}
/// Sets needed variables to use the `launchUrl` method.
void setLaunchUrlExpectations({
required String url,
LaunchOptions? options,
}) {
canLaunchUrl = url;
this.options = options;
}
@override
Future<bool> canLaunch(String url) async {
expect(url, canLaunchUrl);
canLaunchCalled = true;
return response!;
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) async {
expect(url, canLaunchUrl);
expect(useSafariVC, this.useSafariVC);
expect(useWebView, this.useWebView);
expect(enableJavaScript, this.enableJavaScript);
expect(enableDomStorage, this.enableDomStorage);
expect(headers, this.headers);
expect(webOnlyWindowName, this.webOnlyWindowName);
launchCalled = true;
return response!;
}
@override
Future<bool> launchUrl(String url, LaunchOptions options) async {
expect(url, canLaunchUrl);
if (this.options != null) {
expect(options, this.options);
}
launchCalled = true;
return response!;
}
}
| news_toolkit/flutter_news_example/packages/email_launcher/test/helpers/mock_url_launcher.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/email_launcher/test/helpers/mock_url_launcher.dart",
"repo_id": "news_toolkit",
"token_count": 1024
} | 896 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart' hide ProgressIndicator;
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template image}
/// A reusable image news block widget.
/// {@endtemplate}
class Image extends StatelessWidget {
/// {@macro image}
const Image({required this.block, super.key});
/// The associated [ImageBlock] instance.
final ImageBlock block;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: InlineImage(
imageUrl: block.imageUrl,
progressIndicatorBuilder: (context, url, downloadProgress) =>
ProgressIndicator(progress: downloadProgress.progress),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/image.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/image.dart",
"repo_id": "news_toolkit",
"token_count": 286
} | 897 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template slideshow_introduction}
/// A reusable slideshow introduction news block widget.
/// {@endtemplate}
class SlideshowIntroduction extends StatelessWidget {
/// {@macro slideshow_introduction}
const SlideshowIntroduction({
required this.block,
required this.slideshowText,
this.onPressed,
super.key,
});
/// The associated [SlideshowIntroductionBlock] instance.
final SlideshowIntroductionBlock block;
/// An optional callback which is invoked when the action is triggered.
/// A [Uri] from the associated [BlockAction] is provided to the callback.
final BlockActionCallback? onPressed;
/// Text displayed in the slideshow category widget.
final String slideshowText;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final action = block.action;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: GestureDetector(
onTap: () {
if (action != null) onPressed?.call(action);
},
child: Stack(
alignment: Alignment.bottomLeft,
children: [
PostLargeImage(
imageUrl: block.coverImageUrl,
isContentOverlaid: true,
isLocked: false,
),
Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SlideshowCategory(slideshowText: slideshowText),
const SizedBox(
height: AppSpacing.xs,
),
Text(
block.title,
style: textTheme.displayMedium?.copyWith(
color: AppColors.highEmphasisPrimary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/slideshow_introduction.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/slideshow_introduction.dart",
"repo_id": "news_toolkit",
"token_count": 1046
} | 898 |
import 'package:app_ui/app_ui.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/widgets.dart';
/// {@template overlaid_image}
/// A reusable image widget overlaid with colored gradient.
/// {@endtemplate}
class OverlaidImage extends StatelessWidget {
/// {@macro overlaid_image}
const OverlaidImage({
required this.imageUrl,
required this.gradientColor,
super.key,
});
/// The aspect ratio of this image.
static const aspectRatio = 3 / 2;
/// The url of this image.
final String imageUrl;
/// The color of gradient.
final Color gradientColor;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: aspectRatio,
child: Stack(
key: const Key('overlaidImage_stack'),
children: [
CachedNetworkImage(
imageUrl: imageUrl,
height: double.infinity,
width: double.infinity,
fit: BoxFit.cover,
),
DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
AppColors.transparent,
gradientColor.withOpacity(0.7),
],
),
),
child: const SizedBox.expand(),
),
],
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/overlaid_image.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/overlaid_image.dart",
"repo_id": "news_toolkit",
"token_count": 657
} | 899 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import '../helpers/helpers.dart';
void main() {
const category = PostCategory.technology;
const author = 'Sean Hollister';
final publishedAt = DateTime(2022, 3, 9);
const imageUrl =
'https://cdn.vox-cdn.com/thumbor/OTpmptgr7XcTVAJ27UBvIxl0vrg='
'/0x146:2040x1214/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset'
'/file/22049166/shollister_201117_4303_0003.0.jpg';
const title = 'Nvidia and AMD GPUs are returning to shelves '
'and prices are finally falling';
const premiumText = 'Subscriber Exclusive';
group('ArticleIntroduction', () {
setUpAll(setUpTolerantComparator);
final technologyArticleIntroduction = ArticleIntroductionBlock(
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
);
testWidgets('renders correctly', (tester) async {
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
SingleChildScrollView(
child: Column(
children: [
ArticleIntroduction(
block: technologyArticleIntroduction,
premiumText: premiumText,
),
],
),
),
),
);
expect(find.byType(ArticleIntroduction), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/article_introduction_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/article_introduction_test.dart",
"repo_id": "news_toolkit",
"token_count": 673
} | 900 |
// ignore_for_file: unnecessary_const, prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import '../../helpers/helpers.dart';
void main() {
const id = '499305f6-5096-4051-afda-824dcfc7df23';
const category = PostCategory.technology;
const author = 'Sean Hollister';
final publishedAt = DateTime(2022, 3, 9);
const imageUrl =
'https://cdn.vox-cdn.com/thumbor/OTpmptgr7XcTVAJ27UBvIxl0vrg='
'/0x146:2040x1214/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset'
'/file/22049166/shollister_201117_4303_0003.0.jpg';
const title = 'Nvidia and AMD GPUs are returning to shelves '
'and prices are finally falling';
group('PostLarge', () {
setUpAll(setUpTolerantComparator);
group('renders correctly overlaid ', () {
testWidgets(
'showing LockIcon '
'when isLocked is true', (tester) async {
final technologyPostLarge = PostLargeBlock(
id: id,
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
isContentOverlaid: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
SingleChildScrollView(
child: Column(
children: [
PostLarge(
block: technologyPostLarge,
premiumText: 'Premium',
isLocked: true,
),
],
),
),
),
);
expect(find.byKey(Key('postLarge_stack')), findsOneWidget);
expect(find.byType(LockIcon), findsOneWidget);
});
testWidgets(
'not showing LockIcon '
'when isLocked is false', (tester) async {
final technologyPostLarge = PostLargeBlock(
id: id,
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
isContentOverlaid: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
SingleChildScrollView(
child: Column(
children: [
PostLarge(
block: technologyPostLarge,
premiumText: 'Premium',
isLocked: false,
),
],
),
),
),
);
expect(find.byKey(Key('postLarge_stack')), findsOneWidget);
expect(find.byType(LockIcon), findsNothing);
});
});
group('renders correctly in column ', () {
testWidgets(
'showing LockIcon '
'when isLocked is true', (tester) async {
final technologyPostLarge = PostLargeBlock(
id: id,
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
SingleChildScrollView(
child: Column(
children: [
PostLarge(
block: technologyPostLarge,
premiumText: 'Premium',
isLocked: true,
),
],
),
),
),
);
expect(find.byKey(Key('postLarge_column')), findsOneWidget);
expect(find.byType(LockIcon), findsOneWidget);
});
testWidgets(
'not showing LockIcon '
'when isLocked is false', (tester) async {
final technologyPostLarge = PostLargeBlock(
id: id,
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
SingleChildScrollView(
child: Column(
children: [
PostLarge(
block: technologyPostLarge,
premiumText: 'Premium',
isLocked: false,
),
],
),
),
),
);
expect(find.byKey(Key('postLarge_column')), findsOneWidget);
expect(find.byType(LockIcon), findsNothing);
});
});
});
testWidgets('onPressed is called with action when tapped', (tester) async {
final action = NavigateToArticleAction(articleId: id);
final actions = <BlockAction>[];
final technologyPostLarge = PostLargeBlock(
id: id,
category: category,
author: author,
publishedAt: publishedAt,
imageUrl: imageUrl,
title: title,
action: action,
isContentOverlaid: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(
ListView(
children: [
PostLarge(
block: technologyPostLarge,
premiumText: 'Premium',
onPressed: actions.add,
isLocked: false,
),
],
),
),
);
await tester.ensureVisible(find.byType(PostLarge));
await tester.tap(find.byType(PostLarge));
expect(actions, equals([action]));
});
}
// TODO(jan-stepien): Update golden tests containing network images
// testWidgets('renders correctly non-premium', (tester) async {
// final _technologyPostLarge = PostLargeBlock(
// id: id,
// category: category,
// author: author,
// publishedAt: publishedAt,
// imageUrl: imageUrl,
// title: title,
// );
// await mockNetworkImages(
// () async => tester.pumpContentThemedApp(
// SingleChildScrollView(
// child: Column(
// children: [
// PostLarge(
// block: _technologyPostLarge,
// premiumText: 'Premium',
// ),
// ],
// ),
// ),
// ),
// );
// await expectLater(
// find.byType(PostLarge),
// matchesGoldenFile('post_large_non_premium.png'),
// );
// });
// testWidgets('renders correctly premium', (tester) async {
// final premiumBlock = PostLargeBlock(
// id: id,
// category: category,
// author: author,
// publishedAt: publishedAt,
// imageUrl: imageUrl,
// title: title,
// isPremium: true,
// );
// await mockNetworkImages(
// () async => tester.pumpContentThemedApp(
// SingleChildScrollView(
// child: Column(
// children: [
// PostLarge(
// block: premiumBlock,
// premiumText: 'Premium',
// ),
// ],
// ),
// ),
// ),
// );
// await expectLater(
// find.byType(PostLarge),
// matchesGoldenFile('post_large_premium.png'),
// );
// });
// testWidgets('renders correctly overlaid view', (tester) async {
// final _technologyPostLarge = PostLargeBlock(
// id: id,
// category: category,
// author: author,
// publishedAt: publishedAt,
// imageUrl: imageUrl,
// title: title,
// isContentOverlaid: true,
// );
// await mockNetworkImages(
// () async => tester.pumpContentThemedApp(
// SingleChildScrollView(
// child: Column(
// children: [
// PostLarge(
// block: _technologyPostLarge,
// premiumText: 'Premium',
// ),
// ],
// ),
// ),
// ),
// );
// await expectLater(
// find.byType(PostLarge),
// matchesGoldenFile('post_large_overlaid_non_premium.png'),
// );
// });
// });
// }
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/post_large/post_large_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/post_large/post_large_test.dart",
"repo_id": "news_toolkit",
"token_count": 4113
} | 901 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_client/one_signal_notifications_client/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 902 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/package_info_client/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/package_info_client/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 903 |
import 'package:in_app_purchase/in_app_purchase.dart';
/// List of available [ProductDetails] products.
final Map<String, ProductDetails> availableProducts = {
'dd339fda-33e9-49d0-9eb5-0ccb77eb760f': ProductDetails(
id: 'dd339fda-33e9-49d0-9eb5-0ccb77eb760f',
title: 'premium',
description: 'premium subscription',
price: r'$14.99',
rawPrice: 14.99,
currencyCode: 'USD',
)
};
| news_toolkit/flutter_news_example/packages/purchase_client/lib/src/products.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/purchase_client/lib/src/products.dart",
"repo_id": "news_toolkit",
"token_count": 170
} | 904 |
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:persistent_storage/persistent_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storage/storage.dart';
class MockSharedPreferences extends Mock implements SharedPreferences {}
void main() {
const mockKey = 'mock-key';
const mockValue = 'mock-value';
final mockException = Exception('oops');
group('PersistentStorage', () {
late SharedPreferences sharedPreferences;
late PersistentStorage persistentStorage;
setUp(() {
sharedPreferences = MockSharedPreferences();
persistentStorage = PersistentStorage(
sharedPreferences: sharedPreferences,
);
});
group('read', () {
test(
'returns value '
'when SharedPreferences.getString returns successfully', () async {
when(() => sharedPreferences.getString(any())).thenReturn(mockValue);
final actualValue = await persistentStorage.read(key: mockKey);
expect(actualValue, mockValue);
});
test(
'returns null '
'when sharedPreferences.getString returns null', () async {
when(() => sharedPreferences.getString(any())).thenReturn(null);
final actualValue = await persistentStorage.read(key: mockKey);
expect(actualValue, isNull);
});
test(
'throws a StorageException '
'when sharedPreferences.getString fails', () async {
when(() => sharedPreferences.getString(any())).thenThrow(mockException);
expect(
() => persistentStorage.read(key: mockKey),
throwsA(
isA<StorageException>().having(
(exception) => exception.error,
'error',
equals(mockException),
),
),
);
});
});
group('write', () {
test(
'completes '
'when sharedPreferences.setString completes', () async {
when(() => sharedPreferences.setString(any(), any()))
.thenAnswer((_) async => true);
expect(
persistentStorage.write(key: mockKey, value: mockValue),
completes,
);
});
test(
'throws a StorageException '
'when sharedPreferences.setString fails', () async {
when(() => sharedPreferences.setString(any(), any()))
.thenThrow(mockException);
expect(
() => persistentStorage.write(key: mockKey, value: mockValue),
throwsA(
isA<StorageException>().having(
(exception) => exception.error,
'error',
equals(mockException),
),
),
);
});
});
group('delete', () {
test(
'completes '
'when sharedPreferences.remove completes', () async {
when(() => sharedPreferences.remove(any()))
.thenAnswer((_) async => true);
expect(
persistentStorage.delete(key: mockKey),
completes,
);
});
test(
'throws a StorageException '
'when sharedPreferences.remove fails', () async {
when(() => sharedPreferences.remove(any())).thenThrow(mockException);
expect(
() => persistentStorage.delete(key: mockKey),
throwsA(
isA<StorageException>().having(
(exception) => exception.error,
'error',
equals(mockException),
),
),
);
});
});
group('clear', () {
test(
'completes '
'when sharedPreferences.clear completes', () async {
when(sharedPreferences.clear).thenAnswer((_) async => true);
expect(persistentStorage.clear(), completes);
});
test(
'throws a StorageException '
'when sharedPreferences.clear fails', () async {
when(sharedPreferences.clear).thenThrow(mockException);
expect(
persistentStorage.clear,
throwsA(
isA<StorageException>().having(
(exception) => exception.error,
'error',
equals(mockException),
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/packages/storage/persistent_storage/test/src/persistent_storage_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/test/src/persistent_storage_test.dart",
"repo_id": "news_toolkit",
"token_count": 1917
} | 905 |
export 'user.dart';
| news_toolkit/flutter_news_example/packages/user_repository/lib/src/models/models.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/user_repository/lib/src/models/models.dart",
"repo_id": "news_toolkit",
"token_count": 8
} | 906 |
import 'package:analytics_repository/analytics_repository.dart' as analytics;
import 'package:flutter_news_example/analytics/analytics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:user_repository/user_repository.dart';
class MockUser extends Mock implements User {}
class MockAnalyticsEvent extends Mock implements analytics.AnalyticsEvent {}
void main() {
group('AnalyticsEvent', () {
group('TrackAnalyticsEvent', () {
test('supports value comparisons', () {
final event = MockAnalyticsEvent();
expect(TrackAnalyticsEvent(event), TrackAnalyticsEvent(event));
});
});
});
}
| news_toolkit/flutter_news_example/test/analytics/bloc/analytics_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/analytics/bloc/analytics_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 227
} | 907 |
// ignore_for_file: prefer_const_constructors
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/ads/ads.dart';
import 'package:flutter_news_example/analytics/analytics.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/network_error/network_error.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../helpers/helpers.dart';
class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState>
implements ArticleBloc {}
class MockNavigatorObserver extends Mock implements NavigatorObserver {}
const networkErrorButtonText = 'Try Again';
void main() {
late ArticleBloc articleBloc;
final content = <NewsBlock>[
DividerHorizontalBlock(),
SpacerBlock(spacing: Spacing.medium),
TextParagraphBlock(text: 'text'),
ImageBlock(imageUrl: 'imageUrl'),
];
setUp(() {
articleBloc = MockArticleBloc();
when(() => articleBloc.state).thenReturn(
ArticleState(content: content, status: ArticleStatus.populated),
);
VisibilityDetectorController.instance.updateInterval = Duration.zero;
});
group('ArticleContent', () {
testWidgets('renders a SelectionArea', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(find.byType(SelectionArea), findsOneWidget);
});
testWidgets('renders StickyAd', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(find.byType(StickyAd), findsOneWidget);
});
group('when ArticleStatus is failure and content is present', () {
setUp(() {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(content: content, status: ArticleStatus.failure),
]),
);
});
testWidgets('shows NetworkErrorAlert', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.byType(NetworkError),
findsOneWidget,
);
});
testWidgets('shows ArticleContentItem for each content block',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
for (final block in content) {
expect(
find.byWidgetPredicate(
(widget) => widget is ArticleContentItem && widget.block == block,
),
findsOneWidget,
);
}
});
testWidgets('NetworkErrorAlert requests article on press',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.text(networkErrorButtonText),
findsOneWidget,
);
await tester.ensureVisible(find.textContaining(networkErrorButtonText));
verify(() => articleBloc.add(ArticleRequested())).called(1);
await tester.pump();
await tester.tap(find.textContaining(networkErrorButtonText));
verify(() => articleBloc.add(ArticleRequested())).called(1);
});
});
group('when ArticleStatus is failure and content is absent', () {
setUpAll(() {
registerFallbackValue(NetworkError.route());
});
setUp(() {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(content: [], status: ArticleStatus.failure),
]),
);
});
testWidgets('pushes NetworkErrorAlert on Scaffold', (tester) async {
final navigatorObserver = MockNavigatorObserver();
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
navigatorObserver: navigatorObserver,
);
verify(() => navigatorObserver.didPush(any(), any()));
expect(
find.ancestor(
of: find.byType(NetworkError),
matching: find.byType(Scaffold),
),
findsOneWidget,
);
});
testWidgets('NetworkErrorAlert requests article on press',
(tester) async {
final navigatorObserver = MockNavigatorObserver();
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
navigatorObserver: navigatorObserver,
);
verify(() => navigatorObserver.didPush(any(), any()));
expect(
find.text(networkErrorButtonText),
findsOneWidget,
);
await tester.ensureVisible(find.textContaining(networkErrorButtonText));
verify(() => articleBloc.add(ArticleRequested())).called(1);
await tester.pump();
await tester.tap(find.textContaining(networkErrorButtonText).last);
await tester.pump();
verify(() => articleBloc.add(ArticleRequested())).called(1);
verify(() => navigatorObserver.didPop(any(), any()));
});
});
group('when ArticleStatus is shareFailure', () {
setUp(() {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(content: content, status: ArticleStatus.shareFailure),
]),
);
});
testWidgets('shows SnackBar with error message', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.byKey(const Key('articleContent_shareFailure_snackBar')),
findsOneWidget,
);
});
});
group('when ArticleStatus is populated', () {
final uri = Uri(path: 'notEmptyUrl');
setUp(() {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(
status: ArticleStatus.populated,
content: content,
uri: uri,
),
]),
);
});
testWidgets('shows ArticleContentItem for each content block',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
for (final block in content) {
expect(
find.byWidgetPredicate(
(widget) => widget is ArticleContentItem && widget.block == block,
),
findsOneWidget,
);
}
});
testWidgets(
'adds ShareRequested to ArticleBloc '
'when ArticleContentItem onSharePressed is called', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
final articleItem = find.byType(ArticleContentItem).first;
tester.widget<ArticleContentItem>(articleItem).onSharePressed?.call();
verify(() => articleBloc.add(ShareRequested(uri: uri))).called(1);
});
testWidgets(
'adds ArticleContentSeen to ArticleBloc '
'for every visible content block', (tester) async {
final longContent = <NewsBlock>[
DividerHorizontalBlock(),
SpacerBlock(spacing: Spacing.medium),
TextParagraphBlock(text: 'text'),
ImageBlock(imageUrl: 'imageUrl'),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
SpacerBlock(spacing: Spacing.extraLarge),
TextLeadParagraphBlock(text: 'text'),
];
final state =
ArticleState(content: longContent, status: ArticleStatus.populated);
whenListen(
articleBloc,
Stream.value(state),
initialState: state,
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
await tester.pump();
verifyNever(
() => articleBloc
.add(ArticleContentSeen(contentIndex: longContent.length - 1)),
);
await tester.dragUntilVisible(
find.byWidgetPredicate(
(widget) =>
widget is ArticleContentItem &&
widget.block == longContent.last,
),
find.byType(ArticleContent),
Offset(0, -50),
duration: Duration.zero,
);
await tester.pump();
for (var index = 0; index < longContent.length; index++) {
verify(
() => articleBloc.add(ArticleContentSeen(contentIndex: index)),
).called(isNonZero);
}
});
testWidgets(
'adds TrackAnalyticsEvent to AnalyticsBloc '
'with ArticleMilestoneEvent '
'when contentMilestone changes', (tester) async {
final analyticsBloc = MockAnalyticsBloc();
final initialState = ArticleState.initial().copyWith(title: 'title');
final states = [
initialState.copyWith(contentSeenCount: 3, contentTotalCount: 10),
initialState.copyWith(contentSeenCount: 5, contentTotalCount: 10),
initialState.copyWith(contentSeenCount: 10, contentTotalCount: 10),
];
whenListen(
articleBloc,
Stream.fromIterable(states),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
analyticsBloc: analyticsBloc,
);
for (final state in states) {
verify(
() => analyticsBloc.add(
TrackAnalyticsEvent(
ArticleMilestoneEvent(
articleTitle: state.title!,
milestonePercentage: state.contentMilestone,
),
),
),
).called(1);
}
});
});
group('ArticleContentLoaderItem', () {
group('is shown', () {
testWidgets('when ArticleStatus is initial', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
]),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.byKey(Key('articleContent_empty_loaderItem')),
findsOneWidget,
);
});
testWidgets('when ArticleStatus is loading', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState(status: ArticleStatus.loading),
]),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.byKey(Key('articleContent_moreContent_loaderItem')),
findsOneWidget,
);
});
testWidgets(
'when ArticleStatus is populated '
'and hasMoreContent is true', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(
status: ArticleStatus.populated,
content: content,
hasMoreContent: true,
)
]),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(
find.byKey(Key('articleContent_moreContent_loaderItem')),
findsOneWidget,
);
});
});
testWidgets(
'is not shown and ArticleTrailingContent is shown '
'when ArticleStatus is populated '
'and hasMoreContent is false', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(
status: ArticleStatus.populated,
content: content,
hasMoreContent: false,
)
]),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
expect(find.byType(ArticleContentLoaderItem), findsNothing);
expect(find.byType(ArticleTrailingContent), findsOneWidget);
});
testWidgets('adds ArticleRequested to ArticleBloc', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(
status: ArticleStatus.populated,
content: content,
hasMoreContent: true,
)
]),
initialState: ArticleState.initial(),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
verify(() => articleBloc.add(ArticleRequested())).called(1);
});
testWidgets(
'does not add ArticleRequested to ArticleBloc '
'when ArticleStatus is loading', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable([
ArticleState.initial(),
ArticleState(
status: ArticleStatus.loading,
content: content,
hasMoreContent: true,
)
]),
initialState: ArticleState.initial(),
);
await tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: ArticleContent(),
),
);
verifyNever(() => articleBloc.add(ArticleRequested()));
});
});
group('when isArticlePreview is true ', () {
testWidgets('renders ArticleTrailingShadow', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState(
content: content,
status: ArticleStatus.populated,
isPreview: true,
),
);
await tester.pumpApp(
BlocProvider.value(value: articleBloc, child: ArticleContent()),
);
expect(find.byType(ArticleTrailingShadow), findsOneWidget);
});
});
});
}
| news_toolkit/flutter_news_example/test/article/widgets/article_content_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/article/widgets/article_content_test.dart",
"repo_id": "news_toolkit",
"token_count": 7453
} | 908 |
export 'find_widget_by_type.dart';
export 'mock_hydrated_storage.dart';
export 'pump_app.dart';
| news_toolkit/flutter_news_example/test/helpers/helpers.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/helpers/helpers.dart",
"repo_id": "news_toolkit",
"token_count": 39
} | 909 |
// ignore_for_file: avoid_redundant_argument_values
import 'package:app_ui/app_ui.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/magic_link_prompt/magic_link_prompt.dart';
import 'package:flutter_news_example/terms_of_service/terms_of_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:form_inputs/form_inputs.dart';
import 'package:mockingjay/mockingjay.dart';
import 'package:user_repository/user_repository.dart';
import '../../helpers/helpers.dart';
class MockUserRepository extends Mock implements UserRepository {}
class MockLoginBloc extends MockBloc<LoginEvent, LoginState>
implements LoginBloc {}
class MockEmail extends Mock implements Email {}
void main() {
const nextButtonKey = Key('loginWithEmailForm_nextButton');
const emailInputKey = Key('loginWithEmailForm_emailInput_textField');
const loginWithEmailFormHeaderTitleKey =
Key('loginWithEmailForm_header_title');
const loginWithEmailFormTermsAndPrivacyPolicyKey =
Key('loginWithEmailForm_terms_and_privacy_policy');
const loginWithEmailFormClearIconKey =
Key('loginWithEmailForm_clearIconButton');
const testEmail = '[email protected]';
const invalidTestEmail = 'test@g';
late LoginBloc loginBloc;
group('LoginWithEmailForm', () {
setUp(() {
loginBloc = MockLoginBloc();
when(() => loginBloc.state).thenReturn(const LoginState());
});
group('adds', () {
testWidgets('LoginEmailChanged when email changes', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.enterText(find.byKey(emailInputKey), testEmail);
verify(() => loginBloc.add(const LoginEmailChanged(testEmail)))
.called(1);
});
testWidgets('SendEmailLinkSubmitted when next button is pressed',
(tester) async {
when(() => loginBloc.state).thenReturn(
const LoginState(valid: true),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.tap(find.byKey(nextButtonKey));
verify(() => loginBloc.add(SendEmailLinkSubmitted())).called(1);
});
testWidgets('LoginEmailChanged when pressed on suffixIcon',
(tester) async {
when(() => loginBloc.state).thenAnswer(
(_) => const LoginState(email: Email.dirty(testEmail)),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.enterText(find.byKey(emailInputKey), testEmail);
await tester.ensureVisible(find.byKey(loginWithEmailFormClearIconKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(loginWithEmailFormClearIconKey));
await tester.pumpAndSettle();
verify(() => loginBloc.add(const LoginEmailChanged(''))).called(1);
});
group('renders', () {
testWidgets('header title', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final headerTitle = find.byKey(loginWithEmailFormHeaderTitleKey);
expect(headerTitle, findsOneWidget);
});
testWidgets('email text field', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final emailTextField = find.byKey(emailInputKey);
expect(emailTextField, findsOneWidget);
});
testWidgets('terms and privacy policy text', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final termsAndPrivacyPolicyText =
find.byKey(loginWithEmailFormTermsAndPrivacyPolicyKey);
expect(termsAndPrivacyPolicyText, findsOneWidget);
});
testWidgets('Login with email failure SnackBar when submission fails',
(tester) async {
whenListen(
loginBloc,
Stream.fromIterable(const <LoginState>[
LoginState(status: FormzSubmissionStatus.inProgress),
LoginState(status: FormzSubmissionStatus.failure)
]),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.pump();
expect(find.byType(SnackBar), findsOneWidget);
});
testWidgets(
'TermsOfServiceModal when tapped on '
'Terms of Use and Privacy Policy text', (tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final richText = tester.widget<RichText>(
find.byKey(loginWithEmailFormTermsAndPrivacyPolicyKey),
);
tapTextSpan(
richText,
'Terms of Use and Privacy Policy',
);
await tester.pumpAndSettle();
expect(find.byType(TermsOfServiceModal), findsOneWidget);
});
testWidgets('disabled next button when status is not validated',
(tester) async {
when(() => loginBloc.state).thenReturn(
const LoginState(valid: false),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final signUpButton = tester.widget<AppButton>(
find.byKey(nextButtonKey),
);
expect(signUpButton.onPressed, null);
});
testWidgets('disabled next button when invalid email is added',
(tester) async {
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.enterText(find.byKey(emailInputKey), invalidTestEmail);
final signUpButton = tester.widget<AppButton>(
find.byKey(nextButtonKey),
);
expect(signUpButton.onPressed, null);
});
testWidgets('enabled next button when status is validated',
(tester) async {
when(() => loginBloc.state).thenReturn(
const LoginState(valid: true),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final signUpButton = tester.widget<AppButton>(
find.byKey(nextButtonKey),
);
expect(signUpButton.onPressed, isNotNull);
});
});
});
group('navigates', () {
testWidgets('to MagicLinkPromptPage when submission is success',
(tester) async {
whenListen(
loginBloc,
Stream.fromIterable(
<LoginState>[
const LoginState(status: FormzSubmissionStatus.inProgress),
const LoginState(status: FormzSubmissionStatus.success)
],
),
initialState: const LoginState(),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
await tester.pump();
expect(find.byType(MagicLinkPromptPage), findsOneWidget);
});
});
group('disables', () {
testWidgets('email text field when status is inProgress', (tester) async {
when(() => loginBloc.state).thenAnswer(
(_) => const LoginState(status: FormzSubmissionStatus.inProgress),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final emailTextField = tester.widget<AppEmailTextField>(
find.byKey(emailInputKey),
);
expect(emailTextField.readOnly, isTrue);
});
testWidgets('clear icon button when status is inProgress',
(tester) async {
when(() => loginBloc.state).thenAnswer(
(_) => const LoginState(status: FormzSubmissionStatus.inProgress),
);
await tester.pumpApp(
BlocProvider.value(
value: loginBloc,
child: const LoginWithEmailForm(),
),
);
final clearIcon = tester.widget<ClearIconButton>(
find.byType(ClearIconButton),
);
expect(clearIcon.onPressed, null);
});
});
});
}
void tapTextSpan(RichText richText, String text) =>
richText.text.visitChildren((visitor) {
if (visitor is TextSpan && visitor.text == text) {
final recognizer = visitor.recognizer;
if (recognizer is TapGestureRecognizer) {
recognizer.onTap!();
}
return false;
}
return true;
});
| news_toolkit/flutter_news_example/test/login/widgets/login_with_email_form_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/login/widgets/login_with_email_form_test.dart",
"repo_id": "news_toolkit",
"token_count": 4446
} | 910 |
import 'package:flutter_news_example/notification_preferences/notification_preferences.dart';
// ignore: lines_longer_than_80_chars
// ignore_for_file: prefer_const_literals_to_create_immutables, prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks/news_blocks.dart';
void main() {
group('NotificationPreferencesState', () {
test('initial has correct status', () {
final initialState = NotificationPreferencesState.initial();
expect(
initialState,
equals(
NotificationPreferencesState(
selectedCategories: {},
status: NotificationPreferencesStatus.initial,
categories: {},
),
),
);
});
test('supports value comparison', () {
expect(
NotificationPreferencesState.initial(),
equals(
NotificationPreferencesState.initial(),
),
);
});
group('copyWith ', () {
test(
'returns same object '
'when no parameters changed', () {
expect(
NotificationPreferencesState.initial().copyWith(),
equals(NotificationPreferencesState.initial()),
);
});
test(
'returns object with updated categories '
'when categories changed', () {
expect(
NotificationPreferencesState.initial().copyWith(
categories: {Category.business},
),
equals(
NotificationPreferencesState(
categories: {Category.business},
selectedCategories: {},
status: NotificationPreferencesStatus.initial,
),
),
);
});
test(
'returns object with updated status '
'when status changed', () {
expect(
NotificationPreferencesState.initial().copyWith(
status: NotificationPreferencesStatus.success,
),
equals(
NotificationPreferencesState(
categories: {},
status: NotificationPreferencesStatus.success,
selectedCategories: {},
),
),
);
});
test(
'returns object with updated selectedCategories '
'when selectedCategories changed', () {
expect(
NotificationPreferencesState.initial().copyWith(
selectedCategories: {Category.business},
),
equals(
NotificationPreferencesState(
categories: {},
status: NotificationPreferencesStatus.initial,
selectedCategories: {Category.business},
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_state_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/notification_preferences/bloc/notification_preferences_state_test.dart",
"repo_id": "news_toolkit",
"token_count": 1214
} | 911 |
// ignore_for_file: prefer_const_constructors
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'package:app_ui/app_ui.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/slideshow/slideshow.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import '../../helpers/helpers.dart';
class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState>
implements ArticleBloc {}
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
void main() {
late ArticleBloc articleBloc;
final slides = List.generate(
4,
(index) => SlideBlock(
caption: 'caption',
description: 'description',
photoCredit: 'photo credit',
imageUrl: 'imageUrl',
),
);
final slideshow = SlideshowBlock(title: 'title', slides: slides);
setUp(() {
articleBloc = MockArticleBloc();
when(() => articleBloc.state).thenReturn(ArticleState.initial());
});
group('renders ShareButton ', () {
testWidgets('when url is not empty', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(uri: Uri(path: 'notEmptyUrl')),
);
await mockNetworkImages(
() async => tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: SlideshowView(
block: slideshow,
),
),
),
);
expect(find.byType(ShareButton), findsOneWidget);
});
testWidgets('that adds ShareRequested on ShareButton tap', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(
uri: Uri(path: 'notEmptyUrl'),
),
);
await mockNetworkImages(
() async => tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: SlideshowView(
block: slideshow,
),
),
),
);
await tester.tap(find.byType(ShareButton));
verify(
() => articleBloc.add(
ShareRequested(
uri: Uri(path: 'notEmptyUrl'),
),
),
).called(1);
});
});
group('does not render ShareButton', () {
testWidgets('when url is empty', (tester) async {
await mockNetworkImages(
() async => tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: SlideshowView(
block: slideshow,
),
),
),
);
expect(find.byType(ShareButton), findsNothing);
});
});
testWidgets('renders ArticleSubscribeButton', (tester) async {
await mockNetworkImages(
() async => tester.pumpApp(
BlocProvider.value(
value: articleBloc,
child: SlideshowView(
block: slideshow,
),
),
),
);
expect(find.byType(ArticleSubscribeButton), findsOneWidget);
});
group('ArticleSubscribeButton', () {
testWidgets('renders AppButton', (tester) async {
await tester.pumpApp(
Row(
children: [ArticleSubscribeButton()],
),
);
expect(find.byType(AppButton), findsOneWidget);
});
});
}
| news_toolkit/flutter_news_example/test/slideshow/view/slideshow_view_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/slideshow/view/slideshow_view_test.dart",
"repo_id": "news_toolkit",
"token_count": 1569
} | 912 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/user_profile/user_profile.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:user_repository/user_repository.dart';
void main() {
group('UserProfileState', () {
test('initial has correct status', () {
expect(
UserProfileState.initial().status,
equals(UserProfileStatus.initial),
);
});
test('supports value comparisons', () {
expect(
UserProfileState.initial(),
equals(UserProfileState.initial()),
);
});
group('copyWith', () {
test(
'returns same object '
'when no properties are passed', () {
expect(
UserProfileState.initial().copyWith(),
equals(UserProfileState.initial()),
);
});
test(
'returns object with updated status '
'when status is passed', () {
expect(
UserProfileState.initial().copyWith(
status: UserProfileStatus.fetchingNotificationsEnabled,
),
equals(
UserProfileState(
user: User.anonymous,
status: UserProfileStatus.fetchingNotificationsEnabled,
),
),
);
});
test(
'returns object with updated notificationsEnabled '
'when notificationsEnabled is passed', () {
expect(
UserProfileState.initial().copyWith(
notificationsEnabled: true,
),
equals(
UserProfileState(
user: User.anonymous,
status: UserProfileStatus.initial,
notificationsEnabled: true,
),
),
);
});
test(
'returns object with updated user '
'when user is passed', () {
expect(
UserProfileState.initial().copyWith(
user: User.anonymous,
),
equals(
UserProfileState(
status: UserProfileStatus.initial,
user: User.anonymous,
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_state_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/user_profile/bloc/user_profile_state_test.dart",
"repo_id": "news_toolkit",
"token_count": 1021
} | 913 |
b96c13d1e9ff3e8ebb9f3647b43c8d51c221e82e
| packages/.ci/flutter_master.version/0 | {
"file_path": "packages/.ci/flutter_master.version",
"repo_id": "packages",
"token_count": 30
} | 914 |
#!/bin/bash
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set -e
# For pre-submit, check for missing or breaking changes that don't have a
# corresponding override label.
# For post-submit, ignore platform interface breaking version changes and
# missing version/CHANGELOG detection since PR-level overrides aren't available
# in post-submit.
if [[ $LUCI_PR == "" ]]; then
.ci/scripts/tool_runner.sh version-check --ignore-platform-interface-breaks
else
.ci/scripts/tool_runner.sh version-check --check-for-missing-changes --pr-labels="$PR_OVERRIDE_LABELS"
fi
| packages/.ci/scripts/check_version.sh/0 | {
"file_path": "packages/.ci/scripts/check_version.sh",
"repo_id": "packages",
"token_count": 196
} | 915 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: analyze repo tools
script: .ci/scripts/analyze_repo_tools.sh
- name: download Dart deps
script: .ci/scripts/tool_runner.sh
args: ["fetch-deps"]
infra_step: true
- name: analyze
script: .ci/scripts/tool_runner.sh
# DO NOT change the custom-analysis argument here without changing the Dart repo.
# See the comment in script/configs/custom_analysis.yaml for details.
args: ["analyze", "--custom-analysis=script/configs/custom_analysis.yaml"]
# Re-run analysis with path-based dependencies to ensure that publishing
# the changes won't break analysis of other packages in the respository
# that depend on it.
- name: analyze - pathified
script: .ci/scripts/analyze_pathified.sh
| packages/.ci/targets/analyze.yaml/0 | {
"file_path": "packages/.ci/targets/analyze.yaml",
"repo_id": "packages",
"token_count": 293
} | 916 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: download Dart and macOS deps
script: .ci/scripts/tool_runner.sh
args: ["fetch-deps", "--macos", "--supporting-target-platforms-only"]
infra_step: true
- name: build examples
script: .ci/scripts/tool_runner.sh
args: ["build-examples", "--macos"]
- name: xcode analyze
script: .ci/scripts/tool_runner.sh
args: ["xcode-analyze", "--macos"]
- name: xcode analyze deprecation
# Ensure we don't accidentally introduce deprecated code.
script: .ci/scripts/tool_runner.sh
args: ["xcode-analyze", "--macos", "--macos-min-version=12.3"]
- name: native test
script: .ci/scripts/tool_runner.sh
args: ["native-test", "--macos"]
- name: drive examples
script: .ci/scripts/tool_runner.sh
args: ["drive-examples", "--macos", "--exclude=script/configs/exclude_integration_macos.yaml"]
| packages/.ci/targets/macos_platform_tests.yaml/0 | {
"file_path": "packages/.ci/targets/macos_platform_tests.yaml",
"repo_id": "packages",
"token_count": 373
} | 917 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'container_transition.dart';
import 'fade_scale_transition.dart';
import 'fade_through_transition.dart';
import 'shared_axis_transition.dart';
void main() {
runApp(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
).copyWith(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: ZoomPageTransitionsBuilder(),
},
),
),
home: _TransitionsHomePage(),
),
);
}
class _TransitionsHomePage extends StatefulWidget {
@override
_TransitionsHomePageState createState() => _TransitionsHomePageState();
}
class _TransitionsHomePageState extends State<_TransitionsHomePage> {
bool _slowAnimations = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Material Transitions')),
body: Column(
children: <Widget>[
Expanded(
child: ListView(
children: <Widget>[
_TransitionListTile(
title: 'Container transform',
subtitle: 'OpenContainer',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return const OpenContainerTransformDemo();
},
),
);
},
),
_TransitionListTile(
title: 'Shared axis',
subtitle: 'SharedAxisTransition',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return const SharedAxisTransitionDemo();
},
),
);
},
),
_TransitionListTile(
title: 'Fade through',
subtitle: 'FadeThroughTransition',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return const FadeThroughTransitionDemo();
},
),
);
},
),
_TransitionListTile(
title: 'Fade',
subtitle: 'FadeScaleTransition',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return const FadeScaleTransitionDemo();
},
),
);
},
),
],
),
),
const Divider(height: 0.0),
SafeArea(
child: SwitchListTile(
value: _slowAnimations,
onChanged: (bool value) async {
setState(() {
_slowAnimations = value;
});
// Wait until the Switch is done animating before actually slowing
// down time.
if (_slowAnimations) {
await Future<void>.delayed(const Duration(milliseconds: 300));
}
timeDilation = _slowAnimations ? 20.0 : 1.0;
},
title: const Text('Slow animations'),
),
),
],
),
);
}
}
class _TransitionListTile extends StatelessWidget {
const _TransitionListTile({
this.onTap,
required this.title,
required this.subtitle,
});
final GestureTapCallback? onTap;
final String title;
final String subtitle;
@override
Widget build(BuildContext context) {
return ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 15.0,
),
leading: Container(
width: 40.0,
height: 40.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
color: Colors.black54,
),
),
child: const Icon(
Icons.play_arrow,
size: 35,
),
),
onTap: onTap,
title: Text(title),
subtitle: Text(subtitle),
);
}
}
| packages/packages/animations/example/lib/main.dart/0 | {
"file_path": "packages/packages/animations/example/lib/main.dart",
"repo_id": "packages",
"token_count": 2606
} | 918 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera/camera.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('translates correctly from platform interface classes', () {
final CameraImageData originalImage = CameraImageData(
format: const CameraImageFormat(ImageFormatGroup.jpeg, raw: 1234),
planes: <CameraImagePlane>[
CameraImagePlane(
bytes: Uint8List.fromList(<int>[1, 2, 3, 4]),
bytesPerRow: 20,
bytesPerPixel: 3,
width: 200,
height: 100,
),
CameraImagePlane(
bytes: Uint8List.fromList(<int>[5, 6, 7, 8]),
bytesPerRow: 18,
bytesPerPixel: 4,
width: 220,
height: 110,
),
],
width: 640,
height: 480,
lensAperture: 2.5,
sensorExposureTime: 5,
sensorSensitivity: 1.3,
);
final CameraImage image = CameraImage.fromPlatformInterface(originalImage);
// Simple values.
expect(image.width, 640);
expect(image.height, 480);
expect(image.lensAperture, 2.5);
expect(image.sensorExposureTime, 5);
expect(image.sensorSensitivity, 1.3);
// Format.
expect(image.format.group, ImageFormatGroup.jpeg);
expect(image.format.raw, 1234);
// Planes.
expect(image.planes.length, originalImage.planes.length);
for (int i = 0; i < image.planes.length; i++) {
expect(
image.planes[i].bytes.length, originalImage.planes[i].bytes.length);
for (int j = 0; j < image.planes[i].bytes.length; j++) {
expect(image.planes[i].bytes[j], originalImage.planes[i].bytes[j]);
}
expect(
image.planes[i].bytesPerPixel, originalImage.planes[i].bytesPerPixel);
expect(image.planes[i].bytesPerRow, originalImage.planes[i].bytesPerRow);
expect(image.planes[i].width, originalImage.planes[i].width);
expect(image.planes[i].height, originalImage.planes[i].height);
}
});
group('legacy constructors', () {
test('$CameraImage can be created', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': 35,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.height, 1);
expect(cameraImage.width, 4);
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
expect(cameraImage.planes.length, 1);
});
test('$CameraImage has ImageFormatGroup.yuv420 for iOS', () {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': 875704438,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
});
test('$CameraImage has ImageFormatGroup.yuv420 for Android', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': 35,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
});
test('$CameraImage has ImageFormatGroup.nv21 for android', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': 17,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.nv21);
});
test('$CameraImage has ImageFormatGroup.bgra8888 for iOS', () {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': 1111970369,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.bgra8888);
});
test('$CameraImage has ImageFormatGroup.unknown', () {
final CameraImage cameraImage =
CameraImage.fromPlatformData(<dynamic, dynamic>{
'format': null,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.unknown);
});
});
}
| packages/packages/camera/camera/test/camera_image_test.dart/0 | {
"file_path": "packages/packages/camera/camera/test/camera_image_test.dart",
"repo_id": "packages",
"token_count": 3105
} | 919 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import android.graphics.Rect;
import android.os.Build.VERSION_CODES;
import android.util.Range;
import android.util.Size;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
/** An interface allowing access to the different characteristics of the device's camera. */
public interface CameraProperties {
/**
* Returns the name (or identifier) of the camera device.
*
* @return String The name of the camera device.
*/
@NonNull
String getCameraName();
/**
* Returns the list of frame rate ranges for @see android.control.aeTargetFpsRange supported by
* this camera device.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_AE_TARGET_FPS_RANGE key.
*
* @return android.util.Range<Integer>[] List of frame rate ranges supported by this camera
* device.
*/
@NonNull
Range<Integer>[] getControlAutoExposureAvailableTargetFpsRanges();
/**
* Returns the maximum and minimum exposure compensation values for @see
* android.control.aeExposureCompensation, in counts of @see android.control.aeCompensationStep,
* that are supported by this camera device.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_AE_COMPENSATION_RANGE key.
*
* @return android.util.Range<Integer> Maximum and minimum exposure compensation supported by this
* camera device.
*/
@NonNull
Range<Integer> getControlAutoExposureCompensationRange();
/**
* Returns the smallest step by which the exposure compensation can be changed.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_AE_COMPENSATION_STEP key.
*
* @return double Smallest step by which the exposure compensation can be changed.
*/
double getControlAutoExposureCompensationStep();
/**
* Returns a list of auto-focus modes for @see android.control.afMode that are supported by this
* camera device.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_AF_AVAILABLE_MODES key.
*
* @return int[] List of auto-focus modes supported by this camera device.
*/
@NonNull
int[] getControlAutoFocusAvailableModes();
/**
* Returns the maximum number of metering regions that can be used by the auto-exposure routine.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_MAX_REGIONS_AE key.
*
* @return Integer Maximum number of metering regions that can be used by the auto-exposure
* routine.
*/
@NonNull
Integer getControlMaxRegionsAutoExposure();
/**
* Returns the maximum number of metering regions that can be used by the auto-focus routine.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_MAX_REGIONS_AF key.
*
* @return Integer Maximum number of metering regions that can be used by the auto-focus routine.
*/
@NonNull
Integer getControlMaxRegionsAutoFocus();
/**
* Returns a list of distortion correction modes for @see android.distortionCorrection.mode that
* are supported by this camera device.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES key.
*
* @return int[] List of distortion correction modes supported by this camera device.
*/
@RequiresApi(api = VERSION_CODES.P)
@Nullable
int[] getDistortionCorrectionAvailableModes();
/**
* Returns whether this camera device has a flash unit.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#FLASH_INFO_AVAILABLE key.
*
* @return Boolean Whether this camera device has a flash unit.
*/
@NonNull
Boolean getFlashInfoAvailable();
/**
* Returns the direction the camera faces relative to device screen.
*
* <p><string>Possible values:</string>
*
* <ul>
* <li>@see android.hardware.camera2.CameraMetadata.LENS_FACING_FRONT
* <li>@see android.hardware.camera2.CameraMetadata.LENS_FACING_BACK
* <li>@see android.hardware.camera2.CameraMetadata.LENS_FACING_EXTERNAL
* </ul>
*
* <p>By default maps to the @see android.hardware.camera2.CameraCharacteristics.LENS_FACING key.
*
* @return int Direction the camera faces relative to device screen.
*/
int getLensFacing();
/**
* Returns the shortest distance from front most surface of the lens that can be brought into
* sharp focus.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE key.
*
* @return Float Shortest distance from front most surface of the lens that can be brought into
* sharp focus.
*/
@Nullable
Float getLensInfoMinimumFocusDistance();
/**
* Returns the maximum ratio between both active area width and crop region width, and active area
* height and crop region height, for @see android.scaler.cropRegion.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM key.
*
* @return Float Maximum ratio between both active area width and crop region width, and active
* area height and crop region height.
*/
@NonNull
Float getScalerAvailableMaxDigitalZoom();
/**
* Returns the minimum ratio between the default camera zoom setting and all of the available
* zoom.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE key's lower value.
*
* @return Float Minimum ratio between the default zoom ratio and the minimum possible zoom.
*/
@Nullable
@RequiresApi(api = VERSION_CODES.R)
Float getScalerMinZoomRatio();
/**
* Returns the maximum ratio between the default camera zoom setting and all of the available
* zoom.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE key's upper value.
*
* @return Float Maximum ratio between the default zoom ratio and the maximum possible zoom.
*/
@Nullable
@RequiresApi(api = VERSION_CODES.R)
Float getScalerMaxZoomRatio();
/**
* Returns the area of the image sensor which corresponds to active pixels after any geometric
* distortion correction has been applied.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE key.
*
* @return android.graphics.Rect area of the image sensor which corresponds to active pixels after
* any geometric distortion correction has been applied.
*/
@NonNull
Rect getSensorInfoActiveArraySize();
/**
* Returns the dimensions of the full pixel array, possibly including black calibration pixels.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#SENSOR_INFO_PIXEL_ARRAY_SIZE key.
*
* @return android.util.Size Dimensions of the full pixel array, possibly including black
* calibration pixels.
*/
@NonNull
Size getSensorInfoPixelArraySize();
/**
* Returns the area of the image sensor which corresponds to active pixels prior to the
* application of any geometric distortion correction.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
* key.
*
* @return android.graphics.Rect Area of the image sensor which corresponds to active pixels prior
* to the application of any geometric distortion correction.
*/
@RequiresApi(api = VERSION_CODES.M)
@NonNull
Rect getSensorInfoPreCorrectionActiveArraySize();
/**
* Returns the clockwise angle through which the output image needs to be rotated to be upright on
* the device screen in its native orientation.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#SENSOR_ORIENTATION key.
*
* @return int Clockwise angle through which the output image needs to be rotated to be upright on
* the device screen in its native orientation.
*/
int getSensorOrientation();
/**
* Returns a level which generally classifies the overall set of the camera device functionality.
*
* <p><strong>Possible values:</strong>
*
* <ul>
* <li>@see android.hardware.camera2.CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY
* <li>@see android.hardware.camera2.CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
* <li>@see android.hardware.camera2.CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
* <li>@see android.hardware.camera2.CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEVEL_3
* <li>@see android.hardware.camera2.CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL
* </ul>
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL key.
*
* @return int Level which generally classifies the overall set of the camera device
* functionality.
*/
int getHardwareLevel();
/**
* Returns a list of noise reduction modes for @see android.noiseReduction.mode that are supported
* by this camera device.
*
* <p>By default maps to the @see
* android.hardware.camera2.CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES
* key.
*
* @return int[] List of noise reduction modes that are supported by this camera device.
*/
@NonNull
int[] getAvailableNoiseReductionModes();
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraProperties.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraProperties.java",
"repo_id": "packages",
"token_count": 3146
} | 920 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.autofocus;
import android.annotation.SuppressLint;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls the auto focus configuration on the {@see anddroid.hardware.camera2} API. */
public class AutoFocusFeature extends CameraFeature<FocusMode> {
@NonNull private FocusMode currentSetting = FocusMode.auto;
// When switching recording modes this feature is re-created with the appropriate setting here.
private final boolean recordingVideo;
/**
* Creates a new instance of the {@see AutoFocusFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
* @param recordingVideo Indicates whether the camera is currently recording video.
*/
public AutoFocusFeature(@NonNull CameraProperties cameraProperties, boolean recordingVideo) {
super(cameraProperties);
this.recordingVideo = recordingVideo;
}
@NonNull
@Override
public String getDebugName() {
return "AutoFocusFeature";
}
@NonNull
@SuppressLint("KotlinPropertyAccess")
@Override
public FocusMode getValue() {
return currentSetting;
}
@Override
public void setValue(@NonNull FocusMode value) {
this.currentSetting = value;
}
@Override
public boolean checkIsSupported() {
int[] modes = cameraProperties.getControlAutoFocusAvailableModes();
final Float minFocus = cameraProperties.getLensInfoMinimumFocusDistance();
// Check if the focal length of the lens is fixed. If the minimum focus distance == 0, then the
// focal length is fixed. The minimum focus distance can be null on some devices: https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE
boolean isFixedLength = minFocus == null || minFocus == 0;
return !isFixedLength
&& !(modes.length == 0
|| (modes.length == 1 && modes[0] == CameraCharacteristics.CONTROL_AF_MODE_OFF));
}
@Override
public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
switch (currentSetting) {
case locked:
// When locking the auto-focus the camera device should do a one-time focus and afterwards
// set the auto-focus to idle. This is accomplished by setting the CONTROL_AF_MODE to
// CONTROL_AF_MODE_AUTO.
requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
break;
case auto:
requestBuilder.set(
CaptureRequest.CONTROL_AF_MODE,
recordingVideo
? CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO
: CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
break;
default:
break;
}
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeature.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeature.java",
"repo_id": "packages",
"token_count": 1028
} | 921 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.zoomlevel;
import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.hardware.camera2.CaptureRequest;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.SdkCapabilityChecker;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls the zoom configuration on the {@link android.hardware.camera2} API. */
public class ZoomLevelFeature extends CameraFeature<Float> {
private static final Float DEFAULT_ZOOM_LEVEL = 1.0f;
private final boolean hasSupport;
private final Rect sensorArraySize;
@NonNull private Float currentSetting = DEFAULT_ZOOM_LEVEL;
private Float minimumZoomLevel = currentSetting;
private final Float maximumZoomLevel;
/**
* Creates a new instance of the {@link ZoomLevelFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
*/
public ZoomLevelFeature(@NonNull CameraProperties cameraProperties) {
super(cameraProperties);
sensorArraySize = cameraProperties.getSensorInfoActiveArraySize();
if (sensorArraySize == null) {
maximumZoomLevel = minimumZoomLevel;
hasSupport = false;
return;
}
// On Android 11+ CONTROL_ZOOM_RATIO_RANGE should be use to get the zoom ratio directly as minimum zoom does not have to be 1.0f.
if (SdkCapabilityChecker.supportsZoomRatio()) {
minimumZoomLevel = cameraProperties.getScalerMinZoomRatio();
maximumZoomLevel = cameraProperties.getScalerMaxZoomRatio();
} else {
minimumZoomLevel = DEFAULT_ZOOM_LEVEL;
Float maxDigitalZoom = cameraProperties.getScalerAvailableMaxDigitalZoom();
maximumZoomLevel =
((maxDigitalZoom == null) || (maxDigitalZoom < minimumZoomLevel))
? minimumZoomLevel
: maxDigitalZoom;
}
hasSupport = (Float.compare(maximumZoomLevel, minimumZoomLevel) > 0);
}
@NonNull
@Override
public String getDebugName() {
return "ZoomLevelFeature";
}
@SuppressLint("KotlinPropertyAccess")
@NonNull
@Override
public Float getValue() {
return currentSetting;
}
@Override
public void setValue(@NonNull Float value) {
currentSetting = value;
}
@Override
public boolean checkIsSupported() {
return hasSupport;
}
@Override
public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
// On Android 11+ CONTROL_ZOOM_RATIO can be set to a zoom ratio and the camera feed will compute
// how to zoom on its own accounting for multiple logical cameras.
// Prior the image cropping window must be calculated and set manually.
if (SdkCapabilityChecker.supportsZoomRatio()) {
requestBuilder.set(
CaptureRequest.CONTROL_ZOOM_RATIO,
ZoomUtils.computeZoomRatio(currentSetting, minimumZoomLevel, maximumZoomLevel));
} else {
final Rect computedZoom =
ZoomUtils.computeZoomRect(
currentSetting, sensorArraySize, minimumZoomLevel, maximumZoomLevel);
requestBuilder.set(CaptureRequest.SCALER_CROP_REGION, computedZoom);
}
}
/**
* Gets the minimum supported zoom level.
*
* @return The minimum zoom level.
*/
public float getMinimumZoomLevel() {
return minimumZoomLevel;
}
/**
* Gets the maximum supported zoom level.
*
* @return The maximum zoom level.
*/
public float getMaximumZoomLevel() {
return maximumZoomLevel;
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeature.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeature.java",
"repo_id": "packages",
"token_count": 1250
} | 922 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.fpsrange;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import android.util.Range;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.DeviceInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class FpsRangeFeaturePixel4aTest {
@Test
public void ctor_shouldInitializeFpsRangeWith30WhenDeviceIsPixel4a() {
DeviceInfo.BRAND = "google";
DeviceInfo.MODEL = "Pixel 4a";
FpsRangeFeature fpsRangeFeature = new FpsRangeFeature(mock(CameraProperties.class));
Range<Integer> range = fpsRangeFeature.getValue();
assertEquals(30, (int) range.getLower());
assertEquals(30, (int) range.getUpper());
}
}
| packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeaturePixel4aTest.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeaturePixel4aTest.java",
"repo_id": "packages",
"token_count": 333
} | 923 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/camera/camera_android/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/camera/camera_android/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 924 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraFlutterApi;
public class CameraFlutterApiImpl extends CameraFlutterApi {
private final @NonNull InstanceManager instanceManager;
public CameraFlutterApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
super(binaryMessenger);
this.instanceManager = instanceManager;
}
void create(Camera camera, Reply<Void> reply) {
create(instanceManager.addHostCreatedInstance(camera), reply);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java",
"repo_id": "packages",
"token_count": 249
} | 925 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.FocusMeteringAction;
import androidx.camera.core.MeteringPoint;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringActionHostApi;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Host API implementation for {@link FocusMeteringAction}.
*
* <p>This class may handle instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class FocusMeteringActionHostApiImpl implements FocusMeteringActionHostApi {
private final InstanceManager instanceManager;
private final FocusMeteringActionProxy proxy;
/** Proxy for constructor of {@link FocusMeteringAction}. */
@VisibleForTesting
public static class FocusMeteringActionProxy {
/** Creates an instance of {@link FocusMeteringAction}. */
public @NonNull FocusMeteringAction create(
@NonNull List<MeteringPoint> meteringPoints,
@NonNull List<Integer> meteringPointModes,
@Nullable Boolean disableAutoCancel) {
if (meteringPoints.size() >= 1 && meteringPoints.size() != meteringPointModes.size()) {
throw new IllegalArgumentException(
"One metering point must be specified and the number of specified metering points must match the number of specified metering point modes.");
}
FocusMeteringAction.Builder focusMeteringActionBuilder;
// Create builder to potentially add more MeteringPoints to.
MeteringPoint firstMeteringPoint = meteringPoints.get(0);
Integer firstMeteringPointMode = meteringPointModes.get(0);
if (firstMeteringPointMode == null) {
focusMeteringActionBuilder = getFocusMeteringActionBuilder(firstMeteringPoint);
} else {
focusMeteringActionBuilder =
getFocusMeteringActionBuilder(firstMeteringPoint, firstMeteringPointMode);
}
// Add any additional metering points in order as specified by input lists.
for (int i = 1; i < meteringPoints.size(); i++) {
MeteringPoint meteringPoint = meteringPoints.get(i);
Integer meteringMode = meteringPointModes.get(i);
if (meteringMode == null) {
focusMeteringActionBuilder.addPoint(meteringPoint);
} else {
focusMeteringActionBuilder.addPoint(meteringPoint, meteringMode);
}
}
if (disableAutoCancel != null && disableAutoCancel == true) {
focusMeteringActionBuilder.disableAutoCancel();
}
return focusMeteringActionBuilder.build();
}
@VisibleForTesting
@NonNull
public FocusMeteringAction.Builder getFocusMeteringActionBuilder(
@NonNull MeteringPoint meteringPoint) {
return new FocusMeteringAction.Builder(meteringPoint);
}
@VisibleForTesting
@NonNull
public FocusMeteringAction.Builder getFocusMeteringActionBuilder(
@NonNull MeteringPoint meteringPoint, int meteringMode) {
return new FocusMeteringAction.Builder(meteringPoint, meteringMode);
}
}
/**
* Constructs a {@link FocusMeteringActionHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public FocusMeteringActionHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new FocusMeteringActionProxy());
}
/**
* Constructs a {@link FocusMeteringActionHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor of {@link FocusMeteringAction}
*/
FocusMeteringActionHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull FocusMeteringActionProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
@Override
public void create(
@NonNull Long identifier,
@NonNull List<MeteringPointInfo> meteringPointInfos,
@Nullable Boolean disableAutoCancel) {
final List<MeteringPoint> meteringPoints = new ArrayList<MeteringPoint>();
final List<Integer> meteringPointModes = new ArrayList<Integer>();
for (MeteringPointInfo meteringPointInfo : meteringPointInfos) {
meteringPoints.add(instanceManager.getInstance(meteringPointInfo.getMeteringPointId()));
Long meteringPointMode = meteringPointInfo.getMeteringMode();
meteringPointModes.add(meteringPointMode == null ? null : meteringPointMode.intValue());
}
instanceManager.addDartCreatedInstance(
proxy.create(meteringPoints, meteringPointModes, disableAutoCancel), identifier);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java",
"repo_id": "packages",
"token_count": 1594
} | 926 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.video.PendingRecording;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoRecordEvent;
import androidx.core.content.ContextCompat;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PendingRecordingHostApi;
import java.util.Objects;
import java.util.concurrent.Executor;
public class PendingRecordingHostApiImpl implements PendingRecordingHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
@Nullable private Context context;
@VisibleForTesting @NonNull public CameraXProxy cameraXProxy = new CameraXProxy();
@VisibleForTesting SystemServicesFlutterApiImpl systemServicesFlutterApi;
@VisibleForTesting RecordingFlutterApiImpl recordingFlutterApi;
public PendingRecordingHostApiImpl(
@NonNull BinaryMessenger binaryMessenger,
@NonNull InstanceManager instanceManager,
@Nullable Context context) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
this.context = context;
systemServicesFlutterApi = cameraXProxy.createSystemServicesFlutterApiImpl(binaryMessenger);
recordingFlutterApi = new RecordingFlutterApiImpl(binaryMessenger, instanceManager);
}
/** Sets the context, which is used to get the {@link Executor} needed to start the recording. */
public void setContext(@Nullable Context context) {
this.context = context;
}
/**
* Starts the given {@link PendingRecording}, creating a new {@link Recording}. The recording is
* then added to the instance manager and we return the corresponding identifier.
*
* @param identifier An identifier corresponding to a PendingRecording.
*/
@NonNull
@Override
public Long start(@NonNull Long identifier) {
PendingRecording pendingRecording = getPendingRecordingFromInstanceId(identifier);
Recording recording =
pendingRecording.start(this.getExecutor(), event -> handleVideoRecordEvent(event));
recordingFlutterApi.create(recording, reply -> {});
return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(recording));
}
@Nullable
@VisibleForTesting
public Executor getExecutor() {
if (context == null) {
throw new IllegalStateException("Context must be set to get an executor to start recording.");
}
return ContextCompat.getMainExecutor(context);
}
/**
* Handles {@link VideoRecordEvent}s that come in during video recording. Sends any errors
* encountered using {@link SystemServicesFlutterApiImpl}.
*/
@VisibleForTesting
public void handleVideoRecordEvent(@NonNull VideoRecordEvent event) {
if (event instanceof VideoRecordEvent.Finalize) {
VideoRecordEvent.Finalize castedEvent = (VideoRecordEvent.Finalize) event;
if (castedEvent.hasError()) {
String cameraErrorMessage;
if (castedEvent.getCause() != null) {
cameraErrorMessage = castedEvent.getCause().toString();
} else {
cameraErrorMessage =
"Error code " + castedEvent.getError() + ": An error occurred while recording video.";
}
systemServicesFlutterApi.sendCameraError(cameraErrorMessage, reply -> {});
}
}
}
private PendingRecording getPendingRecordingFromInstanceId(Long instanceId) {
return (PendingRecording) Objects.requireNonNull(instanceManager.getInstance(instanceId));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java",
"repo_id": "packages",
"token_count": 1166
} | 927 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.camera.video.Recorder;
import androidx.camera.video.VideoCapture;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoCaptureHostApi;
import java.util.Objects;
public class VideoCaptureHostApiImpl implements VideoCaptureHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
public VideoCaptureHostApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
@Override
@NonNull
public Long withOutput(@NonNull Long videoOutputId) {
Recorder recorder =
(Recorder) Objects.requireNonNull(instanceManager.getInstance(videoOutputId));
VideoCapture<Recorder> videoCapture = VideoCapture.withOutput(recorder);
final VideoCaptureFlutterApiImpl videoCaptureFlutterApi =
getVideoCaptureFlutterApiImpl(binaryMessenger, instanceManager);
videoCaptureFlutterApi.create(videoCapture, result -> {});
return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(videoCapture));
}
@Override
@NonNull
public Long getOutput(@NonNull Long identifier) {
VideoCapture<Recorder> videoCapture = getVideoCaptureInstance(identifier);
Recorder recorder = videoCapture.getOutput();
return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(recorder));
}
@VisibleForTesting
@NonNull
public VideoCaptureFlutterApiImpl getVideoCaptureFlutterApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
return new VideoCaptureFlutterApiImpl(binaryMessenger, instanceManager);
}
/** Dynamically sets the target rotation of the {@link VideoCapture}. */
@Override
public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) {
VideoCapture<Recorder> videoCapture = getVideoCaptureInstance(identifier);
videoCapture.setTargetRotation(rotation.intValue());
}
/**
* Retrieves the {@link VideoCapture} instance associated with the specified {@code identifier}.
*/
private VideoCapture<Recorder> getVideoCaptureInstance(@NonNull Long identifier) {
return Objects.requireNonNull(instanceManager.getInstance(identifier));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java",
"repo_id": "packages",
"token_count": 759
} | 928 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.util.Range;
import android.util.Rational;
import androidx.camera.core.ExposureState;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureCompensationRange;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class ExposureStateTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public ExposureState mockExposureState;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Config(sdk = 21)
@Test
public void create_makesExpectedCallToCreateInstanceOnDartSide() {
// SDK version configured because ExposureState requires Android 21.
ExposureStateFlutterApiImpl exposureStateFlutterApiImpl =
spy(new ExposureStateFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
final int minExposureCompensation = 0;
final int maxExposureCompensation = 1;
Range<Integer> testExposueCompensationRange =
new Range<Integer>(minExposureCompensation, maxExposureCompensation);
Rational textExposureCompensationStep = new Rational(1, 5); // Makes expected Double value 0.2.
when(mockExposureState.getExposureCompensationRange()).thenReturn(testExposueCompensationRange);
when(mockExposureState.getExposureCompensationStep()).thenReturn(textExposureCompensationStep);
final ArgumentCaptor<ExposureCompensationRange> exposureCompensationRangeCaptor =
ArgumentCaptor.forClass(ExposureCompensationRange.class);
exposureStateFlutterApiImpl.create(mockExposureState, reply -> {});
final long identifier =
Objects.requireNonNull(
testInstanceManager.getIdentifierForStrongReference(mockExposureState));
verify(exposureStateFlutterApiImpl)
.create(eq(identifier), exposureCompensationRangeCaptor.capture(), eq(0.2), any());
ExposureCompensationRange exposureCompensationRange =
exposureCompensationRangeCaptor.getValue();
assertEquals(
exposureCompensationRange.getMinCompensation().intValue(), minExposureCompensation);
assertEquals(
exposureCompensationRange.getMaxCompensation().intValue(), maxExposureCompensation);
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java",
"repo_id": "packages",
"token_count": 1036
} | 929 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.lifecycle.Lifecycle.Event;
import androidx.lifecycle.LifecycleRegistry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class ProxyLifecycleProviderTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock Activity activity;
@Mock Application application;
@Mock LifecycleRegistry mockLifecycleRegistry;
private final int testHashCode = 27;
@Before
public void setUp() {
when(activity.getApplication()).thenReturn(application);
}
@Test
public void onActivityCreated_handlesOnCreateEvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
Bundle mockBundle = mock(Bundle.class);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityCreated(activity, mockBundle);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_CREATE);
}
@Test
public void onActivityStarted_handlesOnActivityStartedEvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityStarted(activity);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_START);
}
@Test
public void onActivityResumed_handlesOnActivityResumedEvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityResumed(activity);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_RESUME);
}
@Test
public void onActivityPaused_handlesOnActivityPausedEvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityPaused(activity);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_PAUSE);
}
@Test
public void onActivityStopped_handlesOnActivityStoppedEvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityStopped(activity);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_STOP);
}
@Test
public void onActivityDestroyed_handlesOnActivityDestroyed() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivityDestroyed(activity);
verify(mockLifecycleRegistry).handleLifecycleEvent(Event.ON_DESTROY);
}
@Test
public void onActivitySaveInstanceState_doesNotHandleLifecycleEvvent() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
Bundle mockBundle = mock(Bundle.class);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
proxyLifecycleProvider.onActivitySaveInstanceState(activity, mockBundle);
verifyNoInteractions(mockLifecycleRegistry);
}
@Test
public void getLifecycle_returnsExpectedLifecycle() {
ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity);
proxyLifecycleProvider.lifecycle = mockLifecycleRegistry;
assertEquals(proxyLifecycleProvider.getLifecycle(), mockLifecycleRegistry);
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProxyLifecycleProviderTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProxyLifecycleProviderTest.java",
"repo_id": "packages",
"token_count": 1284
} | 930 |
// 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:io';
import 'dart:ui';
import 'package:camera_android_camerax/camera_android_camerax.dart';
import 'package:camera_android_camerax_example/camera_controller.dart';
import 'package:camera_android_camerax_example/camera_image.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
CameraPlatform.instance = AndroidCameraCameraX();
});
final Map<ResolutionPreset, Size> presetExpectedSizes =
<ResolutionPreset, Size>{
ResolutionPreset.low: const Size(240, 320),
ResolutionPreset.medium: const Size(480, 720),
ResolutionPreset.high: const Size(720, 1280),
ResolutionPreset.veryHigh: const Size(1080, 1920),
ResolutionPreset.ultraHigh: const Size(2160, 3840),
// Don't bother checking for max here since it could be anything.
};
/// Verify that [actual] has dimensions that are at most as large as
/// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns
/// whether the dimensions exactly match.
bool assertExpectedDimensions(Size expectedSize, Size actual) {
expect(actual.shortestSide, lessThanOrEqualTo(expectedSize.shortestSide));
expect(actual.longestSide, lessThanOrEqualTo(expectedSize.longestSide));
return actual.shortestSide == expectedSize.shortestSide &&
actual.longestSide == expectedSize.longestSide;
}
// This tests that the capture is no bigger than the preset, since we have
// automatic code to fall back to smaller sizes when we need to. Returns
// whether the image is exactly the desired resolution.
Future<bool> testCaptureImageResolution(
CameraController controller, ResolutionPreset preset) async {
final Size expectedSize = presetExpectedSizes[preset]!;
// Take Picture
final XFile file = await controller.takePicture();
// Load picture
final File fileImage = File(file.path);
final Image image = await decodeImageFromList(fileImage.readAsBytesSync());
// Verify image dimensions are as expected
expect(image, isNotNull);
return assertExpectedDimensions(
expectedSize, Size(image.height.toDouble(), image.width.toDouble()));
}
testWidgets('availableCameras only supports valid back or front cameras',
(WidgetTester tester) async {
final List<CameraDescription> availableCameras =
await CameraPlatform.instance.availableCameras();
for (final CameraDescription cameraDescription in availableCameras) {
expect(
cameraDescription.lensDirection, isNot(CameraLensDirection.external));
expect(cameraDescription.sensorOrientation, anyOf(0, 90, 180, 270));
}
});
testWidgets('Capture specific image resolutions',
(WidgetTester tester) async {
final List<CameraDescription> cameras =
await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final CameraDescription cameraDescription in cameras) {
bool previousPresetExactlySupported = true;
for (final MapEntry<ResolutionPreset, Size> preset
in presetExpectedSizes.entries) {
final CameraController controller =
CameraController(cameraDescription, preset.key);
await controller.initialize();
final bool presetExactlySupported =
await testCaptureImageResolution(controller, preset.key);
// Ensures that if a lower resolution was used for previous (lower)
// resolution preset, then the current (higher) preset also is adjusted,
// as it demands a hgher resolution.
expect(
previousPresetExactlySupported || !presetExactlySupported, isTrue,
reason:
'The camera took higher resolution pictures at a lower resolution.');
previousPresetExactlySupported = presetExactlySupported;
await controller.dispose();
}
}
});
testWidgets('Preview takes expected resolution from preset',
(WidgetTester tester) async {
final List<CameraDescription> cameras =
await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final CameraDescription cameraDescription in cameras) {
bool previousPresetExactlySupported = true;
for (final MapEntry<ResolutionPreset, Size> preset
in presetExpectedSizes.entries) {
final CameraController controller =
CameraController(cameraDescription, preset.key);
await controller.initialize();
while (controller.value.previewSize == null) {
// Wait for preview size to update.
}
final bool presetExactlySupported = assertExpectedDimensions(
preset.value, controller.value.previewSize!);
// Ensures that if a lower resolution was used for previous (lower)
// resolution preset, then the current (higher) preset also is adjusted,
// as it demands a hgher resolution.
expect(
previousPresetExactlySupported || !presetExactlySupported, isTrue,
reason: 'The preview has a lower resolution than that specified.');
previousPresetExactlySupported = presetExactlySupported;
await controller.dispose();
}
}
});
testWidgets('Images from streaming have expected resolution from preset',
(WidgetTester tester) async {
final List<CameraDescription> cameras =
await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
return;
}
for (final CameraDescription cameraDescription in cameras) {
bool previousPresetExactlySupported = true;
for (final MapEntry<ResolutionPreset, Size> preset
in presetExpectedSizes.entries) {
final CameraController controller =
CameraController(cameraDescription, preset.key);
final Completer<CameraImage> imageCompleter = Completer<CameraImage>();
await controller.initialize();
await controller.startImageStream((CameraImage image) {
imageCompleter.complete(image);
controller.stopImageStream();
});
final CameraImage image = await imageCompleter.future;
final bool presetExactlySupported = assertExpectedDimensions(
preset.value,
Size(image.height.toDouble(), image.width.toDouble()));
// Ensures that if a lower resolution was used for previous (lower)
// resolution preset, then the current (higher) preset also is adjusted,
// as it demands a hgher resolution.
expect(
previousPresetExactlySupported || !presetExactlySupported, isTrue,
reason: 'The preview has a lower resolution than that specified.');
previousPresetExactlySupported = presetExactlySupported;
await controller.dispose();
}
}
});
}
| packages/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart",
"repo_id": "packages",
"token_count": 2412
} | 931 |
// 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' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camera_state.dart';
import 'camerax_library.g.dart';
import 'exposure_state.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'live_data.dart';
import 'zoom_state.dart';
/// The metadata of a camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo.
@immutable
class CameraInfo extends JavaObject {
/// Constructs a [CameraInfo] that is not automatically attached to a native object.
CameraInfo.detached(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _CameraInfoHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final _CameraInfoHostApiImpl _api;
/// Gets sensor orientation degrees of the camera.
Future<int> getSensorRotationDegrees() =>
_api.getSensorRotationDegreesFromInstance(this);
/// Starts listening for the camera closing.
Future<LiveData<CameraState>> getCameraState() =>
_api.getCameraStateFromInstance(this);
/// Gets the exposure state of the camera.
Future<ExposureState> getExposureState() =>
_api.getExposureStateFromInstance(this);
/// Gets the live zoom state of the camera.
Future<LiveData<ZoomState>> getZoomState() =>
_api.getZoomStateFromInstance(this);
}
/// Host API implementation of [CameraInfo].
class _CameraInfoHostApiImpl extends CameraInfoHostApi {
/// Constructs a [_CameraInfoHostApiImpl].
_CameraInfoHostApiImpl(
{super.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Gets sensor orientation degrees of the specified [CameraInfo] instance.
Future<int> getSensorRotationDegreesFromInstance(
CameraInfo instance,
) async {
final int sensorRotationDegrees = await getSensorRotationDegrees(
instanceManager.getIdentifier(instance)!);
return sensorRotationDegrees;
}
/// Gets the [LiveData<CameraState>] that represents the state of the camera
/// to which the CameraInfo [instance] pertains.
Future<LiveData<CameraState>> getCameraStateFromInstance(
CameraInfo instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final int liveCameraStateId = await getCameraState(identifier!);
final LiveData<CameraState> liveCameraState =
instanceManager.getInstanceWithWeakReference<LiveData<CameraState>>(
liveCameraStateId)!;
return liveCameraState;
}
/// Gets the [ExposureState] of the specified [CameraInfo] instance.
Future<ExposureState> getExposureStateFromInstance(
CameraInfo instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final int exposureStateIdentifier = await getExposureState(identifier!);
return instanceManager
.getInstanceWithWeakReference<ExposureState>(exposureStateIdentifier)!;
}
/// Gets the [LiveData<ZoomState>] of the specified [CameraInfo] instance.
Future<LiveData<ZoomState>> getZoomStateFromInstance(
CameraInfo instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final int zoomStateIdentifier = await getZoomState(identifier!);
return instanceManager.getInstanceWithWeakReference<LiveData<ZoomState>>(
zoomStateIdentifier)!;
}
}
/// Flutter API implementation of [CameraInfo].
class CameraInfoFlutterApiImpl extends CameraInfoFlutterApi {
/// Constructs a [CameraInfoFlutterApiImpl].
///
/// If [binaryMessenger] is null, the default [BinaryMessenger] will be used,
/// which routes to the host platform.
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created. If left null, it
/// will default to the global instance defined in [JavaObject].
CameraInfoFlutterApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : _binaryMessenger = binaryMessenger,
_instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? _binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager _instanceManager;
@override
void create(int identifier) {
_instanceManager.addHostCreatedInstance(
CameraInfo.detached(
binaryMessenger: _binaryMessenger, instanceManager: _instanceManager),
identifier,
onCopy: (CameraInfo original) {
return CameraInfo.detached(
binaryMessenger: _binaryMessenger,
instanceManager: _instanceManager);
},
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/camera_info.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/camera_info.dart",
"repo_id": "packages",
"token_count": 1644
} | 932 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show WidgetsFlutterBinding;
import 'camerax_library.g.dart';
import 'instance_manager.dart';
/// Root of the Java class hierarchy.
///
/// See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html.
@immutable
class JavaObject {
/// Constructs a [JavaObject] without creating the associated Java object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
JavaObject.detached({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : _api = JavaObjectHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
/// Global instance of [InstanceManager].
static final InstanceManager globalInstanceManager = _initInstanceManager();
static InstanceManager _initInstanceManager() {
WidgetsFlutterBinding.ensureInitialized();
// Clears the native `InstanceManager` on initial use of the Dart one.
InstanceManagerHostApi().clear();
return InstanceManager(
onWeakReferenceRemoved: (int identifier) {
JavaObjectHostApiImpl().dispose(identifier);
},
);
}
/// Release the weak reference to the [instance].
static void dispose(JavaObject instance) {
instance._api.instanceManager.removeWeakReference(instance);
}
// ignore: unused_field
final JavaObjectHostApiImpl _api;
}
/// Handles methods calls to the native Java Object class.
class JavaObjectHostApiImpl extends JavaObjectHostApi {
/// Constructs a [JavaObjectHostApiImpl].
JavaObjectHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
}
/// Handles callbacks methods for the native Java Object class.
class JavaObjectFlutterApiImpl implements JavaObjectFlutterApi {
/// Constructs a [JavaObjectFlutterApiImpl].
JavaObjectFlutterApiImpl({InstanceManager? instanceManager})
: instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void dispose(int identifier) {
instanceManager.remove(identifier);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/java_object.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/java_object.dart",
"repo_id": "packages",
"token_count": 837
} | 933 |
// 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:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'recorder.dart';
import 'use_case.dart';
/// Dart wrapping of CameraX VideoCapture class.
///
/// See https://developer.android.com/reference/androidx/camera/video/VideoCapture.
@immutable
class VideoCapture extends UseCase {
/// Creates a [VideoCapture] that is not automatically attached to a native
/// object.
VideoCapture.detached(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = VideoCaptureHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final VideoCaptureHostApiImpl _api;
/// Creates a [VideoCapture] associated with the given [Recorder].
static Future<VideoCapture> withOutput(Recorder recorder,
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) {
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
final VideoCaptureHostApiImpl api = VideoCaptureHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
return api.withOutputFromInstance(recorder);
}
/// Dynamically sets the target rotation of this instance.
///
/// [rotation] should be specified in terms of one of the [Surface]
/// rotation constants that represents the counter-clockwise degrees of
/// rotation relative to [DeviceOrientation.portraitUp].
Future<void> setTargetRotation(int rotation) =>
_api.setTargetRotationFromInstances(this, rotation);
/// Gets the [Recorder] associated with this VideoCapture.
Future<Recorder> getOutput() {
return _api.getOutputFromInstance(this);
}
}
/// Host API implementation of [VideoCapture].
class VideoCaptureHostApiImpl extends VideoCaptureHostApi {
/// Constructs a [VideoCaptureHostApiImpl].
VideoCaptureHostApiImpl(
{this.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Creates a [VideoCapture] associated with the provided [Recorder] instance.
Future<VideoCapture> withOutputFromInstance(Recorder recorder) async {
int? identifier = instanceManager.getIdentifier(recorder);
identifier ??= instanceManager.addDartCreatedInstance(recorder,
onCopy: (Recorder original) {
return Recorder(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
});
final int videoCaptureId = await withOutput(identifier);
return instanceManager
.getInstanceWithWeakReference<VideoCapture>(videoCaptureId)!;
}
/// Dynamically sets the target rotation of [instance] to [rotation].
Future<void> setTargetRotationFromInstances(
VideoCapture instance, int rotation) {
return setTargetRotation(
instanceManager.getIdentifier(instance)!, rotation);
}
/// Gets the [Recorder] associated with the provided [VideoCapture] instance.
Future<Recorder> getOutputFromInstance(VideoCapture instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final int recorderId = await getOutput(identifier!);
return instanceManager.getInstanceWithWeakReference(recorderId)!;
}
}
/// Flutter API implementation of [VideoCapture].
class VideoCaptureFlutterApiImpl implements VideoCaptureFlutterApi {
/// Constructs a [VideoCaptureFlutterApiImpl].
VideoCaptureFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(int identifier) {
instanceManager.addHostCreatedInstance(
VideoCapture.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
identifier, onCopy: (VideoCapture original) {
return VideoCapture.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
});
}
}
| packages/packages/camera/camera_android_camerax/lib/src/video_capture.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/video_capture.dart",
"repo_id": "packages",
"token_count": 1517
} | 934 |
// 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_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/focus_metering_action.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/metering_point.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'focus_metering_action_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
MeteringPoint,
TestFocusMeteringActionHostApi,
TestInstanceManagerHostApi
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('FocusMeteringAction', () {
tearDown(() => TestCameraHostApi.setup(null));
test('detached create does not call create on the Java side', () {
final MockTestFocusMeteringActionHostApi mockApi =
MockTestFocusMeteringActionHostApi();
TestFocusMeteringActionHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
FocusMeteringAction.detached(
meteringPointInfos: <(MeteringPoint, int?)>[
(MockMeteringPoint(), FocusMeteringAction.flagAwb)
],
instanceManager: instanceManager,
);
verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<List<int>>()),
argThat(isA<bool?>())));
});
test('create calls create on the Java side', () {
final MockTestFocusMeteringActionHostApi mockApi =
MockTestFocusMeteringActionHostApi();
TestFocusMeteringActionHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final MeteringPoint mockMeteringPoint1 = MockMeteringPoint();
const int mockMeteringPoint1Mode = FocusMeteringAction.flagAe;
const int mockMeteringPoint1Id = 7;
final MeteringPoint mockMeteringPoint2 = MockMeteringPoint();
const int mockMeteringPoint2Mode = FocusMeteringAction.flagAwb;
const int mockMeteringPoint2Id = 17;
final List<(MeteringPoint meteringPoint, int? meteringMode)>
meteringPointInfos =
<(MeteringPoint meteringPoint, int? meteringMode)>[
(mockMeteringPoint1, mockMeteringPoint1Mode),
(mockMeteringPoint2, mockMeteringPoint2Mode)
];
const bool disableAutoCancel = true;
instanceManager
.addHostCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id,
onCopy: (MeteringPoint original) {
return MockMeteringPoint();
});
instanceManager
.addHostCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id,
onCopy: (MeteringPoint original) {
return MockMeteringPoint();
});
final FocusMeteringAction instance = FocusMeteringAction(
meteringPointInfos: meteringPointInfos,
disableAutoCancel: disableAutoCancel,
instanceManager: instanceManager,
);
final VerificationResult verificationResult = verify(mockApi.create(
argThat(equals(instanceManager.getIdentifier(instance))),
captureAny,
argThat(equals(disableAutoCancel))));
final List<MeteringPointInfo?> captureMeteringPointInfos =
verificationResult.captured.single as List<MeteringPointInfo?>;
expect(captureMeteringPointInfos.length, equals(2));
expect(captureMeteringPointInfos[0]!.meteringPointId,
equals(mockMeteringPoint1Id));
expect(
captureMeteringPointInfos[0]!.meteringMode, mockMeteringPoint1Mode);
expect(captureMeteringPointInfos[1]!.meteringPointId,
equals(mockMeteringPoint2Id));
expect(
captureMeteringPointInfos[1]!.meteringMode, mockMeteringPoint2Mode);
});
});
}
| packages/packages/camera/camera_android_camerax/test/focus_metering_action_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/focus_metering_action_test.dart",
"repo_id": "packages",
"token_count": 1576
} | 935 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/observer_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// 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
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestObserverHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestObserverHostApi extends _i1.Mock
implements _i2.TestObserverHostApi {
MockTestObserverHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i2.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/observer_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/observer_test.mocks.dart",
"repo_id": "packages",
"token_count": 667
} | 936 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/resolution_selector_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart' as _i2;
import 'package:camera_android_camerax/src/resolution_strategy.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i4;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// 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
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [AspectRatioStrategy].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockAspectRatioStrategy extends _i1.Mock
implements _i2.AspectRatioStrategy {
MockAspectRatioStrategy() {
_i1.throwOnMissingStub(this);
}
@override
int get preferredAspectRatio => (super.noSuchMethod(
Invocation.getter(#preferredAspectRatio),
returnValue: 0,
) as int);
@override
int get fallbackRule => (super.noSuchMethod(
Invocation.getter(#fallbackRule),
returnValue: 0,
) as int);
}
/// A class which mocks [ResolutionStrategy].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockResolutionStrategy extends _i1.Mock
implements _i3.ResolutionStrategy {
MockResolutionStrategy() {
_i1.throwOnMissingStub(this);
}
}
/// A class which mocks [TestResolutionSelectorHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestResolutionSelectorHostApi extends _i1.Mock
implements _i4.TestResolutionSelectorHostApi {
MockTestResolutionSelectorHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? resolutionStrategyIdentifier,
int? aspectRatioStrategyIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
resolutionStrategyIdentifier,
aspectRatioStrategyIdentifier,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i4.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart",
"repo_id": "packages",
"token_count": 1171
} | 937 |
// 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 camera_avfoundation;
@import camera_avfoundation.Test;
@import AVFoundation;
@import XCTest;
#import <OCMock/OCMock.h>
#import "CameraTestUtils.h"
/// Includes test cases related to sample buffer handling for FLTCam class.
@interface FLTCamSampleBufferTests : XCTestCase
@end
@implementation FLTCamSampleBufferTests
- (void)testSampleBufferCallbackQueueMustBeCaptureSessionQueue {
dispatch_queue_t captureSessionQueue = dispatch_queue_create("testing", NULL);
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(captureSessionQueue);
XCTAssertEqual(captureSessionQueue, cam.captureVideoOutput.sampleBufferCallbackQueue,
@"Sample buffer callback queue must be the capture session queue.");
}
- (void)testCopyPixelBuffer {
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(dispatch_queue_create("test", NULL));
CMSampleBufferRef capturedSampleBuffer = FLTCreateTestSampleBuffer();
CVPixelBufferRef capturedPixelBuffer = CMSampleBufferGetImageBuffer(capturedSampleBuffer);
// Mimic sample buffer callback when captured a new video sample
[cam captureOutput:cam.captureVideoOutput
didOutputSampleBuffer:capturedSampleBuffer
fromConnection:OCMClassMock([AVCaptureConnection class])];
CVPixelBufferRef deliveriedPixelBuffer = [cam copyPixelBuffer];
XCTAssertEqual(deliveriedPixelBuffer, capturedPixelBuffer,
@"FLTCam must deliver the latest captured pixel buffer to copyPixelBuffer API.");
CFRelease(capturedSampleBuffer);
CFRelease(deliveriedPixelBuffer);
}
- (void)testDidOutputSampleBuffer_mustNotChangeSampleBufferRetainCountAfterPauseResumeRecording {
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(dispatch_queue_create("test", NULL));
CMSampleBufferRef sampleBuffer = FLTCreateTestSampleBuffer();
id writerMock = OCMClassMock([AVAssetWriter class]);
OCMStub([writerMock alloc]).andReturn(writerMock);
OCMStub([writerMock initWithURL:OCMOCK_ANY fileType:OCMOCK_ANY error:[OCMArg setTo:nil]])
.andReturn(writerMock);
__block AVAssetWriterStatus status = AVAssetWriterStatusUnknown;
OCMStub([writerMock startWriting]).andDo(^(NSInvocation *invocation) {
status = AVAssetWriterStatusWriting;
});
OCMStub([writerMock status]).andDo(^(NSInvocation *invocation) {
[invocation setReturnValue:&status];
});
FLTThreadSafeFlutterResult *result =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id result){
// no-op
}];
// Pause then resume the recording.
[cam startVideoRecordingWithResult:result];
[cam pauseVideoRecordingWithResult:result];
[cam resumeVideoRecordingWithResult:result];
[cam captureOutput:cam.captureVideoOutput
didOutputSampleBuffer:sampleBuffer
fromConnection:OCMClassMock([AVCaptureConnection class])];
XCTAssertEqual(CFGetRetainCount(sampleBuffer), 1,
@"didOutputSampleBuffer must not change the sample buffer retain count after "
@"pause resume recording.");
CFRelease(sampleBuffer);
}
- (void)testDidOutputSampleBufferIgnoreAudioSamplesBeforeVideoSamples {
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(dispatch_queue_create("testing", NULL));
CMSampleBufferRef videoSample = FLTCreateTestSampleBuffer();
CMSampleBufferRef audioSample = FLTCreateTestAudioSampleBuffer();
id connectionMock = OCMClassMock([AVCaptureConnection class]);
id writerMock = OCMClassMock([AVAssetWriter class]);
OCMStub([writerMock alloc]).andReturn(writerMock);
OCMStub([writerMock initWithURL:OCMOCK_ANY fileType:OCMOCK_ANY error:[OCMArg setTo:nil]])
.andReturn(writerMock);
__block AVAssetWriterStatus status = AVAssetWriterStatusUnknown;
OCMStub([writerMock startWriting]).andDo(^(NSInvocation *invocation) {
status = AVAssetWriterStatusWriting;
});
OCMStub([writerMock status]).andDo(^(NSInvocation *invocation) {
[invocation setReturnValue:&status];
});
__block NSArray *writtenSamples = @[];
id videoMock = OCMClassMock([AVAssetWriterInputPixelBufferAdaptor class]);
OCMStub([videoMock assetWriterInputPixelBufferAdaptorWithAssetWriterInput:OCMOCK_ANY
sourcePixelBufferAttributes:OCMOCK_ANY])
.andReturn(videoMock);
OCMStub([videoMock appendPixelBuffer:[OCMArg anyPointer] withPresentationTime:kCMTimeZero])
.ignoringNonObjectArgs()
.andDo(^(NSInvocation *invocation) {
writtenSamples = [writtenSamples arrayByAddingObject:@"video"];
});
id audioMock = OCMClassMock([AVAssetWriterInput class]);
OCMStub([audioMock assetWriterInputWithMediaType:[OCMArg isEqual:AVMediaTypeAudio]
outputSettings:OCMOCK_ANY])
.andReturn(audioMock);
OCMStub([audioMock isReadyForMoreMediaData]).andReturn(YES);
OCMStub([audioMock appendSampleBuffer:[OCMArg anyPointer]]).andDo(^(NSInvocation *invocation) {
writtenSamples = [writtenSamples arrayByAddingObject:@"audio"];
});
FLTThreadSafeFlutterResult *result =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id result){
}];
[cam startVideoRecordingWithResult:result];
[cam captureOutput:nil didOutputSampleBuffer:audioSample fromConnection:connectionMock];
[cam captureOutput:nil didOutputSampleBuffer:audioSample fromConnection:connectionMock];
[cam captureOutput:cam.captureVideoOutput
didOutputSampleBuffer:videoSample
fromConnection:connectionMock];
[cam captureOutput:nil didOutputSampleBuffer:audioSample fromConnection:connectionMock];
NSArray *expectedSamples = @[ @"video", @"audio" ];
XCTAssertEqualObjects(writtenSamples, expectedSamples, @"First appended sample must be video.");
CFRelease(videoSample);
CFRelease(audioSample);
}
@end
| packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSampleBufferTests.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSampleBufferTests.m",
"repo_id": "packages",
"token_count": 1980
} | 938 |
name: camera_avfoundation
description: iOS implementation of the camera plugin.
repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_avfoundation
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
version: 0.9.14+1
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: camera
platforms:
ios:
pluginClass: CameraPlugin
dartPluginClass: AVFoundationCamera
dependencies:
camera_platform_interface: ^2.7.0
flutter:
sdk: flutter
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
topics:
- camera
| packages/packages/camera/camera_avfoundation/pubspec.yaml/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/pubspec.yaml",
"repo_id": "packages",
"token_count": 280
} | 939 |
name: cross_file
description: An abstraction to allow working with files across multiple platforms.
repository: https://github.com/flutter/packages/tree/main/packages/cross_file
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+cross_file%22
version: 0.3.4+1
environment:
sdk: ^3.3.0
dependencies:
meta: ^1.3.0
web: ^0.5.0
dev_dependencies:
path: ^1.8.1
test: ^1.21.1
topics:
- files
| packages/packages/cross_file/pubspec.yaml/0 | {
"file_path": "packages/packages/cross_file/pubspec.yaml",
"repo_id": "packages",
"token_count": 181
} | 940 |
A package that provides two dynamic grid layouts: wrap and staggered.
## Features
This package provides support for multi sized tiles and different layouts.
Currently the layouts that are implemented in this package are `Stagger` and
`Wrap`.
### Stagger Features
`DynamicGridView` is a subclass of `GridView` and gives access
to the `SliverGridDelegate`s that are already implemented in the Flutter
Framework. Some `SliverGridDelegate`s are `SliverGridDelegateWithMaxCrossAxisExtent` and
`SliverGridDelegateWithFixedCrossAxisCount`. This layout can be used with
`DynamicGridView.stagger`.
### Wrap Features
The Wrap layout is able to do runs of different widgets and adapt accordingly with
the sizes of the children. It can leave spacing with `mainAxisSpacing` and
`crossAxisSpacing`.
Having different sizes in only one of the axis is possible by
changing the values of `childCrossAxisExtent` and `childMainAxisExtent`. These
values by default are set to have loose constraints, but by giving `childCrossAxisExtent` a specific value like
100 pixels, it will make all of the children 100 pixels in the main axis.
This layout can be used with `DynamicGridView.wrap` and with
`DynamicGridView.builder` and `SliverGridDelegateWithWrapping` as the delegate.
## Getting started
### Depend on it
Run this command with Flutter:
```sh
$ flutter pub add dynamic_layouts
```
### Import it
Now in your Dart code, you can use:
```sh
import 'package:dynamic_layouts/dynamic_layouts.dart';
```
## Usage
Use `DynamicGridView`s to access these layouts.
`DynamicGridView` has some constructors that use `SliverChildListDelegate` like
`.wrap` and `.stagger`. For a more efficient option that uses `SliverChildBuilderDelegate` use
`.builder`, it works the same as `GridView.builder`.
### Wrap
The following are simple examples of how to use `DynamicGridView.wrap`.
The following example uses `DynamicGridView.builder` with
`SliverGridDelegateWithWrapping`.
By using `childCrossAxisExtent` and `childMainAxisExtent` the main axis
can be limited to have a specific size and the other can be set to loose
constraints.
### Stagger
The `Stagger` layout can be used with the constructor
`DynamicGridView.stagger` and still use the delegates from `GridView`
like `SliverGridDelegateWithMaxCrossAxisExtent` and
`SliverGridDelegateWithFixedCrossAxisCount`.
## Additional information
The staggered layout is similar to Android's [StaggeredGridLayoutManager](https://developer.android.com/reference/androidx/recyclerview/widget/StaggeredGridLayoutManager), while the wrap layout
emulates iOS' [UICollectionView](https://developer.apple.com/documentation/uikit/uicollectionview).
The inner functionality of this package is exposed, meaning that other dynamic layouts
can be created on top of it and added to the collection. If you want to contribute to
this package, you can open a pull request in [Flutter Packages](https://github.com/flutter/packages)
and add the tag "p: dynamic_layouts".
| packages/packages/dynamic_layouts/README.md/0 | {
"file_path": "packages/packages/dynamic_layouts/README.md",
"repo_id": "packages",
"token_count": 811
} | 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.
import 'package:dynamic_layouts/dynamic_layouts.dart';
import 'package:flutter/material.dart';
/// The wrap example
class WrapExample extends StatelessWidget {
/// The constructor for the wrap example
const WrapExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Wrap demo'),
),
body: DynamicGridView.builder(
gridDelegate: const SliverGridDelegateWithWrapping(),
itemCount: 20,
itemBuilder: (BuildContext context, int index) {
return Container(
height: index.isEven ? index % 7 * 50 + 150 : index % 4 * 50 + 100,
width: index.isEven ? index % 5 * 20 + 40 : index % 3 * 50 + 100,
color: index.isEven
? Colors.red[(index % 7 + 1) * 100]
: Colors.blue[(index % 7 + 1) * 100],
child: Center(
child: Text('Index $index'),
),
);
},
),
);
}
}
| packages/packages/dynamic_layouts/example/lib/wrap_layout_example.dart/0 | {
"file_path": "packages/packages/dynamic_layouts/example/lib/wrap_layout_example.dart",
"repo_id": "packages",
"token_count": 490
} | 942 |
// 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:math' as math;
import 'package:flutter/rendering.dart';
import 'base_grid_layout.dart';
import 'render_dynamic_grid.dart';
import 'wrap_layout.dart';
/// A [DynamicSliverGridLayout] that creates tiles with varying main axis
/// sizes and fixed cross axis sizes, generating a staggered layout. The extent
/// in the main axis will be defined by the child's size and must be finite.
/// Similar to Android's StaggeredGridLayoutManager:
/// [https://developer.android.com/reference/androidx/recyclerview/widget/StaggeredGridLayoutManager].
///
/// The tiles are placed in the column (or row in case [scrollDirection] is set
/// to [Axis.horizontal]) with the minimum extent, which means children are not
/// necessarily laid out in sequential order.
///
/// See also:
///
/// * [SliverGridWrappingTileLayout], a similar layout that allows tiles to be
/// freely sized in the main and cross axis.
/// * [DynamicSliverGridDelegateWithMaxCrossAxisExtent], which creates
/// staggered layouts with a maximum extent in the cross axis.
/// * [DynamicSliverGridDelegateWithFixedCrossAxisCount], which creates
/// staggered layouts with a consistent amount of tiles in the cross axis.
/// * [DynamicGridView.staggered], which uses these delegates to create
/// staggered layouts.
/// * [DynamicSliverGridGeometry], which establishes the position of a child
/// and pass the child's desired proportions to a [DynamicSliverGridLayout].
/// * [RenderDynamicSliverGrid], which is the sliver where the dynamic sized
/// tiles are positioned.
class SliverGridStaggeredTileLayout extends DynamicSliverGridLayout {
/// Creates a layout with dynamic main axis extents determined by the child's
/// size and fixed cross axis extents.
///
/// All arguments must be not null. The [crossAxisCount] argument must be
/// greater than zero. The [mainAxisSpacing], [crossAxisSpacing] and
/// [childCrossAxisExtent] arguments must not be negative.
SliverGridStaggeredTileLayout({
required this.crossAxisCount,
required this.mainAxisSpacing,
required this.crossAxisSpacing,
required this.childCrossAxisExtent,
required this.scrollDirection,
}) : assert(crossAxisCount > 0),
assert(crossAxisSpacing >= 0),
assert(childCrossAxisExtent >= 0);
/// The number of children in the cross axis.
final int crossAxisCount;
/// The number of logical pixels between each child along the main axis.
final double mainAxisSpacing;
/// The number of logical pixels between each child along the cross axis.
final double crossAxisSpacing;
/// The number of pixels from the leading edge of one tile to the trailing
/// edge of the same tile in the cross axis.
final double childCrossAxisExtent;
/// The axis along which the scroll view scrolls.
final Axis scrollDirection;
/// The collection of scroll offsets for every row or column across the main
/// axis. It includes the tiles' sizes and the spacing between them.
final List<double> _scrollOffsetForMainAxis = <double>[];
/// The amount of tiles in every row or column across the main axis.
final List<int> _mainAxisCount = <int>[];
/// Returns the row or column with the minimum extent for the next child to
/// be laid out.
int _getNextCrossAxisSlot() {
int nextCrossAxisSlot = 0;
double minScrollOffset = double.infinity;
if (_scrollOffsetForMainAxis.length < crossAxisCount) {
nextCrossAxisSlot = _scrollOffsetForMainAxis.length;
_scrollOffsetForMainAxis.add(0.0);
return nextCrossAxisSlot;
}
for (int i = 0; i < crossAxisCount; i++) {
if (_scrollOffsetForMainAxis[i] < minScrollOffset) {
nextCrossAxisSlot = i;
minScrollOffset = _scrollOffsetForMainAxis[i];
}
}
return nextCrossAxisSlot;
}
@override
bool reachedTargetScrollOffset(double targetOffset) {
for (final double scrollOffset in _scrollOffsetForMainAxis) {
if (scrollOffset < targetOffset) {
return false;
}
}
return true;
}
@override
DynamicSliverGridGeometry getGeometryForChildIndex(int index) {
return DynamicSliverGridGeometry(
scrollOffset: 0.0,
crossAxisOffset: 0.0,
mainAxisExtent: double.infinity,
crossAxisExtent: childCrossAxisExtent,
);
}
@override
DynamicSliverGridGeometry updateGeometryForChildIndex(
int index,
Size childSize,
) {
final int crossAxisSlot = _getNextCrossAxisSlot();
final double currentScrollOffset = _scrollOffsetForMainAxis[crossAxisSlot];
final double childMainAxisExtent =
scrollDirection == Axis.vertical ? childSize.height : childSize.width;
final double scrollOffset = currentScrollOffset +
(_mainAxisCount.length >= crossAxisCount
? _mainAxisCount[crossAxisSlot]
: 0) *
mainAxisSpacing;
final double crossAxisOffset =
crossAxisSlot * (childCrossAxisExtent + crossAxisSpacing);
final double mainAxisExtent =
scrollDirection == Axis.vertical ? childSize.height : childSize.width;
_scrollOffsetForMainAxis[crossAxisSlot] =
childMainAxisExtent + _scrollOffsetForMainAxis[crossAxisSlot];
_mainAxisCount.length >= crossAxisCount
? _mainAxisCount[crossAxisSlot] += 1
: _mainAxisCount.add(1);
return DynamicSliverGridGeometry(
scrollOffset: scrollOffset,
crossAxisOffset: crossAxisOffset,
mainAxisExtent: mainAxisExtent,
crossAxisExtent: childCrossAxisExtent,
);
}
}
/// Creates dynamic grid layouts with a fixed number of tiles in the cross axis
/// and varying main axis size dependent on the child's corresponding finite
/// extent. It uses the same logic as
/// [SliverGridDelegateWithFixedCrossAxisCount] where the total extent in the
/// cross axis is distributed equally between the specified amount of tiles,
/// but with a [SliverGridStaggeredTileLayout].
///
/// For example, if the grid is vertical, this delegate will create a layout
/// with a fixed number of columns. If the grid is horizontal, this delegate
/// will create a layout with a fixed number of rows.
///
/// This sample code shows how to use it independently with a [DynamicGridView]
/// constructor:
///
/// ```dart
/// DynamicGridView(
/// gridDelegate: const DynamicSliverGridDelegateWithFixedCrossAxisCount(
/// crossAxisCount: 4,
/// ),
/// children: List<Widget>.generate(
/// 50,
/// (int index) => SizedBox(
/// height: index % 2 * 20 + 20,
/// child: Text('Index $index'),
/// ),
/// ),
/// );
/// ```
///
/// See also:
///
/// * [DynamicSliverGridDelegateWithMaxCrossAxisExtent], which creates a
/// dynamic layout with tiles that have a maximum cross-axis extent
/// and varying main axis size.
/// * [DynamicGridView], which can use this delegate to control the layout of
/// its tiles.
/// * [DynamicSliverGridGeometry], which establishes the position of a child
/// and pass the child's desired proportions to [DynamicSliverGridLayout].
/// * [RenderDynamicSliverGrid], which is the sliver where the dynamic sized
/// tiles are positioned.
class DynamicSliverGridDelegateWithFixedCrossAxisCount
extends SliverGridDelegateWithFixedCrossAxisCount {
/// Creates a delegate that makes grid layouts with a fixed number of tiles
/// in the cross axis and varying main axis size dependent on the child's
/// corresponding finite extent.
///
/// Only the [crossAxisCount] argument needs to be greater than zero. All of
/// them must be not null.
const DynamicSliverGridDelegateWithFixedCrossAxisCount({
required super.crossAxisCount,
super.mainAxisSpacing = 0.0,
super.crossAxisSpacing = 0.0,
}) : assert(crossAxisCount > 0),
assert(mainAxisSpacing >= 0),
assert(crossAxisSpacing >= 0);
bool _debugAssertIsValid() {
assert(crossAxisCount > 0);
assert(mainAxisSpacing >= 0.0);
assert(crossAxisSpacing >= 0.0);
assert(childAspectRatio > 0.0);
return true;
}
@override
DynamicSliverGridLayout getLayout(SliverConstraints constraints) {
assert(_debugAssertIsValid());
final double usableCrossAxisExtent = math.max(
0.0,
constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1),
);
final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
return SliverGridStaggeredTileLayout(
crossAxisCount: crossAxisCount,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
childCrossAxisExtent: childCrossAxisExtent,
scrollDirection: axisDirectionToAxis(constraints.axisDirection),
);
}
}
/// Creates dynamic grid layouts with tiles that each have a maximum cross-axis
/// extent and varying main axis size dependent on the child's corresponding
/// finite extent. It uses the same logic as
/// [SliverGridDelegateWithMaxCrossAxisExtent] where every tile has the same
/// cross axis size and does not exceed the provided max extent, but with a
/// [SliverGridStaggeredTileLayout].
///
/// This delegate will select a cross-axis extent for the tiles that is as
/// large as possible subject to the following conditions:
///
/// * The extent evenly divides the cross-axis extent of the grid.
/// * The extent is at most [maxCrossAxisExtent].
///
/// This sample code shows how to use it independently with a [DynamicGridView]
/// constructor:
///
/// ```dart
/// DynamicGridView(
/// gridDelegate: const DynamicSliverGridDelegateWithMaxCrossAxisExtent(
/// maxCrossAxisExtent: 100,
/// ),
/// children: List<Widget>.generate(
/// 50,
/// (int index) => SizedBox(
/// height: index % 2 * 20 + 20,
/// child: Text('Index $index'),
/// ),
/// ),
/// );
/// ```
///
/// See also:
///
/// * [DynamicSliverGridDelegateWithFixedCrossAxisCount], which creates a
/// layout with a fixed number of tiles in the cross axis.
/// * [DynamicGridView], which can use this delegate to control the layout of
/// its tiles.
/// * [DynamicSliverGridGeometry], which establishes the position of a child
/// and pass the child's desired proportions to [DynamicSliverGridLayout].
/// * [RenderDynamicSliverGrid], which is the sliver where the dynamic sized
/// tiles are positioned.
class DynamicSliverGridDelegateWithMaxCrossAxisExtent
extends SliverGridDelegateWithMaxCrossAxisExtent {
/// Creates a delegate that makes grid layouts with tiles that have a maximum
/// cross-axis extent and varying main axis size dependent on the child's
/// corresponding finite extent.
///
/// Only the [maxCrossAxisExtent] argument needs to be greater than zero.
/// All of them must be not null.
const DynamicSliverGridDelegateWithMaxCrossAxisExtent({
required super.maxCrossAxisExtent,
super.mainAxisSpacing = 0.0,
super.crossAxisSpacing = 0.0,
}) : assert(maxCrossAxisExtent > 0),
assert(mainAxisSpacing >= 0),
assert(crossAxisSpacing >= 0);
bool _debugAssertIsValid(double crossAxisExtent) {
assert(crossAxisExtent > 0.0);
assert(maxCrossAxisExtent > 0.0);
assert(mainAxisSpacing >= 0.0);
assert(crossAxisSpacing >= 0.0);
assert(childAspectRatio > 0.0);
return true;
}
@override
DynamicSliverGridLayout getLayout(SliverConstraints constraints) {
assert(_debugAssertIsValid(constraints.crossAxisExtent));
final int crossAxisCount =
(constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing))
.ceil();
final double usableCrossAxisExtent = math.max(
0.0,
constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1),
);
final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
return SliverGridStaggeredTileLayout(
crossAxisCount: crossAxisCount,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
childCrossAxisExtent: childCrossAxisExtent,
scrollDirection: axisDirectionToAxis(constraints.axisDirection),
);
}
}
| packages/packages/dynamic_layouts/lib/src/staggered_layout.dart/0 | {
"file_path": "packages/packages/dynamic_layouts/lib/src/staggered_layout.dart",
"repo_id": "packages",
"token_count": 3971
} | 943 |
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 7.4.2" type="baseline" client="gradle" dependencies="false" name="AGP (7.4.2)" variant="all" version="7.4.2">
<issue
id="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="180"
column="17"/>
</issue>
<issue
id="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="186"
column="17"/>
</issue>
<issue
id="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="192"
column="17"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
errorLine1=" ((io.flutter.embedding.android.FlutterView) flutterView).getAttachedFlutterEngine();"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="83"
column="68"/>
</issue>
<issue
id="LogConditional"
message="The log call Log.i(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`"
errorLine1=" Log.i(TAG, "Dart VM service protocol runs at uri: " + serviceProtocolUri);"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="52"
column="5"/>
</issue>
<issue
id="LogConditional"
message="The log call Log.d(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`"
errorLine1=" Log.d("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="65"
column="5"/>
</issue>
<issue
id="LogConditional"
message="The log call Log.d(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`"
errorLine1=" Log.d("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="132"
column="7"/>
</issue>
<issue
id="LogConditional"
message="The log call Log.d(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`"
errorLine1=" Log.d("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/action/WidgetCoordinatesCalculator.java"
line="42"
column="5"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred when performing the given action %s on widget matched %s","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="139"
column="23"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("Flutter testing APIs not registered with Dart isolate %s.", isolateId));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="346"
column="27"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred in JSON-RPC response when querying isolate info for %s: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="358"
column="17"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("Flutter testing API registered with Dart isolate %s.", isolateId));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="368"
column="29"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("Dart VM Observatory url %s is malformed.", observatoryUrl), e);"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="40"
column="25"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" Log.w(TAG, String.format("Widget info that matches %s is null.", widgetMatcher));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="127"
column="34"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("Widget info that matches %s is null.", widgetMatcher));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="129"
column="27"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" return String.format(Locale.ROOT, "type text(%s)", stringToBeTyped);"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterTypeTextAction.java"
line="145"
column="39"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Perform a %s action on the Flutter widget matched %s.", widgetAction, widgetMatcher);"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="95"
column="9"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("Not a valid Flutter view:%s", HumanReadables.describe(view)));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="40"
column="25"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving a Flutter widget's geometry info. Response""
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="40"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving a Flutter widget's geometry info. Response""
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="49"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving a Flutter widget's geometry info. Response""
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="71"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving a Flutter widget's geometry info. Response""
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="84"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving Dart VM info. Response received: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="40"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving Dart VM info. Response received: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="48"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving widget's diagnostics info. Response received: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="46"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Error occurred during retrieving widget's diagnostics info. Response received: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="54"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" String.format("JSON-RPC Request sent to uri %s: %s.", webSocketUri, request.toJson()));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="79"
column="25"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" Log.d(TAG, String.format("JSON-RPC response received: %s.", response));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="111"
column="34"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Received a message with empty or unknown ID: %s. Drop the message.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="120"
column="19"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" Log.w(TAG, String.format("Failed to deliver message with error: %s.", t.getMessage()));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="141"
column="32"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "The widget diagnostics info must contain the runtime type of the widget. Illegal""
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WidgetInfoFactory.java"
line="58"
column="15"/>
</issue>
<issue
id="StringFormatTrivial"
message="This formatting string is trivial. Rather than using `String.format` to create your String, it will be more performant to concatenate your arguments with `+`. "
errorLine1=" "Unknown widget type: %s. Widget diagnostics info: %s.","
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WidgetInfoFactory.java"
line="86"
column="17"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `DartVmService` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="330"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `DartVmService` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="336"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `DartVmService` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="356"
column="13"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `DartVmService` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="367"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` constructor of class `WidgetInteraction` requires synthetic accessor"
errorLine1=" return new WidgetInteraction(isFlutterView(), widgetMatcher);"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="61"
column="12"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `EspressoFlutter` requires synthetic accessor"
errorLine1=" Log.w(TAG, String.format("Widget info that matches %s is null.", widgetMatcher));"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="127"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `idGenerator` of class `EspressoFlutter` requires synthetic accessor"
errorLine1=" widgetMatcher, flutterAction, okHttpClient, idGenerator, taskExecutor);"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="145"
column="59"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `okHttpClient` of class `EspressoFlutter` requires synthetic accessor"
errorLine1=" widgetMatcher, flutterAction, okHttpClient, idGenerator, taskExecutor);"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="145"
column="45"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `taskExecutor` of class `EspressoFlutter` requires synthetic accessor"
errorLine1=" widgetMatcher, flutterAction, okHttpClient, idGenerator, taskExecutor);"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="145"
column="72"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` constructor of class `MatchesWidgetAssertion` requires synthetic accessor"
errorLine1=" return new MatchesWidgetAssertion(checkNotNull(widgetMatcher, "Matcher cannot be null."));"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterAssertions.java"
line="24"
column="12"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` constructor of class `IsFlutterViewMatcher` requires synthetic accessor"
errorLine1=" return new IsFlutterViewMatcher();"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="24"
column="12"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `resultFuture` of class `FlutterViewAction` requires synthetic accessor"
errorLine1=" resultFuture.set(actionResultFuture.get());"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="154"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `resultFuture` of class `FlutterViewAction` requires synthetic accessor"
errorLine1=" resultFuture.setException(e);"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="156"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `dx` of class `Coordinates` requires synthetic accessor"
errorLine1=" return response.dx;"
errorLine2=" ~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="75"
column="23"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `dy` of class `Coordinates` requires synthetic accessor"
errorLine1=" return response.dy;"
errorLine2=" ~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="88"
column="23"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` constructor of class `GetOffsetResponse` requires synthetic accessor"
errorLine1=" GetOffsetResponse response = new GetOffsetResponse();"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="133"
column="36"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `isError` of class `GetOffsetResponse` requires synthetic accessor"
errorLine1=" response.isError = this.isError;"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="134"
column="16"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `response` of class `GetOffsetResponse` requires synthetic accessor"
errorLine1=" response.response = this.coordinate;"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="135"
column="16"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `type` of class `GetOffsetResponse` requires synthetic accessor"
errorLine1=" response.type = checkNotNull(type).toString();"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java"
line="136"
column="16"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `runtimeType` of class `DiagnosticNodeInfo` requires synthetic accessor"
errorLine1=" return widgetInfo.runtimeType;"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="71"
column="25"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `description` of class `DiagnosticNodeInfo` requires synthetic accessor"
errorLine1=" return widgetInfo.description;"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="98"
column="23"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `hasChildren` of class `DiagnosticNodeInfo` requires synthetic accessor"
errorLine1=" return widgetInfo.hasChildren;"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="110"
column="23"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `GetWidgetDiagnosticsResponse` requires synthetic accessor"
errorLine1=" Log.w(TAG, "Widget property list is null.");"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="132"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` member of class `WebSocketListenerImpl` requires synthetic accessor"
errorLine1=" WebSocketListener webSocketListener = new WebSocketListenerImpl();"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="53"
column="43"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" if (Log.isLoggable(TAG, Log.DEBUG)) {"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="110"
column="26"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" Log.d(TAG, String.format("JSON-RPC response received: %s.", response));"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="111"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `responseFutures` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" synchronized (responseFutures) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="114"
column="21"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `responseFutures` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" || !responseFutures.containsKey(responseObj.getId())) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="116"
column="17"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="118"
column="15"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `responseFutures` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" responseFutures.remove(responseObj.getId());"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="125"
column="13"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" TAG,"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="133"
column="11"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `TAG` of class `JsonRpcClient` requires synthetic accessor"
errorLine1=" Log.w(TAG, String.format("Failed to deliver message with error: %s.", t.getMessage()));"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="141"
column="13"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` constructor of class `JsonRpcRequest` requires synthetic accessor"
errorLine1=" JsonRpcRequest request = new JsonRpcRequest(id, method);"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="214"
column="32"/>
</issue>
<issue
id="SyntheticAccessor"
message="Access to `private` field `params` of class `JsonRpcRequest` requires synthetic accessor"
errorLine1=" request.params = this.params;"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="216"
column="17"/>
</issue>
<issue
id="LambdaLast"
message="Functional interface parameters (such as parameter 3, "messageIdGenerator", in androidx.test.espresso.flutter.internal.protocol.impl.DartVmService.DartVmService) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions"
errorLine1=" ExecutorService taskExecutor) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="90"
column="7"/>
</issue>
<issue
id="LambdaLast"
message="Functional interface parameters (such as parameter 4, "messageIdGenerator", in androidx.test.espresso.flutter.action.FlutterViewAction.FlutterViewAction) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions"
errorLine1=" ExecutorService taskExecutor) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="79"
column="7"/>
</issue>
<issue
id="LambdaLast"
message="Functional interface parameters (such as parameter 1, "assertion", in androidx.test.espresso.flutter.assertion.FlutterViewAssertion.FlutterViewAssertion) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions"
errorLine1=" public FlutterViewAssertion(WidgetAssertion assertion, WidgetInfo widgetInfo) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="29"
column="58"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public AmbiguousWidgetMatcherException(String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/exception/AmbiguousWidgetMatcherException.java"
line="18"
column="42"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<Void> perform("
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/ClickAction.java"
line="43"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" String isolateId,"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="87"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" JsonRpcClient jsonRpcClient,"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="88"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" IdGenerator<Integer> messageIdGenerator,"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="89"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" ExecutorService taskExecutor) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="90"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> connect() {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="116"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> perform("
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="121"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" @Nullable final WidgetMatcher widgetMatcher, final SyntheticAction action) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="122"
column="58"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<WidgetInfo> matchWidget(@Nonnull WidgetMatcher widgetMatcher) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="148"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Rect> getLocalRect(@Nonnull WidgetMatcher widgetMatcher) {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="164"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> waitUntilIdle() {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="207"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<JsonRpcResponse> getIsolateInfo() {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="224"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<GetVmResponse> getVmInfo() {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="234"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static URI getServiceProtocolUri(String observatoryUrl) {"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="29"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static URI getServiceProtocolUri(String observatoryUrl) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="29"
column="43"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static String getDartIsolateId(View flutterView) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="62"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static String getDartIsolateId(View flutterView) {"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="62"
column="41"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static DartExecutor getDartExecutor(View flutterView) {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="75"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static DartExecutor getDartExecutor(View flutterView) {"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="75"
column="46"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Duration(long quantity, TimeUnit unit) {"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/common/Duration.java"
line="29"
column="34"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public TimeUnit getUnit() {"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/common/Duration.java"
line="40"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Duration plus(@Nullable Duration duration) {"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/common/Duration.java"
line="53"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ErrorObject(int code, String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="20"
column="32"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ErrorObject(int code, String message, JsonObject data) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="24"
column="32"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ErrorObject(int code, String message, JsonObject data) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="24"
column="48"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getMessage() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="36"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonObject getData() {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="41"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetInteraction onFlutterWidget(@Nonnull WidgetMatcher widgetMatcher) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="60"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInteraction perform(@Nonnull final WidgetAction... widgetActions) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="104"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInteraction check(@Nonnull WidgetAssertion assertion) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java"
line="121"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/com/example/espresso/EspressoPlugin.java"
line="33"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<R> perform("
errorLine2=" ~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterAction.java"
line="25"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetAction click() {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java"
line="33"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetAction syntheticClick() {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java"
line="48"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetAction typeText(@Nonnull String stringToBeTyped) {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java"
line="64"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetAction scrollTo() {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java"
line="73"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetAssertion matches(@Nonnull Matcher<WidgetInfo> widgetMatcher) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterAssertions.java"
line="23"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static Matcher<View> isFlutterView() {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="23"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetMatcher withTooltip(@Nonnull String tooltip) {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="32"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetMatcher withValueKey(@Nonnull String valueKey) {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="41"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetMatcher withType(@Nonnull String type) {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="55"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetMatcher withText(@Nonnull String text) {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="64"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static WidgetMatcher isDescendantOf("
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="74"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static Matcher<WidgetInfo> isExisting() {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java"
line="86"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterProtocolException(String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java"
line="11"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterProtocolException(Throwable t) {"
errorLine2=" ~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java"
line="15"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterProtocolException(String message, Throwable t) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java"
line="19"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterProtocolException(String message, Throwable t) {"
errorLine2=" ~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java"
line="19"
column="51"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> perform("
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterScrollToAction.java"
line="25"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> connect();"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java"
line="19"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<Void> perform(@Nullable WidgetMatcher widgetMatcher, @Nonnull SyntheticAction action);"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java"
line="41"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<WidgetInfo> matchWidget(@Nonnull WidgetMatcher widgetMatcher);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java"
line="60"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<Rect> getLocalRect(@Nonnull WidgetMatcher widgetMatcher);"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java"
line="70"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<Void> waitUntilIdle();"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java"
line="73"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<Void> perform("
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterTypeTextAction.java"
line="77"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" WidgetMatcher widgetMatcher,"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="75"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" FlutterAction<T> widgetAction,"
errorLine2=" ~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="76"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" OkHttpClient webSocketClient,"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="77"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" IdGenerator<Integer> messageIdGenerator,"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="78"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" ExecutorService taskExecutor) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="79"
column="7"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Matcher<View> getConstraints() {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="88"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getDescription() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="93"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void perform(UiController uiController, View flutterView) {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="100"
column="23"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void perform(UiController uiController, View flutterView) {"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="100"
column="50"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public T waitUntilCompleted(long timeout, TimeUnit unit)"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/FlutterViewAction.java"
line="170"
column="45"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterViewAssertion(WidgetAssertion assertion, WidgetInfo widgetInfo) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="29"
column="31"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public FlutterViewAssertion(WidgetAssertion assertion, WidgetInfo widgetInfo) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="29"
column="58"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void check(View view, NoMatchingViewException noViewFoundException) {"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="35"
column="21"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void check(View view, NoMatchingViewException noViewFoundException) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java"
line="35"
column="32"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static OffsetType fromString(String typeString) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetAction.java"
line="34"
column="19"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static OffsetType fromString(String typeString) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetAction.java"
line="34"
column="41"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static GetVmResponse fromJsonRpcResponse(JsonRpcResponse jsonRpcResponse) {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="35"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static GetVmResponse fromJsonRpcResponse(JsonRpcResponse jsonRpcResponse) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="35"
column="51"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Isolate getIsolate(int index) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="60"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public IdException(String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java"
line="16"
column="22"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public IdException(String message, Throwable throwable) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java"
line="20"
column="22"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public IdException(String message, Throwable throwable) {"
errorLine2=" ~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java"
line="20"
column="38"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public IdException(Throwable throwable) {"
errorLine2=" ~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdException.java"
line="24"
column="22"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static IdGenerator<Integer> newIntegerIdGenerator(int nextValue) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerators.java"
line="30"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static IdGenerator<Integer> newIntegerIdGenerator() {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerators.java"
line="54"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static IdGenerator<String> randomUuidStringGenerator() {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerators.java"
line="62"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public InvalidFlutterViewException(String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/exception/InvalidFlutterViewException.java"
line="16"
column="38"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetMatcher getAncestorMatcher() {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java"
line="47"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetMatcher getWidgetMatcher() {"
errorLine2=" ~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java"
line="52"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java"
line="62"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java"
line="68"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsExistingMatcher.java"
line="23"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/IsExistingMatcher.java"
line="28"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonRpcClient(OkHttpClient client, URI webSocketUri) {"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="45"
column="24"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonRpcClient(OkHttpClient client, URI webSocketUri) {"
errorLine2=" ~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="45"
column="45"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<JsonRpcResponse> request(JsonRpcRequest request) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="74"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ListenableFuture<JsonRpcResponse> request(JsonRpcRequest request) {"
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/JsonRpcClient.java"
line="74"
column="52"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static JsonRpcRequest fromJson(String jsonString) {"
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="51"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static JsonRpcRequest fromJson(String jsonString) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="51"
column="41"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getVersion() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="86"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getId() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="95"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getMethod() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="104"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonObject getParams() {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="109"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String toJson() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="118"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder(String method) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="172"
column="20"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setId(@Nullable String id) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="177"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setMethod(String method) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="183"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setMethod(String method) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="183"
column="30"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setParams(JsonObject params) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="189"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder setParams(JsonObject params) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="189"
column="30"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, String value) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="195"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, String value) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="195"
column="29"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, String value) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="195"
column="41"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, int value) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="201"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, int value) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="201"
column="29"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, boolean value) {"
errorLine2=" ~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="207"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Builder addParam(String tag, boolean value) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="207"
column="29"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonRpcRequest build() {"
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="213"
column="12"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static JsonRpcResponse fromJson(String jsonString) {"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="49"
column="17"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public static JsonRpcResponse fromJson(String jsonString) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="49"
column="42"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonRpcResponse(String id) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="62"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getVersion() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="72"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getId() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="77"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void setId(String id) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="86"
column="21"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public JsonObject getResult() {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="91"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void setResult(JsonObject result) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="100"
column="25"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public ErrorObject getError() {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="105"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void setError(ErrorObject error) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="114"
column="24"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String toJson() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="123"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public NoMatchingWidgetException(String message) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/exception/NoMatchingWidgetException.java"
line="16"
column="36"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected String actionId;"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/SyntheticAction.java"
line="30"
column="13"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> perform("
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/SyntheticClickAction.java"
line="28"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<Void> perform("
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/WaitUntilIdleAction.java"
line="20"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" Future<Void> perform("
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/WidgetAction.java"
line="38"
column="3"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" void check(View flutterView, WidgetInfo widgetInfo);"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/WidgetAssertion.java"
line="24"
column="14"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" void check(View flutterView, WidgetInfo widgetInfo);"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/WidgetAssertion.java"
line="24"
column="32"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInfoBuilder setValueKey(@Nullable String valueKey) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java"
line="42"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInfoBuilder setRuntimeType(@Nonnull String runtimeType) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java"
line="52"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInfoBuilder setText(@Nullable String text) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java"
line="62"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInfoBuilder setTooltip(@Nullable String tooltip) {"
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java"
line="72"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public WidgetInfo build() {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java"
line="78"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public Future<WidgetInfo> perform("
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/action/WidgetInfoFetcher.java"
line="21"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected String matcherId;"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/WidgetMatcher.java"
line="31"
column="13"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getText() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTextMatcher.java"
line="31"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTextMatcher.java"
line="41"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTextMatcher.java"
line="46"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getTooltip() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTooltipMatcher.java"
line="34"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTooltipMatcher.java"
line="44"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTooltipMatcher.java"
line="49"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getType() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTypeMatcher.java"
line="31"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTypeMatcher.java"
line="41"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithTypeMatcher.java"
line="46"
column="26"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public String getValueKey() {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithValueKeyMatcher.java"
line="36"
column="10"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" protected boolean matchesSafely(WidgetInfo widget) {"
errorLine2=" ~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithValueKeyMatcher.java"
line="46"
column="35"/>
</issue>
<issue
id="UnknownNullness"
message="Unknown nullability; explicitly declare as `@Nullable` or `@NonNull` to improve Kotlin interoperability; see https://developer.android.com/kotlin/interop#nullability_annotations"
errorLine1=" public void describeTo(Description description) {"
errorLine2=" ~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/matcher/WithValueKeyMatcher.java"
line="51"
column="26"/>
</issue>
</issues>
| packages/packages/espresso/android/lint-baseline.xml/0 | {
"file_path": "packages/packages/espresso/android/lint-baseline.xml",
"repo_id": "packages",
"token_count": 50980
} | 944 |
group 'dev.flutter.packages.file_selector_android'
version '1.0'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'dev.flutter.packages.file_selector_android'
}
compileSdk 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion 19
}
dependencies {
implementation 'androidx.annotation:annotation:1.7.1'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-inline:5.1.0'
testImplementation 'androidx.test:core:1.3.0'
// org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions.
// See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7
implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.10"))
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
| packages/packages/file_selector/file_selector_android/android/build.gradle/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/android/build.gradle",
"repo_id": "packages",
"token_count": 815
} | 945 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_android_example/main.dart' as app;
import 'package:flutter_driver/driver_extension.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
/// Entry point for integration tests that require espresso.
@pragma('vm:entry-point')
void integrationTestMain() {
enableFlutterDriverExtension();
app.main();
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Since this test is lacking integration tests, this test ensures the example
// app can be launched on an emulator/device.
testWidgets('Launch Test', (WidgetTester tester) async {});
}
| packages/packages/file_selector/file_selector_android/example/integration_test/file_selector_android_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/example/integration_test/file_selector_android_test.dart",
"repo_id": "packages",
"token_count": 239
} | 946 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v10.1.3), do not edit directly.
// See also: https://pub.dev/packages/pigeon
import Foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif
private func wrapResult(_ result: Any?) -> [Any?] {
return [result]
}
private func wrapError(_ error: Any) -> [Any?] {
if let flutterError = error as? FlutterError {
return [
flutterError.code,
flutterError.message,
flutterError.details,
]
}
return [
"\(error)",
"\(type(of: error))",
"Stacktrace: \(Thread.callStackSymbols)",
]
}
private func nilOrValue<T>(_ value: Any?) -> T? {
if value is NSNull { return nil }
return value as! T?
}
/// A Pigeon representation of the macOS portion of an `XTypeGroup`.
///
/// Generated class from Pigeon that represents data sent in messages.
struct AllowedTypes {
var extensions: [String?]
var mimeTypes: [String?]
var utis: [String?]
static func fromList(_ list: [Any?]) -> AllowedTypes? {
let extensions = list[0] as! [String?]
let mimeTypes = list[1] as! [String?]
let utis = list[2] as! [String?]
return AllowedTypes(
extensions: extensions,
mimeTypes: mimeTypes,
utis: utis
)
}
func toList() -> [Any?] {
return [
extensions,
mimeTypes,
utis,
]
}
}
/// Options for save panels.
///
/// These correspond to NSSavePanel properties (which are, by extension
/// NSOpenPanel properties as well).
///
/// Generated class from Pigeon that represents data sent in messages.
struct SavePanelOptions {
var allowedFileTypes: AllowedTypes? = nil
var directoryPath: String? = nil
var nameFieldStringValue: String? = nil
var prompt: String? = nil
static func fromList(_ list: [Any?]) -> SavePanelOptions? {
var allowedFileTypes: AllowedTypes? = nil
if let allowedFileTypesList: [Any?] = nilOrValue(list[0]) {
allowedFileTypes = AllowedTypes.fromList(allowedFileTypesList)
}
let directoryPath: String? = nilOrValue(list[1])
let nameFieldStringValue: String? = nilOrValue(list[2])
let prompt: String? = nilOrValue(list[3])
return SavePanelOptions(
allowedFileTypes: allowedFileTypes,
directoryPath: directoryPath,
nameFieldStringValue: nameFieldStringValue,
prompt: prompt
)
}
func toList() -> [Any?] {
return [
allowedFileTypes?.toList(),
directoryPath,
nameFieldStringValue,
prompt,
]
}
}
/// Options for open panels.
///
/// These correspond to NSOpenPanel properties.
///
/// Generated class from Pigeon that represents data sent in messages.
struct OpenPanelOptions {
var allowsMultipleSelection: Bool
var canChooseDirectories: Bool
var canChooseFiles: Bool
var baseOptions: SavePanelOptions
static func fromList(_ list: [Any?]) -> OpenPanelOptions? {
let allowsMultipleSelection = list[0] as! Bool
let canChooseDirectories = list[1] as! Bool
let canChooseFiles = list[2] as! Bool
let baseOptions = SavePanelOptions.fromList(list[3] as! [Any?])!
return OpenPanelOptions(
allowsMultipleSelection: allowsMultipleSelection,
canChooseDirectories: canChooseDirectories,
canChooseFiles: canChooseFiles,
baseOptions: baseOptions
)
}
func toList() -> [Any?] {
return [
allowsMultipleSelection,
canChooseDirectories,
canChooseFiles,
baseOptions.toList(),
]
}
}
private class FileSelectorApiCodecReader: FlutterStandardReader {
override func readValue(ofType type: UInt8) -> Any? {
switch type {
case 128:
return AllowedTypes.fromList(self.readValue() as! [Any?])
case 129:
return OpenPanelOptions.fromList(self.readValue() as! [Any?])
case 130:
return SavePanelOptions.fromList(self.readValue() as! [Any?])
default:
return super.readValue(ofType: type)
}
}
}
private class FileSelectorApiCodecWriter: FlutterStandardWriter {
override func writeValue(_ value: Any) {
if let value = value as? AllowedTypes {
super.writeByte(128)
super.writeValue(value.toList())
} else if let value = value as? OpenPanelOptions {
super.writeByte(129)
super.writeValue(value.toList())
} else if let value = value as? SavePanelOptions {
super.writeByte(130)
super.writeValue(value.toList())
} else {
super.writeValue(value)
}
}
}
private class FileSelectorApiCodecReaderWriter: FlutterStandardReaderWriter {
override func reader(with data: Data) -> FlutterStandardReader {
return FileSelectorApiCodecReader(data: data)
}
override func writer(with data: NSMutableData) -> FlutterStandardWriter {
return FileSelectorApiCodecWriter(data: data)
}
}
class FileSelectorApiCodec: FlutterStandardMessageCodec {
static let shared = FileSelectorApiCodec(readerWriter: FileSelectorApiCodecReaderWriter())
}
/// Generated protocol from Pigeon that represents a handler of messages from Flutter.
protocol FileSelectorApi {
/// Shows an open panel with the given [options], returning the list of
/// selected paths.
///
/// An empty list corresponds to a cancelled selection.
func displayOpenPanel(
options: OpenPanelOptions, completion: @escaping (Result<[String?], Error>) -> Void)
/// Shows a save panel with the given [options], returning the selected path.
///
/// A null return corresponds to a cancelled save.
func displaySavePanel(
options: SavePanelOptions, completion: @escaping (Result<String?, Error>) -> Void)
}
/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`.
class FileSelectorApiSetup {
/// The codec used by FileSelectorApi.
static var codec: FlutterStandardMessageCodec { FileSelectorApiCodec.shared }
/// Sets up an instance of `FileSelectorApi` to handle messages through the `binaryMessenger`.
static func setUp(binaryMessenger: FlutterBinaryMessenger, api: FileSelectorApi?) {
/// Shows an open panel with the given [options], returning the list of
/// selected paths.
///
/// An empty list corresponds to a cancelled selection.
let displayOpenPanelChannel = FlutterBasicMessageChannel(
name: "dev.flutter.pigeon.FileSelectorApi.displayOpenPanel", binaryMessenger: binaryMessenger,
codec: codec)
if let api = api {
displayOpenPanelChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let optionsArg = args[0] as! OpenPanelOptions
api.displayOpenPanel(options: optionsArg) { result in
switch result {
case .success(let res):
reply(wrapResult(res))
case .failure(let error):
reply(wrapError(error))
}
}
}
} else {
displayOpenPanelChannel.setMessageHandler(nil)
}
/// Shows a save panel with the given [options], returning the selected path.
///
/// A null return corresponds to a cancelled save.
let displaySavePanelChannel = FlutterBasicMessageChannel(
name: "dev.flutter.pigeon.FileSelectorApi.displaySavePanel", binaryMessenger: binaryMessenger,
codec: codec)
if let api = api {
displaySavePanelChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let optionsArg = args[0] as! SavePanelOptions
api.displaySavePanel(options: optionsArg) { result in
switch result {
case .success(let res):
reply(wrapResult(res))
case .failure(let error):
reply(wrapError(error))
}
}
}
} else {
displaySavePanelChannel.setMessageHandler(nil)
}
}
}
| packages/packages/file_selector/file_selector_macos/macos/Classes/messages.g.swift/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/macos/Classes/messages.g.swift",
"repo_id": "packages",
"token_count": 2753
} | 947 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show immutable;
import 'x_type_group.dart';
export 'x_type_group.dart';
/// The response from a save dialog.
@immutable
class FileSaveLocation {
/// Creates a result with the given [path] and optional other dialog state.
const FileSaveLocation(this.path, {this.activeFilter});
/// The path to save to.
final String path;
/// The currently active filter group, if any.
///
/// This is null on platforms that do not support user-selectable filter
/// groups in save dialogs (for example, macOS), or when no filter groups
/// were provided when showing the dialog.
final XTypeGroup? activeFilter;
}
| packages/packages/file_selector/file_selector_platform_interface/lib/src/types/file_save_location.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_platform_interface/lib/src/types/file_save_location.dart",
"repo_id": "packages",
"token_count": 228
} | 948 |
name: file_selector_web_integration_tests
publish_to: none
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
file_selector_platform_interface: ^2.6.0
file_selector_web:
path: ../
flutter:
sdk: flutter
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| packages/packages/file_selector/file_selector_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 151
} | 949 |
// 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:file_selector_windows/file_selector_windows.dart';
import 'package:file_selector_windows/src/messages.g.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'file_selector_windows_test.mocks.dart';
import 'test_api.g.dart';
@GenerateMocks(<Type>[TestFileSelectorApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FileSelectorWindows plugin = FileSelectorWindows();
late MockTestFileSelectorApi mockApi;
setUp(() {
mockApi = MockTestFileSelectorApi();
TestFileSelectorApi.setup(mockApi);
});
test('registered instance', () {
FileSelectorWindows.registerWith();
expect(FileSelectorPlatform.instance, isA<FileSelectorWindows>());
});
group('openFile', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo']));
});
test('simple call works', () async {
final XFile? file = await plugin.openFile();
expect(file!.path, 'foo');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.openFile(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.openFile(confirmButtonText: 'Open File');
verify(mockApi.showOpenDialog(any, null, 'Open File'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
group('openFiles', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo', 'bar']));
});
test('simple call works', () async {
final List<XFile> file = await plugin.openFiles();
expect(file[0].path, 'foo');
expect(file[1].path, 'bar');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, true);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.openFiles(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.openFiles(confirmButtonText: 'Open Files');
verify(mockApi.showOpenDialog(any, null, 'Open Files'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
group('getDirectoryPath', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo']));
});
test('simple call works', () async {
final String? path = await plugin.getDirectoryPath();
expect(path, 'foo');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, true);
});
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Open Directory');
verify(mockApi.showOpenDialog(any, null, 'Open Directory'));
});
});
group('getDirectoryPaths', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo', 'bar']));
});
test('simple call works', () async {
final List<String?> paths = await plugin.getDirectoryPaths();
expect(paths[0], 'foo');
expect(paths[1], 'bar');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, true);
expect(options.selectFolders, true);
});
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Open Directory');
verify(mockApi.showOpenDialog(any, null, 'Open Directory'));
});
});
group('getSaveLocation', () {
setUp(() {
when(mockApi.showSaveDialog(any, any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo']));
});
test('simple call works', () async {
final FileSaveLocation? location = await plugin.getSaveLocation();
expect(location?.path, 'foo');
expect(location?.activeFilter, null);
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin
.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('returns the selected type group correctly', () async {
when(mockApi.showSaveDialog(any, any, any, any)).thenReturn(
FileDialogResult(paths: <String?>['foo'], typeGroupIndex: 1));
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
final FileSaveLocation? result = await plugin
.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
verify(mockApi.showSaveDialog(captureAny, null, null, null));
expect(result?.activeFilter, groupTwo);
});
test('passes initialDirectory correctly', () async {
await plugin.getSaveLocation(
options:
const SaveDialogOptions(initialDirectory: '/example/directory'));
verify(mockApi.showSaveDialog(any, '/example/directory', null, null));
});
test('passes suggestedName correctly', () async {
await plugin.getSaveLocation(
options: const SaveDialogOptions(suggestedName: 'baz.txt'));
verify(mockApi.showSaveDialog(any, null, 'baz.txt', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getSaveLocation(
options: const SaveDialogOptions(confirmButtonText: 'Save File'));
verify(mockApi.showSaveDialog(any, null, null, 'Save File'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
completes);
});
});
group('getSavePath (deprecated)', () {
setUp(() {
when(mockApi.showSaveDialog(any, any, any, any))
.thenReturn(FileDialogResult(paths: <String?>['foo']));
});
test('simple call works', () async {
final String? path = await plugin.getSavePath();
expect(path, 'foo');
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin
.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.getSavePath(initialDirectory: '/example/directory');
verify(mockApi.showSaveDialog(any, '/example/directory', null, null));
});
test('passes suggestedName correctly', () async {
await plugin.getSavePath(suggestedName: 'baz.txt');
verify(mockApi.showSaveDialog(any, null, 'baz.txt', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getSavePath(confirmButtonText: 'Save File');
verify(mockApi.showSaveDialog(any, null, null, 'Save File'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
completes);
});
});
}
// True if the given options match.
//
// This is needed because Pigeon data classes don't have custom equality checks,
// so only match for identical instances.
bool _typeGroupListsMatch(List<TypeGroup?> a, List<TypeGroup?> b) {
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!_typeGroupsMatch(a[i], b[i])) {
return false;
}
}
return true;
}
// True if the given type groups match.
//
// This is needed because Pigeon data classes don't have custom equality checks,
// so only match for identical instances.
bool _typeGroupsMatch(TypeGroup? a, TypeGroup? b) {
return a!.label == b!.label && listEquals(a.extensions, b.extensions);
}
| packages/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart",
"repo_id": "packages",
"token_count": 5873
} | 950 |
// 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/material.dart';
import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart';
void main() {
runApp(const MyApp());
}
/// The main application widget for this example.
class MyApp extends StatelessWidget {
/// Creates a const main application widget.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
/// Creates a basic adaptive page with navigational elements and a body using
/// [AdaptiveLayout].
class MyHomePage extends StatefulWidget {
/// Creates a const [MyHomePage].
const MyHomePage({super.key, this.transitionDuration = 1000});
/// Declare transition duration.
final int transitionDuration;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selectedNavigation = 0;
int _transitionDuration = 1000;
// Initialize transition time variable.
@override
void initState() {
super.initState();
setState(() {
_transitionDuration = widget.transitionDuration;
});
}
@override
Widget build(BuildContext context) {
final NavigationRailThemeData navRailTheme =
Theme.of(context).navigationRailTheme;
// Define the children to display within the body.
final List<Widget> children = List<Widget>.generate(10, (int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
color: const Color.fromARGB(255, 255, 201, 197),
height: 400,
),
);
});
final Widget trailingNavRail = Column(
children: <Widget>[
const Divider(color: Colors.black),
const SizedBox(height: 10),
const Row(
children: <Widget>[
SizedBox(width: 27),
Text('Folders', style: TextStyle(fontSize: 16)),
],
),
const SizedBox(height: 10),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text(
'Freelance',
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 12),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text(
'Mortgage',
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 12),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text('Taxes', overflow: TextOverflow.ellipsis),
),
],
),
const SizedBox(height: 12),
Row(
children: <Widget>[
const SizedBox(width: 16),
IconButton(
onPressed: () {},
icon: const Icon(Icons.folder_copy_outlined),
iconSize: 21,
),
const SizedBox(width: 21),
const Flexible(
child: Text('Receipts', overflow: TextOverflow.ellipsis),
),
],
),
],
);
// Define the list of destinations to be used within the app.
const List<NavigationDestination> destinations = <NavigationDestination>[
NavigationDestination(
label: 'Inbox',
icon: Icon(Icons.inbox_outlined),
selectedIcon: Icon(Icons.inbox),
),
NavigationDestination(
label: 'Articles',
icon: Icon(Icons.article_outlined),
selectedIcon: Icon(Icons.article),
),
NavigationDestination(
label: 'Chat',
icon: Icon(Icons.chat_outlined),
selectedIcon: Icon(Icons.chat),
),
NavigationDestination(
label: 'Video',
icon: Icon(Icons.video_call_outlined),
selectedIcon: Icon(Icons.video_call),
),
];
// #docregion Example
// AdaptiveLayout has a number of slots that take SlotLayouts and these
// SlotLayouts' configs take maps of Breakpoints to SlotLayoutConfigs.
return AdaptiveLayout(
// An option to override the default transition duration.
transitionDuration: Duration(milliseconds: _transitionDuration),
// Primary navigation config has nothing from 0 to 600 dp screen width,
// then an unextended NavigationRail with no labels and just icons then an
// extended NavigationRail with both icons and labels.
primaryNavigation: SlotLayout(
config: <Breakpoint, SlotLayoutConfig>{
Breakpoints.medium: SlotLayout.from(
inAnimation: AdaptiveScaffold.leftOutIn,
key: const Key('Primary Navigation Medium'),
builder: (_) => AdaptiveScaffold.standardNavigationRail(
selectedIndex: selectedNavigation,
onDestinationSelected: (int newIndex) {
setState(() {
selectedNavigation = newIndex;
});
},
leading: const Icon(Icons.menu),
destinations: destinations
.map((NavigationDestination destination) =>
AdaptiveScaffold.toRailDestination(destination))
.toList(),
backgroundColor: navRailTheme.backgroundColor,
selectedIconTheme: navRailTheme.selectedIconTheme,
unselectedIconTheme: navRailTheme.unselectedIconTheme,
selectedLabelTextStyle: navRailTheme.selectedLabelTextStyle,
unSelectedLabelTextStyle: navRailTheme.unselectedLabelTextStyle,
),
),
Breakpoints.large: SlotLayout.from(
key: const Key('Primary Navigation Large'),
inAnimation: AdaptiveScaffold.leftOutIn,
builder: (_) => AdaptiveScaffold.standardNavigationRail(
selectedIndex: selectedNavigation,
onDestinationSelected: (int newIndex) {
setState(() {
selectedNavigation = newIndex;
});
},
extended: true,
leading: const Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
'REPLY',
style: TextStyle(color: Color.fromARGB(255, 255, 201, 197)),
),
Icon(Icons.menu_open)
],
),
destinations: destinations
.map((NavigationDestination destination) =>
AdaptiveScaffold.toRailDestination(destination))
.toList(),
trailing: trailingNavRail,
backgroundColor: navRailTheme.backgroundColor,
selectedIconTheme: navRailTheme.selectedIconTheme,
unselectedIconTheme: navRailTheme.unselectedIconTheme,
selectedLabelTextStyle: navRailTheme.selectedLabelTextStyle,
unSelectedLabelTextStyle: navRailTheme.unselectedLabelTextStyle,
),
),
},
),
// Body switches between a ListView and a GridView from small to medium
// breakpoints and onwards.
body: SlotLayout(
config: <Breakpoint, SlotLayoutConfig>{
Breakpoints.small: SlotLayout.from(
key: const Key('Body Small'),
builder: (_) => ListView.builder(
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
),
),
Breakpoints.mediumAndUp: SlotLayout.from(
key: const Key('Body Medium'),
builder: (_) =>
GridView.count(crossAxisCount: 2, children: children),
)
},
),
// BottomNavigation is only active in small views defined as under 600 dp
// width.
bottomNavigation: SlotLayout(
config: <Breakpoint, SlotLayoutConfig>{
Breakpoints.small: SlotLayout.from(
key: const Key('Bottom Navigation Small'),
inAnimation: AdaptiveScaffold.bottomToTop,
outAnimation: AdaptiveScaffold.topToBottom,
builder: (_) => AdaptiveScaffold.standardBottomNavigationBar(
destinations: destinations,
currentIndex: selectedNavigation,
onDestinationSelected: (int newIndex) {
setState(() {
selectedNavigation = newIndex;
});
},
),
)
},
),
);
// #enddocregion Example
}
}
| packages/packages/flutter_adaptive_scaffold/example/lib/adaptive_layout_demo.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/lib/adaptive_layout_demo.dart",
"repo_id": "packages",
"token_count": 4387
} | 951 |
// 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';
import 'package:flutter/widgets.dart';
import 'breakpoints.dart';
import 'slot_layout.dart';
enum _SlotIds {
primaryNavigation,
secondaryNavigation,
topNavigation,
bottomNavigation,
body,
secondaryBody,
}
/// Layout an app that adapts to different screens using predefined slots.
///
/// This widget separates the app window into predefined sections called
/// "slots". It lays out the app using the following kinds of slots (in order):
///
/// * [topNavigation], full width at the top. Must have defined size.
/// * [bottomNavigation], full width at the bottom. Must have defined size.
/// * [primaryNavigation], displayed on the beginning side of the app window
/// from the bottom of [topNavigation] to the top of [bottomNavigation]. Must
/// have defined size.
/// * [secondaryNavigation], displayed on the end side of the app window from
/// the bottom of [topNavigation] to the top of [bottomNavigation]. Must have
/// defined size.
/// * [body], first panel; fills the remaining space from the beginning side.
/// The main view should have flexible size (like a container).
/// * [secondaryBody], second panel; fills the remaining space from the end
/// side. The use of this property is common in apps that have a main view
/// and a detail view. The main view should have flexible size (like a
/// Container). This provides some automatic functionality with foldable
/// screens.
///
/// Slots can display differently under different screen conditions (such as
/// different widths), and each slot is defined with a [SlotLayout], which maps
/// [Breakpoint]s to [SlotLayoutConfig], where [SlotLayoutConfig] defines the
/// content and transition.
///
/// [AdaptiveLayout] handles the placement of the slots on the app window and
/// animations regarding their macromovements.
///
/// ```dart
/// AdaptiveLayout(
/// primaryNavigation: SlotLayout(
/// config: {
/// Breakpoints.small: SlotLayout.from(
/// key: const Key('Primary Navigation Small'),
/// builder: (_) => const SizedBox.shrink(),
/// ),
/// Breakpoints.medium: SlotLayout.from(
/// inAnimation: leftOutIn,
/// key: const Key('Primary Navigation Medium'),
/// builder: (_) => AdaptiveScaffold.toNavigationRail(destinations: destinations),
/// ),
/// Breakpoints.large: SlotLayout.from(
/// key: const Key('Primary Navigation Large'),
/// inAnimation: leftOutIn,
/// builder: (_) => AdaptiveScaffold.toNavigationRail(extended: true, destinations: destinations),
/// ),
/// },
/// ),
/// body: SlotLayout(
/// config: {
/// Breakpoints.small: SlotLayout.from(
/// key: const Key('Body Small'),
/// builder: (_) => ListView.builder(
/// itemCount: children.length,
/// itemBuilder: (_, idx) => children[idx]
/// ),
/// ),
/// Breakpoints.medium: SlotLayout.from(
/// key: const Key('Body Medium'),
/// builder: (_) => GridView.count(
/// crossAxisCount: 2,
/// children: children
/// ),
/// ),
/// },
/// ),
/// bottomNavigation: SlotLayout(
/// config: {
/// Breakpoints.small: SlotLayout.from(
/// key: const Key('Bottom Navigation Small'),
/// inAnimation: bottomToTop,
/// builder: (_) => AdaptiveScaffold.toBottomNavigationBar(destinations: destinations),
/// ),
/// },
/// ),
/// )
/// ```
///
/// See also:
///
/// * [SlotLayout], which handles the actual switching and animations between
/// elements based on [Breakpoint]s.
/// * [SlotLayout.from], which holds information regarding the actual Widgets
/// and the desired way to animate between switches. Often used within
/// [SlotLayout].
/// * [AdaptiveScaffold], which provides a more friendly API with less
/// customizability. and holds a preset of animations and helper builders.
/// * [Design Doc](https://flutter.dev/go/adaptive-layout-foldables).
/// * [Material Design 3 Specifications](https://m3.material.io/foundations/adaptive-design/overview).
class AdaptiveLayout extends StatefulWidget {
/// Creates a const [AdaptiveLayout] widget.
const AdaptiveLayout({
super.key,
this.topNavigation,
this.primaryNavigation,
this.secondaryNavigation,
this.bottomNavigation,
this.body,
this.secondaryBody,
this.bodyRatio,
this.transitionDuration = const Duration(seconds: 1),
this.internalAnimations = true,
this.bodyOrientation = Axis.horizontal,
});
/// The slot placed on the beginning side of the app window.
///
/// The beginning side means the right when the ambient [Directionality] is
/// [TextDirection.rtl] and on the left when it is [TextDirection.ltr].
///
/// If the content is a flexibly sized Widget like [Container], wrap the
/// content in a [SizedBox] or limit its size (width and height) by another
/// method. See the builder in [AdaptiveScaffold.standardNavigationRail] for
/// an example.
final SlotLayout? primaryNavigation;
/// The slot placed on the end side of the app window.
///
/// The end side means the right when the ambient [Directionality] is
/// [TextDirection.ltr] and on the left when it is [TextDirection.rtl].
///
/// If the content is a flexibly sized Widget like [Container], wrap the
/// content in a [SizedBox] or limit its size (width and height) by another
/// method. See the builder in [AdaptiveScaffold.standardNavigationRail] for
/// an example.
final SlotLayout? secondaryNavigation;
/// The slot placed on the top part of the app window.
///
/// If the content is a flexibly sized Widget like [Container], wrap the
/// content in a [SizedBox] or limit its size (width and height) by another
/// method. See the builder in [AdaptiveScaffold.standardNavigationRail] for
/// an example.
final SlotLayout? topNavigation;
/// The slot placed on the bottom part of the app window.
///
/// If the content is a flexibly sized Widget like [Container], wrap the
/// content in a [SizedBox] or limit its size (width and height) by another
/// method. See the builder in [AdaptiveScaffold.standardNavigationRail] for
/// an example.
final SlotLayout? bottomNavigation;
/// The slot that fills the rest of the space in the center.
final SlotLayout? body;
/// A supporting slot for [body].
///
/// The [secondaryBody] as a sliding entrance animation by default.
///
/// The default ratio for the split between [body] and [secondaryBody] is so
/// that the split axis is in the center of the app window when there is no
/// hinge and surrounding the hinge when there is one.
final SlotLayout? secondaryBody;
/// Defines the fractional ratio of [body] to the [secondaryBody].
///
/// For example 0.3 would mean [body] takes up 30% of the available space
/// and[secondaryBody] takes up the rest.
///
/// If this value is null, the ratio is defined so that the split axis is in
/// the center of the app window when there is no hinge and surrounding the
/// hinge when there is one.
final double? bodyRatio;
/// Defines the duration of transition between layouts.
///
/// Defaults to [Duration(seconds: 1)].
final Duration transitionDuration;
/// Whether or not the developer wants the smooth entering slide transition on
/// [secondaryBody].
///
/// Defaults to true.
final bool internalAnimations;
/// The orientation of the body and secondaryBody. Either horizontal (side by
/// side) or vertical (top to bottom).
///
/// Defaults to Axis.horizontal.
final Axis bodyOrientation;
@override
State<AdaptiveLayout> createState() => _AdaptiveLayoutState();
}
class _AdaptiveLayoutState extends State<AdaptiveLayout>
with TickerProviderStateMixin {
late AnimationController _controller;
late Map<String, SlotLayoutConfig?> chosenWidgets =
<String, SlotLayoutConfig?>{};
Map<String, Size?> slotSizes = <String, Size?>{};
Map<String, ValueNotifier<Key?>> notifiers = <String, ValueNotifier<Key?>>{};
Set<String> isAnimating = <String>{};
@override
void initState() {
if (widget.internalAnimations) {
_controller = AnimationController(
duration: widget.transitionDuration,
vsync: this,
)..forward();
} else {
_controller = AnimationController(
duration: Duration.zero,
vsync: this,
);
}
for (final _SlotIds item in _SlotIds.values) {
notifiers[item.name] = ValueNotifier<Key?>(null)
..addListener(() {
isAnimating.add(item.name);
_controller.reset();
_controller.forward();
});
}
_controller.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
isAnimating.clear();
}
});
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Map<String, SlotLayout?> slots = <String, SlotLayout?>{
_SlotIds.primaryNavigation.name: widget.primaryNavigation,
_SlotIds.secondaryNavigation.name: widget.secondaryNavigation,
_SlotIds.topNavigation.name: widget.topNavigation,
_SlotIds.bottomNavigation.name: widget.bottomNavigation,
_SlotIds.body.name: widget.body,
_SlotIds.secondaryBody.name: widget.secondaryBody,
};
chosenWidgets = <String, SlotLayoutConfig?>{};
slots.forEach((String key, SlotLayout? value) {
slots.update(
key,
(SlotLayout? val) => val,
ifAbsent: () => value,
);
chosenWidgets.update(
key,
(SlotLayoutConfig? val) => val,
ifAbsent: () => SlotLayout.pickWidget(
context, value?.config ?? <Breakpoint, SlotLayoutConfig?>{}),
);
});
final List<Widget> entries = slots.entries
.map((MapEntry<String, SlotLayout?> entry) {
if (entry.value != null) {
return LayoutId(
id: entry.key, child: entry.value ?? const SizedBox());
}
})
.whereType<Widget>()
.toList();
notifiers.forEach((String key, ValueNotifier<Key?> notifier) {
notifier.value = chosenWidgets[key]?.key;
});
Rect? hinge;
for (final DisplayFeature e in MediaQuery.of(context).displayFeatures) {
if (e.type == DisplayFeatureType.hinge ||
e.type == DisplayFeatureType.fold) {
if (e.bounds.left != 0) {
hinge = e.bounds;
}
}
}
return CustomMultiChildLayout(
delegate: _AdaptiveLayoutDelegate(
slots: slots,
chosenWidgets: chosenWidgets,
slotSizes: slotSizes,
controller: _controller,
bodyRatio: widget.bodyRatio,
isAnimating: isAnimating,
internalAnimations: widget.internalAnimations,
bodyOrientation: widget.bodyOrientation,
textDirection: Directionality.of(context) == TextDirection.ltr,
hinge: hinge,
),
children: entries,
);
}
}
/// The delegate responsible for laying out the slots in their correct
/// positions.
class _AdaptiveLayoutDelegate extends MultiChildLayoutDelegate {
_AdaptiveLayoutDelegate({
required this.slots,
required this.chosenWidgets,
required this.slotSizes,
required this.controller,
required this.bodyRatio,
required this.isAnimating,
required this.internalAnimations,
required this.bodyOrientation,
required this.textDirection,
this.hinge,
}) : super(relayout: controller);
final Map<String, SlotLayout?> slots;
final Map<String, SlotLayoutConfig?> chosenWidgets;
final Map<String, Size?> slotSizes;
final Set<String> isAnimating;
final AnimationController controller;
final double? bodyRatio;
final bool internalAnimations;
final Axis bodyOrientation;
final bool textDirection;
final Rect? hinge;
@override
void performLayout(Size size) {
double leftMargin = 0;
double topMargin = 0;
double rightMargin = 0;
double bottomMargin = 0;
// An animation that is used as either a width or height value on the Size
// for the body/secondaryBody.
double animatedSize(double begin, double end) {
if (isAnimating.contains(_SlotIds.secondaryBody.name)) {
return internalAnimations
? Tween<double>(begin: begin, end: end)
.animate(CurvedAnimation(
parent: controller, curve: Curves.easeInOutCubic))
.value
: end;
}
return end;
}
if (hasChild(_SlotIds.topNavigation.name)) {
final Size childSize = layoutChild(
_SlotIds.topNavigation.name,
BoxConstraints.loose(size),
);
// Trigger the animation if the new size is different from the old size.
updateSize(_SlotIds.topNavigation.name, childSize);
// Tween not the actual size, but the size that is used in the margins so
// the offsets can be animated.
final Size currentSize = Tween<Size>(
begin: slotSizes[_SlotIds.topNavigation.name] ?? Size.zero,
end: childSize,
).animate(controller).value;
positionChild(_SlotIds.topNavigation.name, Offset.zero);
topMargin += currentSize.height;
}
if (hasChild(_SlotIds.bottomNavigation.name)) {
final Size childSize = layoutChild(
_SlotIds.bottomNavigation.name,
BoxConstraints.loose(size),
);
updateSize(_SlotIds.bottomNavigation.name, childSize);
final Size currentSize = Tween<Size>(
begin: slotSizes[_SlotIds.bottomNavigation.name] ?? Size.zero,
end: childSize,
).animate(controller).value;
positionChild(
_SlotIds.bottomNavigation.name,
Offset(0, size.height - currentSize.height),
);
bottomMargin += currentSize.height;
}
if (hasChild(_SlotIds.primaryNavigation.name)) {
final Size childSize = layoutChild(
_SlotIds.primaryNavigation.name,
BoxConstraints.loose(size),
);
updateSize(_SlotIds.primaryNavigation.name, childSize);
final Size currentSize = Tween<Size>(
begin: slotSizes[_SlotIds.primaryNavigation.name] ?? Size.zero,
end: childSize,
).animate(controller).value;
if (textDirection) {
positionChild(
_SlotIds.primaryNavigation.name,
Offset(leftMargin, topMargin),
);
leftMargin += currentSize.width;
} else {
positionChild(
_SlotIds.primaryNavigation.name,
Offset(size.width - currentSize.width, topMargin),
);
rightMargin += currentSize.width;
}
}
if (hasChild(_SlotIds.secondaryNavigation.name)) {
final Size childSize = layoutChild(
_SlotIds.secondaryNavigation.name,
BoxConstraints.loose(size),
);
updateSize(_SlotIds.secondaryNavigation.name, childSize);
final Size currentSize = Tween<Size>(
begin: slotSizes[_SlotIds.secondaryNavigation.name] ?? Size.zero,
end: childSize,
).animate(controller).value;
if (textDirection) {
positionChild(
_SlotIds.secondaryNavigation.name,
Offset(size.width - currentSize.width, topMargin),
);
rightMargin += currentSize.width;
} else {
positionChild(_SlotIds.secondaryNavigation.name, Offset(0, topMargin));
leftMargin += currentSize.width;
}
}
final double remainingWidth = size.width - rightMargin - leftMargin;
final double remainingHeight = size.height - bottomMargin - topMargin;
final double halfWidth = size.width / 2;
final double halfHeight = size.height / 2;
final double hingeWidth = hinge != null ? hinge!.right - hinge!.left : 0;
if (hasChild(_SlotIds.body.name) && hasChild(_SlotIds.secondaryBody.name)) {
Size currentBodySize = Size.zero;
Size currentSBodySize = Size.zero;
if (chosenWidgets[_SlotIds.secondaryBody.name] == null ||
chosenWidgets[_SlotIds.secondaryBody.name]!.builder == null) {
if (!textDirection) {
currentBodySize = layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(remainingWidth, remainingHeight),
),
);
} else if (bodyOrientation == Axis.horizontal) {
double beginWidth;
if (bodyRatio == null) {
beginWidth = halfWidth - leftMargin;
} else {
beginWidth = remainingWidth * bodyRatio!;
}
currentBodySize = layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(animatedSize(beginWidth, remainingWidth), remainingHeight),
),
);
} else {
double beginHeight;
if (bodyRatio == null) {
beginHeight = halfHeight - topMargin;
} else {
beginHeight = remainingHeight * bodyRatio!;
}
currentBodySize = layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(remainingWidth, animatedSize(beginHeight, remainingHeight)),
),
);
}
layoutChild(_SlotIds.secondaryBody.name, BoxConstraints.loose(size));
} else {
if (bodyOrientation == Axis.horizontal) {
// Take this path if the body and secondaryBody are laid out horizontally.
if (textDirection) {
// Take this path if the textDirection is LTR.
double finalBodySize;
double finalSBodySize;
if (hinge != null) {
finalBodySize = hinge!.left - leftMargin;
finalSBodySize =
size.width - (hinge!.left + hingeWidth) - rightMargin;
} else if (bodyRatio != null) {
finalBodySize = remainingWidth * bodyRatio!;
finalSBodySize = remainingWidth * (1 - bodyRatio!);
} else {
finalBodySize = halfWidth - leftMargin;
finalSBodySize = halfWidth - rightMargin;
}
currentBodySize = layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(animatedSize(remainingWidth, finalBodySize),
remainingHeight),
),
);
layoutChild(
_SlotIds.secondaryBody.name,
BoxConstraints.tight(
Size(finalSBodySize, remainingHeight),
),
);
} else {
// Take this path if the textDirection is RTL.
double finalBodySize;
double finalSBodySize;
if (hinge != null) {
finalBodySize =
size.width - (hinge!.left + hingeWidth) - rightMargin;
finalSBodySize = hinge!.left - leftMargin;
} else if (bodyRatio != null) {
finalBodySize = remainingWidth * bodyRatio!;
finalSBodySize = remainingWidth * (1 - bodyRatio!);
} else {
finalBodySize = halfWidth - rightMargin;
finalSBodySize = halfWidth - leftMargin;
}
currentSBodySize = layoutChild(
_SlotIds.secondaryBody.name,
BoxConstraints.tight(
Size(animatedSize(0, finalSBodySize), remainingHeight),
),
);
layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(finalBodySize, remainingHeight),
),
);
}
} else {
// Take this path if the body and secondaryBody are laid out vertically.
currentBodySize = layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(
remainingWidth,
animatedSize(
remainingHeight,
bodyRatio == null
? halfHeight - topMargin
: remainingHeight * bodyRatio!,
),
),
),
);
layoutChild(
_SlotIds.secondaryBody.name,
BoxConstraints.tight(
Size(
remainingWidth,
bodyRatio == null
? halfHeight - bottomMargin
: remainingHeight * (1 - bodyRatio!),
),
),
);
}
}
// Handle positioning for the body and secondaryBody.
if (bodyOrientation == Axis.horizontal &&
!textDirection &&
chosenWidgets[_SlotIds.secondaryBody.name] != null) {
if (hinge != null) {
positionChild(
_SlotIds.body.name,
Offset(currentSBodySize.width + leftMargin + hingeWidth, topMargin),
);
positionChild(
_SlotIds.secondaryBody.name, Offset(leftMargin, topMargin));
} else {
positionChild(
_SlotIds.body.name,
Offset(currentSBodySize.width + leftMargin, topMargin),
);
positionChild(
_SlotIds.secondaryBody.name, Offset(leftMargin, topMargin));
}
} else {
positionChild(_SlotIds.body.name, Offset(leftMargin, topMargin));
if (bodyOrientation == Axis.horizontal) {
if (hinge != null) {
positionChild(
_SlotIds.secondaryBody.name,
Offset(
currentBodySize.width + leftMargin + hingeWidth, topMargin),
);
} else {
positionChild(
_SlotIds.secondaryBody.name,
Offset(currentBodySize.width + leftMargin, topMargin),
);
}
} else {
positionChild(
_SlotIds.secondaryBody.name,
Offset(leftMargin, topMargin + currentBodySize.height),
);
}
}
} else if (hasChild(_SlotIds.body.name)) {
layoutChild(
_SlotIds.body.name,
BoxConstraints.tight(
Size(remainingWidth, remainingHeight),
),
);
positionChild(_SlotIds.body.name, Offset(leftMargin, topMargin));
} else if (hasChild(_SlotIds.secondaryBody.name)) {
layoutChild(
_SlotIds.secondaryBody.name,
BoxConstraints.tight(
Size(remainingWidth, remainingHeight),
),
);
}
}
void updateSize(String id, Size childSize) {
if (slotSizes[id] == null || slotSizes[id] != childSize) {
void listener(AnimationStatus status) {
if ((status == AnimationStatus.completed ||
status == AnimationStatus.dismissed) &&
(slotSizes[id] == null || slotSizes[id] != childSize)) {
slotSizes[id] = childSize;
}
controller.removeStatusListener(listener);
}
controller.addStatusListener(listener);
}
}
@override
bool shouldRelayout(_AdaptiveLayoutDelegate oldDelegate) {
return oldDelegate.slots != slots;
}
}
| packages/packages/flutter_adaptive_scaffold/lib/src/adaptive_layout.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/lib/src/adaptive_layout.dart",
"repo_id": "packages",
"token_count": 9445
} | 952 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: 796c8ef79279f9c774545b3771238c3098dbefab
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: android
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: ios
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: linux
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: macos
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: web
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: windows
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| packages/packages/flutter_image/example/.metadata/0 | {
"file_path": "packages/packages/flutter_image/example/.metadata",
"repo_id": "packages",
"token_count": 728
} | 953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.