text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
import 'package:flutter/material.dart' hide Card;
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:io_flip/audio/audio_controller.dart';
import 'package:io_flip/game/game.dart';
import 'package:io_flip/gen/assets.gen.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:mocktail/mocktail.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import '../../helpers/helpers.dart';
class _MockAudioController extends Mock implements AudioController {}
class _MockGameScriptMachine extends Mock implements GameScriptMachine {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('ClashScene', () {
const playerCard = Card(
id: 'player_card',
name: 'host_card',
description: '',
image: 'image.png',
rarity: true,
power: 2,
suit: Suit.air,
);
const firePlayerCard = Card(
id: 'fire_player_card',
name: 'fire_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 2,
suit: Suit.fire,
);
const earthPlayerCard = Card(
id: 'earth_player_card',
name: 'earth_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 2,
suit: Suit.earth,
);
const metalPlayerCard = Card(
id: 'metal_player_card',
name: 'metal_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 2,
suit: Suit.metal,
);
const waterPlayerCard = Card(
id: 'water_player_card',
name: 'water_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 2,
suit: Suit.water,
);
const waterPlayerCardWith11Power = Card(
id: 'water_player_card',
name: 'water_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 11,
suit: Suit.water,
);
const waterPlayerCardWith12Power = Card(
id: 'water_player_card',
name: 'water_host_card',
description: '',
image: 'image.png',
rarity: true,
power: 12,
suit: Suit.water,
);
const opponentCard = Card(
id: 'opponent_card',
name: 'guest_card',
description: '',
image: 'image.png',
rarity: true,
power: 1,
suit: Suit.air,
);
const waterOpponentCard = Card(
id: 'opponent_card',
name: 'guest_card',
description: '',
image: 'image.png',
rarity: true,
power: 1,
suit: Suit.water,
);
late GameScriptMachine gameScriptMachine;
setUp(() {
gameScriptMachine = _MockGameScriptMachine();
});
testWidgets('displays both cards flipped initially and plays "flip" sfx',
(tester) async {
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
playerCard,
opponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
playerCard.suit,
opponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
playerCard,
opponentCard,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
verify(() => audioController.playSfx(Assets.sfx.flip)).called(1);
expect(find.byType(FlippedGameCard), findsNWidgets(2));
});
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and does not plays any sfx because the elements are the same',
(tester) async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
playerCard,
opponentCard,
),
).thenReturn(0);
when(
() => gameScriptMachine.compareSuits(
playerCard.suit,
opponentCard.suit,
),
).thenReturn(0);
await tester.pumpSubject(
playerCard,
opponentCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await mockNetworkImages(() async {
await tester.pump(smallFlipAnimation.duration * 2);
});
final elementalDamage = find.byType(ElementalDamageAnimation);
verifyNever(() => audioController.playSfx(Assets.sfx.air));
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
expect(onFinishedCalled, isTrue);
},
);
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and plays "air" sfx',
(tester) => mockNetworkImages(() async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
playerCard,
waterOpponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
playerCard.suit,
waterOpponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
playerCard,
waterOpponentCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await tester.pump(smallFlipAnimation.duration * 2);
final elementalDamage = find.byType(ElementalDamageAnimation);
verify(() => audioController.playSfx(Assets.sfx.air)).called(1);
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
await tester.pumpAndSettle();
expect(onFinishedCalled, isTrue);
}),
);
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and plays "fire" sfx',
(tester) => mockNetworkImages(() async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
firePlayerCard,
opponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
firePlayerCard.suit,
opponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
firePlayerCard,
opponentCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await tester.pump(smallFlipAnimation.duration * 2);
final elementalDamage = find.byType(ElementalDamageAnimation);
verify(() => audioController.playSfx(Assets.sfx.fire)).called(1);
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
await tester.pumpAndSettle();
expect(onFinishedCalled, isTrue);
}),
);
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and plays "earth" sfx',
(tester) => mockNetworkImages(() async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
earthPlayerCard,
opponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
earthPlayerCard.suit,
opponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
earthPlayerCard,
opponentCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await tester.pump(smallFlipAnimation.duration * 2);
final elementalDamage = find.byType(ElementalDamageAnimation);
verify(() => audioController.playSfx(Assets.sfx.earth)).called(1);
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
await tester.pumpAndSettle();
expect(onFinishedCalled, isTrue);
}),
);
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and plays "metal" sfx',
(tester) => mockNetworkImages(() async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
opponentCard,
metalPlayerCard,
),
).thenReturn(-1);
when(
() => gameScriptMachine.compareSuits(
opponentCard.suit,
metalPlayerCard.suit,
),
).thenReturn(-1);
await tester.pumpSubject(
opponentCard,
metalPlayerCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await tester.pump(smallFlipAnimation.duration * 2);
final elementalDamage = find.byType(ElementalDamageAnimation);
verify(() => audioController.playSfx(Assets.sfx.metal)).called(1);
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
await tester.pumpAndSettle();
expect(onFinishedCalled, isTrue);
}),
);
testWidgets(
'plays damage animation then flips both cards after countdown'
' ,invokes onFinished callback when animation is complete'
' and plays "water" sfx',
(tester) => mockNetworkImages(() async {
var onFinishedCalled = false;
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(
waterPlayerCard,
opponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
waterPlayerCard.suit,
opponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
waterPlayerCard,
opponentCard,
onFinished: () => onFinishedCalled = true,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
final flipCountdown = find.byType(FlipCountdown);
expect(flipCountdown, findsOneWidget);
tester.widget<FlipCountdown>(flipCountdown).onComplete?.call();
await tester.pump(smallFlipAnimation.duration * 2);
final elementalDamage = find.byType(ElementalDamageAnimation);
verify(() => audioController.playSfx(Assets.sfx.water)).called(1);
expect(elementalDamage, findsOneWidget);
tester
.widget<ElementalDamageAnimation>(elementalDamage)
.onComplete
?.call();
tester
.state<ClashSceneState>(find.byType(ClashScene))
.onDamageRecieved();
await tester.pumpAndSettle();
expect(onFinishedCalled, isTrue);
}),
);
testWidgets(
'puts players card over opponents when suit is stronger',
(tester) async {
when(
() => gameScriptMachine.compare(
playerCard,
opponentCard,
),
).thenReturn(1);
when(
() => gameScriptMachine.compareSuits(
playerCard.suit,
opponentCard.suit,
),
).thenReturn(1);
await tester.pumpSubject(
playerCard,
opponentCard,
onFinished: () {},
gameScriptMachine: gameScriptMachine,
);
final stack = find.byWidgetPredicate((stack) {
if (stack is Stack) {
return stack.children.first.key == const Key('opponent_card') &&
stack.children[1].key == const Key('player_card');
}
return false;
});
expect(stack, findsOneWidget);
},
);
testWidgets(
'puts opponents card over players when suit is stronger',
(tester) async {
when(
() => gameScriptMachine.compare(
playerCard,
opponentCard,
),
).thenReturn(-1);
when(
() => gameScriptMachine.compareSuits(
playerCard.suit,
opponentCard.suit,
),
).thenReturn(-1);
await tester.pumpSubject(
playerCard,
opponentCard,
onFinished: () {},
gameScriptMachine: gameScriptMachine,
);
final stack = find.byWidgetPredicate((stack) {
if (stack is Stack) {
return stack.children.first.key == const Key('player_card') &&
stack.children[1].key == const Key('opponent_card');
}
return false;
});
expect(stack, findsOneWidget);
},
);
group('plays winning element sfx correctly', () {
String sfxBySuit(Suit suit) {
switch (suit) {
case Suit.fire:
return Assets.sfx.fire;
case Suit.air:
return Assets.sfx.air;
case Suit.earth:
return Assets.sfx.earth;
case Suit.metal:
return Assets.sfx.metal;
case Suit.water:
return Assets.sfx.water;
}
}
Future<void> testCards(
WidgetTester tester,
Card player,
Card opponent,
int compareResult,
int compareSuitsResult,
) async {
final audioController = _MockAudioController();
when(
() => gameScriptMachine.compare(player, opponent),
).thenReturn(compareResult);
when(
() => gameScriptMachine.compareSuits(player.suit, opponent.suit),
).thenReturn(compareSuitsResult);
await tester.pumpSubject(
player,
opponent,
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
tester
.widget<FlipCountdown>(find.byType(FlipCountdown))
.onComplete
?.call();
await tester.pump(smallFlipAnimation.duration * 2);
tester
.widget<ElementalDamageAnimation>(
find.byType(ElementalDamageAnimation),
)
.onComplete
?.call();
await tester.pumpAndSettle();
final playerSfxPlayed =
(compareResult == 1 ? 1 : 0) + (compareSuitsResult == 1 ? 1 : 0);
final opponentSfxPlayed =
(compareResult == -1 ? 1 : 0) + (compareSuitsResult == -1 ? 1 : 0);
if (playerSfxPlayed == 0) {
verifyNever(() => audioController.playSfx(sfxBySuit(player.suit)));
} else {
verify(
() => audioController.playSfx(sfxBySuit(player.suit)),
).called(playerSfxPlayed);
}
if (opponentSfxPlayed == 0) {
verifyNever(() => audioController.playSfx(sfxBySuit(opponent.suit)));
} else {
verify(
() => audioController.playSfx(sfxBySuit(opponent.suit)),
).called(opponentSfxPlayed);
}
}
/// Covers all cases.
testWidgets(
'air V.S. air',
(t) => testCards(t, playerCard, opponentCard, 0, 0),
);
testWidgets(
'fire V.S. water',
(t) => testCards(t, firePlayerCard, waterOpponentCard, 1, 1),
);
testWidgets(
'water V.S. air',
(t) => testCards(t, waterPlayerCard, opponentCard, -1, -1),
);
testWidgets(
'water11 V.S. air',
(t) => testCards(t, waterPlayerCardWith11Power, opponentCard, 0, -1),
);
testWidgets(
'water12 V.S. air',
(t) => testCards(t, waterPlayerCardWith12Power, opponentCard, 1, -1),
);
});
});
}
extension GameViewTest on WidgetTester {
Future<void> pumpSubject(
Card playerCard,
Card opponentCard, {
VoidCallback? onFinished,
AudioController? audioController,
GameScriptMachine? gameScriptMachine,
}) {
return pumpApp(
ClashScene(
onFinished: onFinished ?? () {},
opponentCard: opponentCard,
playerCard: playerCard,
),
audioController: audioController,
gameScriptMachine: gameScriptMachine,
);
}
}
| io_flip/test/game/widgets/clash_scene_test.dart/0 | {
"file_path": "io_flip/test/game/widgets/clash_scene_test.dart",
"repo_id": "io_flip",
"token_count": 8268
} | 886 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/leaderboard/leaderboard.dart';
void main() {
group('LeaderboardRequested', () {
test('can be instantiated', () {
expect(
LeaderboardRequested(),
isNotNull,
);
});
test('supports equality', () {
expect(
LeaderboardRequested(),
equals(
LeaderboardRequested(),
),
);
});
});
}
| io_flip/test/leaderboard/bloc/leaderboard_event_test.dart/0 | {
"file_path": "io_flip/test/leaderboard/bloc/leaderboard_event_test.dart",
"repo_id": "io_flip",
"token_count": 211
} | 887 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:io_flip/prompt/prompt.dart';
void main() {
group('PromptTermsRequested', () {
test('can be instantiated', () {
expect(PromptTermsRequested(), isNotNull);
});
test('supports equality', () {
expect(
PromptTermsRequested(),
equals(PromptTermsRequested()),
);
});
});
group('PromptSubmitted', () {
test('can be instantiated', () {
expect(PromptSubmitted(data: Prompt()), isNotNull);
});
test('supports equality', () {
expect(
PromptSubmitted(data: Prompt()),
equals(PromptSubmitted(data: Prompt())),
);
});
});
}
| io_flip/test/prompt/bloc/prompt_form_event_test.dart/0 | {
"file_path": "io_flip/test/prompt/bloc/prompt_form_event_test.dart",
"repo_id": "io_flip",
"token_count": 316
} | 888 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:io_flip/share/bloc/download_bloc.dart';
void main() {
const card = Card(
id: '0',
name: '',
description: '',
image: '',
rarity: false,
power: 20,
suit: Suit.fire,
);
const deck = Deck(id: '', userId: '', cards: [card]);
group('DownloadCardsRequested', () {
test('can be instantiated', () {
expect(
DownloadCardsRequested(cards: const [card]),
isNotNull,
);
});
test('supports equality', () {
expect(
DownloadCardsRequested(cards: const [card]),
equals(DownloadCardsRequested(cards: const [card])),
);
});
});
group('DownloadDeckRequested', () {
test('can be instantiated', () {
expect(
DownloadDeckRequested(deck: deck),
isNotNull,
);
});
test('supports equality', () {
expect(
DownloadDeckRequested(deck: deck),
equals(DownloadDeckRequested(deck: deck)),
);
});
});
}
| io_flip/test/share/bloc/download_event_test.dart/0 | {
"file_path": "io_flip/test/share/bloc/download_event_test.dart",
"repo_id": "io_flip",
"token_count": 473
} | 889 |
# π Flutter News Toolkit Docs Site
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
### βοΈ Installation
```
npm install
```
### π§βπ» Local Development
```
npm start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
### π¦ Build
```
npm run build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
| news_toolkit/docs/README.md/0 | {
"file_path": "news_toolkit/docs/README.md",
"repo_id": "news_toolkit",
"token_count": 155
} | 890 |
---
sidebar_position: 4
description: Learn how to configure or remove ads in your application.
---
# Ads setup or removal
The Flutter News Toolkit is pre-configured to work with Google Ad Manager or AdMob. Follow the configuration steps below if you would like to monetize your app with either of these services.
:::note
If you don't want to monetize your app with Google Ad Manager or AdMob, follow the instructions in the [Remove ads](#remove-ads) section.
:::
## Configure ads
### Google Ad Manager
[Google Ad Manager](https://admanager.google.com) offers publishers a complete ad revenue engine, helping clients streamline operations and capture the most value for every impression. To leverage this ad exchange platform in your app, visit [Google Ad Manager](https://admanager.google.com) and enter your Google Account username and password to sign in. If you don't have an account, [sign up for an Ad Manager account](https://admanager.google.com/home/contact-us/) to get started.
#### Create apps
After successfully creating an account or logging into an existing account, create an app for each platform and flavor. By default, you'll need an app for Android `development` and `production` flavors and iOS `development` and `production` flavors (4 apps total). If you created additional flavors when generating your project with mason, be sure to create corresponding apps in your Google Ad Manager.
#### Firebase configuraton
After generating your apps, return to your Firebase Console to link the Google Ad Manager apps to their respective Firebase apps in the **Engage --> AdMob** section of your Firebase project.
### Google AdMob
[Google AdMob](https://admob.google.com/home/) makes earning revenue easy with in-app ads, actionable insights, and powerful, easy-to-use tools that grow your app business. To use this service in your apps, visit Google AdMob to log in or [create an account](https://apps.admob.com/signup/?_ga=2.23772223.461135622.1667403019-1758917868.1667403019&_gl=1*akwl9n*_ga*MTc1ODkxNzg2OC4xNjY3NDAzMDE5*_ga_6R1K8XRD9P*MTY2NzQwMzAxOC4xLjAuMTY2NzQwMzEzOS4wLjAuMA..).
#### Create apps
After successfully creating an account or logging into an existing account, create an app for each platform and flavor. By default, you'll need an app for Android **development** and **production** flavors and iOS **development** and **production** flavors (4 apps total). If you created additional flavors when generating your project with mason, be sure to create corresponding apps in your Google AdMob account.
#### Firebase configuraton
After generating your apps, return to your Firebase Console to link the Google AdMob apps to their respective Firebase apps in the **Engage --> AdMob** section of your Firebase project.
### Swap ad IDs
Finally, you must specify your app IDs regardless of whether you are using Google AdMob or Google Ad Manager.
First, find your [Google Ad Manager app IDs](https://support.google.com/admanager/answer/1656921#copy-id) or [AdMob app IDs](https://support.google.com/admob/answer/7356431). For every app flavor's `strings.xml` file in your codebase, replace the placeholder value associated with the `admob_app_id` key with your flavor-specific app ID. Repeat this procedure and replace the placeholder value for every `ADMOB_APP_ID` key within your `project.pbxproj` file.
## Remove ads
You might want to remove advertisements from your app. This section discusses how to remove the various advertisement types and their dependencies.
### Removing banner ads
Banner ads in the `static_news_data.dart` file are displayed by default. To ensure that your app won't display `BannerAds`, don't insert `AdBlocks` into the data returned from your [data source](/server_development/connecting_your_data_source).
### Removing interstitial ads
By default, entering an article displays interstitial ads. To remove interstitial ads entirely, delete the following line from `_ArticleViewState`'s `initState` method (`lib/article/view/article_page.dart`):
```dart
context.read<FullScreenAdsBloc>().add(const ShowInterstitialAdRequested());
```
### Removing sticky ads
The template contains a sticky ad in `ArticleContent` (`lib/article/widgets/article_content.dart`). To remove it, delete the `StickyAd()` constructor call from the `ArticleContent` widget's `Stack.children`.
### Removing rewarded ads
Rewarded ads are built inside the `SubscribeWithArticleLimitModal` widget (`lib/subscriptions/widgets/subscribe_with_article_limit_modal.dart`).
To remove the rewarded ad option for premium articles, delete the "show rewarded ad" button block in the `SubscribeWithArticleLimitModal` widget:
```dart
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg + AppSpacing.xxs,
),
child: AppButton.transparentWhite(
key: const Key(
'subscribeWithArticleLimitModal_watchVideoButton',
),
onPressed: () => context
.read<FullScreenAdsBloc>()
.add(const ShowRewardedAdRequested()),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.video.svg(),
const SizedBox(width: AppSpacing.sm),
Text(watchVideoButtonTitle),
],
),
),
),
```
### Removing advertisement dependencies
When removing advertisements from your app, it's best to remove all advertisement-related dependencies from your codebase.
_Ad Source Code_
Remove the following directories and files entirely:
- `flutter_news_example/lib/ads`
- `flutter_news_example/test/ads`
- `flutter_news_example/packages/ads_consent_client`
- `flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_content.dart`
- `flutter_news_example/packages/news_blocks_ui/test/src/widgets/banner_ad_content_test.dart`
- `flutter_news_example/packages/news_blocks_ui/lib/src/banner_ad.dart`
- `flutter_news_example/packages/news_blocks_ui/test/src/banner_ad_test.dart`
Remove the noted snippets from the files below:
- `flutter_news_example/lib/app/view/app.dart`
```dart
required AdsConsentClient adsConsentClient,
```
```dart
_adsConsentClient = adsConsentClient,
```
```dart
final AdsConsentClient _adsConsentClient;
```
```dart
RepositoryProvider.value(value: _adsConsentClient),
```
```dart
BlocProvider(
create: (context) => FullScreenAdsBloc(
interstitialAdLoader: ads.InterstitialAd.load,
rewardedAdLoader: ads.RewardedAd.load,
adsRetryPolicy: const AdsRetryPolicy(),
localPlatform: const LocalPlatform(),
)
..add(const LoadInterstitialAdRequested())
..add(const LoadRewardedAdRequested()),
lazy: false,
),
```
- `flutter_news_example/lib/article/view/article_page.dart`
- `HasWatchedRewardedAdListener` class
- `HasWatchedRewardedAdListener` widget (retain the child `Scaffold` widget)
- `flutter_news_example/lib/main/main_development.dart`
```dart
final adsConsentClient = AdsConsentClient();
```
```dart
adsConsentClient: adsConsentClient,
```
- `flutter_news_example/lib/main/main_production.dart`
```dart
final adsConsentClient = AdsConsentClient();
```
```dart
adsConsentClient: adsConsentClient,
```
- `flutter_news_example/lib/onboarding/bloc/onboarding_bloc.dart`
```dart
required AdsConsentClient adsConsentClient,
```
```dart
_adsConsentClient = adsConsentClient,
```
```dart
on<EnableAdTrackingRequested>(
_onEnableAdTrackingRequested,
transformer: droppable(),
);
```
```dart
final AdsConsentClient _adsConsentClient;
```
- the `_onEnableAdTrackingRequested()` function
- `flutter_news_example/lib/onboarding/view/onboarding_page.dart`
```dart
adsConsentClient: context.read<AdsConsentClient>(),
```
- `flutter_news_example/lib/article/widgets/article_content_item.dart`
```dart
else if (newsBlock is BannerAdBlock) {
return BannerAd(
block: newsBlock,
adFailedToLoadTitle: context.l10n.adLoadFailure,
);
}
```
- `flutter_news_example/lib/article/widgets/article_content_item.dart`
```dart
else if (newsBlock is BannerAdBlock) {
return BannerAd(
block: newsBlock,
adFailedToLoadTitle: context.l10n.adLoadFailure,
);
}
```
- `flutter_news_example/packages/news_blocks_ui/lib/news_blocks_ui.dart`
```dart
export 'src/banner_ad.dart' show BannerAd;
```
- `flutter_news_example/packages/news_blocks_ui/lib/src/widgets/widges.dart`
```dart
export 'banner_ad_content.dart';
```
_Pubspec Ad Depenedencies_
Remove the `google_mobile_ads` dependency from the `flutter_news_example/packages/news_blocks_ui/pubspec.yaml` file, as well as all corresponding import statements:
```dart
import 'package:google_mobile_ads/google_mobile_ads.dart'
```
Remove the `ads_consent_client` dependency from `flutter_news_example/pubspec.yaml`, as well as all `ads_consent_client` and all `ads` import statements:
```dart
import 'package:ads_consent_client/ads_consent_client.dart';
import 'package:flutter_news_template/ads/ads.dart';
```
| news_toolkit/docs/docs/project_configuration/ads.md/0 | {
"file_path": "news_toolkit/docs/docs/project_configuration/ads.md",
"repo_id": "news_toolkit",
"token_count": 2974
} | 891 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.flutter.news.example">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.INTERNET"/>
<!--Required for Android 13 or above-->
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<application
android:name="${applicationName}"
android:label="${appName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<!-- Registered callback URL for deep linking -->
<data
android:host="@string/flavor_deep_link_domain"
android:scheme="https"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Registered callback URL for Twitter authentication -->
<data android:scheme="@string/twitter_redirect_uri_scheme" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Facebook authentication meta-data -->
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<meta-data
android:name="com.facebook.sdk.ClientToken"
android:value="@string/facebook_client_token"/>
<!-- Google AdMob meta-data -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="@string/admob_app_id"/>
<meta-data
android:name="io.flutter.plugins.googlemobileads.FLUTTER_NEWS_TEMPLATE_VERSION"
android:value="1.0.0"/>
</application>
</manifest>
| news_toolkit/flutter_news_example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "news_toolkit/flutter_news_example/android/app/src/main/AndroidManifest.xml",
"repo_id": "news_toolkit",
"token_count": 1694
} | 892 |
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:news_blocks/news_blocks.dart';
part 'article.g.dart';
/// {@template article}
/// A news article object which contains paginated contents.
/// {@endtemplate}
@JsonSerializable()
class Article extends Equatable {
/// {@macro article}
const Article({
required this.title,
required this.blocks,
required this.totalBlocks,
required this.url,
});
/// Converts a `Map<String, dynamic>` into a [Article] instance.
factory Article.fromJson(Map<String, dynamic> json) =>
_$ArticleFromJson(json);
/// The article title.
final String title;
/// The list of news blocks for the associated article (paginated).
@NewsBlocksConverter()
final List<NewsBlock> blocks;
/// The total number of blocks for this article.
final int totalBlocks;
/// The article url.
final Uri url;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$ArticleToJson(this);
@override
List<Object> get props => [title, blocks, totalBlocks, url];
}
| news_toolkit/flutter_news_example/api/lib/src/data/models/article.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/data/models/article.dart",
"repo_id": "news_toolkit",
"token_count": 355
} | 893 |
import 'package:dart_frog/dart_frog.dart';
/// A lightweight user object associated with an incoming [Request].
class RequestUser {
const RequestUser._({required this.id});
/// The unique user identifier.
final String id;
/// An anonymous user.
static const anonymous = RequestUser._(id: '');
/// Whether the user is anonymous.
bool get isAnonymous => this == RequestUser.anonymous;
}
/// Provider a [RequestUser] to the current [RequestContext].
Middleware userProvider() {
return (handler) {
return handler.use(
provider<RequestUser>((context) {
final userId = _extractUserId(context.request);
return userId != null
? RequestUser._(id: userId)
: RequestUser.anonymous;
}),
);
};
}
String? _extractUserId(Request request) {
final authorizationHeader = request.headers['authorization'];
if (authorizationHeader == null) return null;
final segments = authorizationHeader.split(' ');
if (segments.length != 2) return null;
if (segments.first.toLowerCase() != 'bearer') return null;
final userId = segments.last;
return userId;
}
| news_toolkit/flutter_news_example/api/lib/src/middleware/user_provider.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/middleware/user_provider.dart",
"repo_id": "news_toolkit",
"token_count": 364
} | 894 |
import 'package:equatable/equatable.dart';
import 'package:flutter_news_example_api/api.dart';
import 'package:json_annotation/json_annotation.dart';
part 'subscriptions_response.g.dart';
/// {@template subscriptions_response}
/// A subscriptions response object which
/// contains a list of all available subscriptions.
/// {@endtemplate}
@JsonSerializable(explicitToJson: true)
class SubscriptionsResponse extends Equatable {
/// {@macro subscriptions_response}
const SubscriptionsResponse({required this.subscriptions});
/// Converts a `Map<String, dynamic>` into a
/// [SubscriptionsResponse] instance.
factory SubscriptionsResponse.fromJson(Map<String, dynamic> json) =>
_$SubscriptionsResponseFromJson(json);
/// The list of subscriptions.
final List<Subscription> subscriptions;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$SubscriptionsResponseToJson(this);
@override
List<Object> get props => [subscriptions];
}
| news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/models/subscriptions_response/subscriptions_response.dart",
"repo_id": "news_toolkit",
"token_count": 299
} | 895 |
// 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 'divider_horizontal_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
DividerHorizontalBlock _$DividerHorizontalBlockFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'DividerHorizontalBlock',
json,
($checkedConvert) {
final val = DividerHorizontalBlock(
type: $checkedConvert(
'type', (v) => v as String? ?? DividerHorizontalBlock.identifier),
);
return val;
},
);
Map<String, dynamic> _$DividerHorizontalBlockToJson(
DividerHorizontalBlock instance) =>
<String, dynamic>{
'type': instance.type,
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/divider_horizontal_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/divider_horizontal_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 347
} | 896 |
// 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 'post_large_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
PostLargeBlock _$PostLargeBlockFromJson(Map<String, dynamic> json) =>
$checkedCreate(
'PostLargeBlock',
json,
($checkedConvert) {
final val = PostLargeBlock(
id: $checkedConvert('id', (v) => v as String),
category: $checkedConvert(
'category', (v) => $enumDecode(_$PostCategoryEnumMap, v)),
author: $checkedConvert('author', (v) => v as String),
publishedAt: $checkedConvert(
'published_at', (v) => DateTime.parse(v as String)),
imageUrl: $checkedConvert('image_url', (v) => v as String),
title: $checkedConvert('title', (v) => v as String),
description: $checkedConvert('description', (v) => v as String?),
action: $checkedConvert('action',
(v) => const BlockActionConverter().fromJson(v as Map?)),
type: $checkedConvert(
'type', (v) => v as String? ?? PostLargeBlock.identifier),
isPremium: $checkedConvert('is_premium', (v) => v as bool? ?? false),
isContentOverlaid: $checkedConvert(
'is_content_overlaid', (v) => v as bool? ?? false),
);
return val;
},
fieldKeyMap: const {
'publishedAt': 'published_at',
'imageUrl': 'image_url',
'isPremium': 'is_premium',
'isContentOverlaid': 'is_content_overlaid'
},
);
Map<String, dynamic> _$PostLargeBlockToJson(PostLargeBlock instance) {
final val = <String, dynamic>{
'id': instance.id,
'category': _$PostCategoryEnumMap[instance.category],
'author': instance.author,
'published_at': instance.publishedAt.toIso8601String(),
};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('image_url', instance.imageUrl);
val['title'] = instance.title;
writeNotNull('description', instance.description);
writeNotNull('action', const BlockActionConverter().toJson(instance.action));
val['is_premium'] = instance.isPremium;
val['is_content_overlaid'] = instance.isContentOverlaid;
val['type'] = instance.type;
return val;
}
const _$PostCategoryEnumMap = {
PostCategory.business: 'business',
PostCategory.entertainment: 'entertainment',
PostCategory.health: 'health',
PostCategory.science: 'science',
PostCategory.sports: 'sports',
PostCategory.technology: 'technology',
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_large_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_large_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 1079
} | 897 |
// 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_caption_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
TextCaptionBlock _$TextCaptionBlockFromJson(Map<String, dynamic> json) =>
$checkedCreate(
'TextCaptionBlock',
json,
($checkedConvert) {
final val = TextCaptionBlock(
text: $checkedConvert('text', (v) => v as String),
color: $checkedConvert(
'color', (v) => $enumDecode(_$TextCaptionColorEnumMap, v)),
type: $checkedConvert(
'type', (v) => v as String? ?? TextCaptionBlock.identifier),
);
return val;
},
);
Map<String, dynamic> _$TextCaptionBlockToJson(TextCaptionBlock instance) =>
<String, dynamic>{
'color': _$TextCaptionColorEnumMap[instance.color],
'text': instance.text,
'type': instance.type,
};
const _$TextCaptionColorEnumMap = {
TextCaptionColor.normal: 'normal',
TextCaptionColor.light: 'light',
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_caption_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/text_caption_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 480
} | 898 |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('ArticleIntroductionBlock', () {
test('can be (de)serialized', () {
final block = ArticleIntroductionBlock(
category: PostCategory.technology,
author: 'author',
publishedAt: DateTime(2022, 3, 9),
imageUrl: 'imageUrl',
title: 'title',
);
expect(ArticleIntroductionBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/article_introduction_block_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/article_introduction_block_test.dart",
"repo_id": "news_toolkit",
"token_count": 194
} | 899 |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('PostSmallBlock', () {
test('can be (de)serialized', () {
final block = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
);
expect(PostSmallBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_small_block_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_small_block_test.dart",
"repo_id": "news_toolkit",
"token_count": 208
} | 900 |
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
Handler middleware(Handler handler) {
return handler
.use(requestLogger())
.use(userProvider())
.use(newsDataSourceProvider());
}
| news_toolkit/flutter_news_example/api/routes/_middleware.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/routes/_middleware.dart",
"repo_id": "news_toolkit",
"token_count": 93
} | 901 |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../routes/index.dart' as route;
class _MockRequestContext extends Mock implements RequestContext {}
void main() {
group('GET /', () {
test('responds with a 204.', () {
final context = _MockRequestContext();
final response = route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.noContent));
});
});
}
| news_toolkit/flutter_news_example/api/test/routes/index_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/test/routes/index_test.dart",
"repo_id": "news_toolkit",
"token_count": 179
} | 902 |
{
"images": [
{
"size": "60x60",
"expected-size": "180",
"filename": "180.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "3x"
},
{
"size": "40x40",
"expected-size": "80",
"filename": "80.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "2x"
},
{
"size": "40x40",
"expected-size": "120",
"filename": "120.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "3x"
},
{
"size": "60x60",
"expected-size": "120",
"filename": "120.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "2x"
},
{
"size": "57x57",
"expected-size": "57",
"filename": "57.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "1x"
},
{
"size": "29x29",
"expected-size": "58",
"filename": "58.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "2x"
},
{
"size": "29x29",
"expected-size": "29",
"filename": "29.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "1x"
},
{
"size": "29x29",
"expected-size": "87",
"filename": "87.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "3x"
},
{
"size": "57x57",
"expected-size": "114",
"filename": "114.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "2x"
},
{
"size": "20x20",
"expected-size": "40",
"filename": "40.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "2x"
},
{
"size": "20x20",
"expected-size": "60",
"filename": "60.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "iphone",
"scale": "3x"
},
{
"size": "1024x1024",
"filename": "1024.png",
"expected-size": "1024",
"idiom": "ios-marketing",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"scale": "1x"
},
{
"size": "40x40",
"expected-size": "80",
"filename": "80.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "72x72",
"expected-size": "72",
"filename": "72.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "76x76",
"expected-size": "152",
"filename": "152.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "50x50",
"expected-size": "100",
"filename": "100.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "29x29",
"expected-size": "58",
"filename": "58.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "76x76",
"expected-size": "76",
"filename": "76.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "29x29",
"expected-size": "29",
"filename": "29.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "50x50",
"expected-size": "50",
"filename": "50.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "72x72",
"expected-size": "144",
"filename": "144.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "40x40",
"expected-size": "40",
"filename": "40.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "83.5x83.5",
"expected-size": "167",
"filename": "167.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
},
{
"size": "20x20",
"expected-size": "20",
"filename": "20.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "1x"
},
{
"size": "20x20",
"expected-size": "40",
"filename": "40.png",
"folder": "Assets.xcassets/AppIcon.appiconset/",
"idiom": "ipad",
"scale": "2x"
}
]
} | news_toolkit/flutter_news_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0 | {
"file_path": "news_toolkit/flutter_news_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json",
"repo_id": "news_toolkit",
"token_count": 2593
} | 903 |
part of 'full_screen_ads_bloc.dart';
abstract class FullScreenAdsEvent extends Equatable {
const FullScreenAdsEvent();
@override
List<Object> get props => [];
}
class LoadInterstitialAdRequested extends FullScreenAdsEvent {
const LoadInterstitialAdRequested({this.retry = 0});
final int retry;
@override
List<Object> get props => [retry];
}
class LoadRewardedAdRequested extends FullScreenAdsEvent {
const LoadRewardedAdRequested({this.retry = 0});
final int retry;
@override
List<Object> get props => [retry];
}
class ShowInterstitialAdRequested extends FullScreenAdsEvent {
const ShowInterstitialAdRequested();
}
class ShowRewardedAdRequested extends FullScreenAdsEvent {
const ShowRewardedAdRequested();
}
class EarnedReward extends FullScreenAdsEvent {
const EarnedReward(this.reward);
final ads.RewardItem reward;
@override
List<Object> get props => [reward];
}
| news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/ads/bloc/full_screen_ads_event.dart",
"repo_id": "news_toolkit",
"token_count": 282
} | 904 |
export 'bloc/article_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| news_toolkit/flutter_news_example/lib/article/article.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/article/article.dart",
"repo_id": "news_toolkit",
"token_count": 36
} | 905 |
part of 'categories_bloc.dart';
abstract class CategoriesEvent extends Equatable {
const CategoriesEvent();
}
class CategoriesRequested extends CategoriesEvent {
const CategoriesRequested();
@override
List<Object> get props => [];
}
class CategorySelected extends CategoriesEvent {
const CategorySelected({required this.category});
final Category category;
@override
List<Object> get props => [category];
}
| news_toolkit/flutter_news_example/lib/categories/bloc/categories_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/categories/bloc/categories_event.dart",
"repo_id": "news_toolkit",
"token_count": 113
} | 906 |
import 'package:bloc/bloc.dart';
part 'home_state.dart';
class HomeCubit extends Cubit<HomeState> {
HomeCubit() : super(HomeState.topStories);
void setTab(int selectedTab) {
switch (selectedTab) {
case 0:
return emit(HomeState.topStories);
case 1:
return emit(HomeState.search);
case 2:
return emit(HomeState.subscribe);
}
}
}
| news_toolkit/flutter_news_example/lib/home/cubit/home_cubit.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/home/cubit/home_cubit.dart",
"repo_id": "news_toolkit",
"token_count": 164
} | 907 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:user_repository/user_repository.dart';
class LoginWithEmailPage extends StatelessWidget {
const LoginWithEmailPage({super.key});
static Route<void> route() =>
MaterialPageRoute<void>(builder: (_) => const LoginWithEmailPage());
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => LoginBloc(
userRepository: context.read<UserRepository>(),
),
child: Scaffold(
appBar: AppBar(
leading: const AppBackButton(),
actions: [
IconButton(
key: const Key('loginWithEmailPage_closeIcon'),
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
)
],
),
body: const LoginWithEmailForm(),
),
);
}
}
| news_toolkit/flutter_news_example/lib/login/view/login_with_email_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/login/view/login_with_email_page.dart",
"repo_id": "news_toolkit",
"token_count": 428
} | 908 |
import 'package:app_ui/app_ui.dart' show AppColors, AppLogo, AppSpacing;
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/navigation/navigation.dart';
class NavDrawer extends StatelessWidget {
const NavDrawer({super.key});
static const _contentPadding = AppSpacing.lg;
@override
Widget build(BuildContext context) {
final isUserSubscribed =
context.select((AppBloc bloc) => bloc.state.isUserSubscribed);
return ClipRRect(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(AppSpacing.lg),
bottomRight: Radius.circular(AppSpacing.lg),
),
child: Drawer(
backgroundColor: AppColors.darkBackground,
child: ListView(
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.only(
top: kToolbarHeight,
left: AppSpacing.lg,
right: AppSpacing.lg,
bottom: AppSpacing.xlg,
),
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: _contentPadding + AppSpacing.xxs,
horizontal: _contentPadding,
),
child: Align(
alignment: Alignment.centerLeft,
child: AppLogo.light(),
),
),
const _NavDrawerDivider(),
const NavDrawerSections(),
if (!isUserSubscribed) ...[
const _NavDrawerDivider(),
const NavDrawerSubscribe(),
],
],
),
),
);
}
}
class _NavDrawerDivider extends StatelessWidget {
const _NavDrawerDivider();
@override
Widget build(BuildContext context) {
return const Divider(color: AppColors.outlineOnDark);
}
}
| news_toolkit/flutter_news_example/lib/navigation/view/nav_drawer.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/navigation/view/nav_drawer.dart",
"repo_id": "news_toolkit",
"token_count": 880
} | 909 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/notification_preferences/notification_preferences.dart';
import 'package:news_repository/news_repository.dart';
import 'package:notifications_repository/notifications_repository.dart';
class NotificationPreferencesPage extends StatelessWidget {
const NotificationPreferencesPage({super.key});
static MaterialPageRoute<void> route() {
return MaterialPageRoute(
builder: (_) => const NotificationPreferencesPage(),
);
}
@override
Widget build(BuildContext context) {
return BlocProvider<NotificationPreferencesBloc>(
create: (_) => NotificationPreferencesBloc(
newsRepository: context.read<NewsRepository>(),
notificationsRepository: context.read<NotificationsRepository>(),
)..add(InitialCategoriesPreferencesRequested()),
child: const NotificationPreferencesView(),
);
}
}
@visibleForTesting
class NotificationPreferencesView extends StatelessWidget {
const NotificationPreferencesView({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
leading: const AppBackButton(),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: AppSpacing.lg),
Text(
l10n.notificationPreferencesTitle,
style: theme.textTheme.headlineMedium,
),
const SizedBox(height: AppSpacing.lg),
Text(
l10n.notificationPreferencesCategoriesSubtitle,
style: theme.textTheme.bodyLarge?.copyWith(
color: AppColors.mediumEmphasisSurface,
),
),
const SizedBox(height: AppSpacing.lg),
BlocBuilder<NotificationPreferencesBloc,
NotificationPreferencesState>(
builder: (context, state) => Expanded(
child: ListView(
children: state.categories
.map<Widget>(
(category) => NotificationCategoryTile(
title: category.name,
trailing: AppSwitch(
onText: l10n.checkboxOnTitle,
offText: l10n.userProfileCheckboxOffTitle,
value:
state.selectedCategories.contains(category),
onChanged: (value) => context
.read<NotificationPreferencesBloc>()
.add(
CategoriesPreferenceToggled(
category: category,
),
),
),
),
)
.toList(),
),
),
),
],
),
),
),
);
}
}
| news_toolkit/flutter_news_example/lib/notification_preferences/view/notification_preferences_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/view/notification_preferences_page.dart",
"repo_id": "news_toolkit",
"token_count": 1783
} | 910 |
export 'bloc/search_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| news_toolkit/flutter_news_example/lib/search/search.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/search/search.dart",
"repo_id": "news_toolkit",
"token_count": 36
} | 911 |
import 'dart:async';
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/l10n/l10n.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:user_repository/user_repository.dart';
Future<void> showPurchaseSubscriptionDialog({
required BuildContext context,
}) async =>
showGeneralDialog(
context: context,
pageBuilder: (_, __, ___) => const PurchaseSubscriptionDialog(),
transitionBuilder: (context, anim1, anim2, child) {
return SlideTransition(
position:
Tween(begin: const Offset(0, 1), end: Offset.zero).animate(anim1),
child: child,
);
},
);
class PurchaseSubscriptionDialog extends StatelessWidget {
const PurchaseSubscriptionDialog({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<SubscriptionsBloc>(
create: (context) => SubscriptionsBloc(
inAppPurchaseRepository: context.read<InAppPurchaseRepository>(),
userRepository: context.read<UserRepository>(),
)..add(SubscriptionsRequested()),
child: const PurchaseSubscriptionDialogView(),
);
}
}
class PurchaseSubscriptionDialogView extends StatelessWidget {
const PurchaseSubscriptionDialogView({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Stack(
children: [
Scaffold(
body: Dialog(
insetPadding: EdgeInsets.zero,
backgroundColor: AppColors.modalBackground,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
l10n.subscriptionPurchaseTitle,
style: theme.textTheme.displaySmall,
),
IconButton(
key: const Key(
'purchaseSubscriptionDialog_closeIconButton',
),
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
),
Text(
l10n.subscriptionPurchaseSubtitle,
style: theme.textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.xlg),
Expanded(
child:
BlocConsumer<SubscriptionsBloc, SubscriptionsState>(
listener: (context, state) {
if (state.purchaseStatus ==
PurchaseStatus.completed) {
context.read<AnalyticsBloc>().add(
TrackAnalyticsEvent(
UserSubscriptionConversionEvent(),
),
);
showDialog<void>(
context: context,
builder: (context) =>
const PurchaseCompletedDialog(),
).then((_) => Navigator.maybePop(context));
}
},
builder: (context, state) {
if (state.subscriptions.isEmpty) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return CustomScrollView(
slivers: <SliverList>[
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => SubscriptionCard(
key: ValueKey(state.subscriptions[index]),
subscription: state.subscriptions[index],
isExpanded: index == 0,
),
childCount: state.subscriptions.length,
),
),
],
);
}
},
),
),
],
),
),
),
),
),
],
);
}
}
@visibleForTesting
class PurchaseCompletedDialog extends StatefulWidget {
const PurchaseCompletedDialog({super.key});
@override
State<PurchaseCompletedDialog> createState() =>
_PurchaseCompletedDialogState();
}
class _PurchaseCompletedDialogState extends State<PurchaseCompletedDialog> {
late Timer _timer;
static const _closeDialogAfterDuration = Duration(seconds: 3);
@override
void initState() {
super.initState();
_timer = Timer(
_closeDialogAfterDuration,
() => Navigator.maybePop(context),
);
}
@override
Widget build(BuildContext context) {
return Center(
child: Card(
child: Container(
padding: const EdgeInsets.symmetric(
vertical: AppSpacing.lg,
horizontal: AppSpacing.xxlg,
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: AppSpacing.md),
const Icon(
Icons.check_circle_outline,
size: AppSpacing.xxlg + AppSpacing.xxlg,
color: AppColors.mediumEmphasisSurface,
),
const SizedBox(height: AppSpacing.xlg),
Text(
context.l10n.subscriptionPurchaseCompleted,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.md),
],
),
),
),
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
}
| news_toolkit/flutter_news_example/lib/subscriptions/dialog/view/purchase_subscription_dialog.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/subscriptions/dialog/view/purchase_subscription_dialog.dart",
"repo_id": "news_toolkit",
"token_count": 3712
} | 912 |
part of 'theme_mode_bloc.dart';
abstract class ThemeModeEvent extends Equatable {
const ThemeModeEvent();
}
/// The app's [ThemeMode] has been changed
class ThemeModeChanged extends ThemeModeEvent {
const ThemeModeChanged(this.themeMode);
final ThemeMode? themeMode;
@override
List<Object?> get props => [themeMode];
}
| news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/theme_selector/bloc/theme_mode_event.dart",
"repo_id": "news_toolkit",
"token_count": 100
} | 913 |
import 'dart:async';
import 'package:google_mobile_ads/google_mobile_ads.dart';
/// {@template ads_consent_failure}
/// A base failure for the ads consent client failures.
/// {@endtemplate}
abstract class AdsContentFailure implements Exception {
/// {@macro ads_consent_failure}
const AdsContentFailure(this.error);
/// The error which was caught.
final Object error;
}
/// {@template request_ads_consent_failure}
/// Thrown when requesting ads consent fails.
/// {@endtemplate}
class RequestConsentFailure extends AdsContentFailure {
/// {@macro request_ads_consent_failure}
const RequestConsentFailure(super.error);
}
/// Signature for the content form provider.
typedef ConsentFormProvider = void Function(
OnConsentFormLoadSuccessListener successListener,
OnConsentFormLoadFailureListener failureListener,
);
/// {@template ads_consent_client}
/// A client that handles requesting ads consent on a device.
/// {@endtemplate}
class AdsConsentClient {
/// {@macro ads_consent_client}
AdsConsentClient({
ConsentInformation? adsConsentInformation,
ConsentFormProvider? adsConsentFormProvider,
}) : _adsConsentInformation =
adsConsentInformation ?? ConsentInformation.instance,
_adsConsentFormProvider =
adsConsentFormProvider ?? ConsentForm.loadConsentForm;
final ConsentInformation _adsConsentInformation;
final ConsentFormProvider _adsConsentFormProvider;
/// Requests the ads consent by presenting the consent form
/// if user consent is required but not yet obtained.
///
/// Returns true if the consent was determined.
///
/// Throws a [RequestConsentFailure] if an exception occurs.
Future<bool> requestConsent() {
final adsConsentDeterminedCompleter = Completer<bool>();
_adsConsentInformation.requestConsentInfoUpdate(
ConsentRequestParameters(),
() async {
try {
if (await _adsConsentInformation.isConsentFormAvailable()) {
adsConsentDeterminedCompleter.complete(await _loadConsentForm());
} else {
final status = await _adsConsentInformation.getConsentStatus();
adsConsentDeterminedCompleter.complete(status.isDetermined);
}
} on FormError catch (error, stackTrace) {
_onRequestConsentError(
error,
completer: adsConsentDeterminedCompleter,
stackTrace: stackTrace,
);
}
},
(error) => _onRequestConsentError(
error,
completer: adsConsentDeterminedCompleter,
),
);
return adsConsentDeterminedCompleter.future;
}
Future<bool> _loadConsentForm() async {
final completer = Completer<bool>();
_adsConsentFormProvider(
(consentForm) async {
final status = await _adsConsentInformation.getConsentStatus();
if (status.isRequired) {
consentForm.show(
(error) async {
if (error != null) {
completer.completeError(error, StackTrace.current);
} else {
final updatedStatus =
await _adsConsentInformation.getConsentStatus();
completer.complete(updatedStatus.isDetermined);
}
},
);
} else {
completer.complete(status.isDetermined);
}
},
(error) => completer.completeError(error, StackTrace.current),
);
return completer.future;
}
void _onRequestConsentError(
FormError error, {
required Completer<bool> completer,
StackTrace? stackTrace,
}) =>
completer.completeError(
RequestConsentFailure(error),
stackTrace ?? StackTrace.current,
);
}
extension on ConsentStatus {
/// Whether the user has consented to the use of personalized ads
/// or the consent is not required, e.g. the user is not in the EEA or UK.
bool get isDetermined =>
this == ConsentStatus.obtained || this == ConsentStatus.notRequired;
/// Whether the consent to the user of personalized ads is required.
bool get isRequired => this == ConsentStatus.required;
}
| news_toolkit/flutter_news_example/packages/ads_consent_client/lib/src/ads_consent_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/ads_consent_client/lib/src/ads_consent_client.dart",
"repo_id": "news_toolkit",
"token_count": 1512
} | 914 |
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 7L9.6 8.4L12.2 11H2V13H12.2L9.6 15.6L11 17L16 12L11 7ZM20 19H12V21H20C21.1 21 22 20.1 22 19V5C22 3.9 21.1 3 20 3H12V5H20V19Z" fill="#1A1A1A"/>
</svg>
| news_toolkit/flutter_news_example/packages/app_ui/assets/icons/log_in_icon.svg/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/assets/icons/log_in_icon.svg",
"repo_id": "news_toolkit",
"token_count": 143
} | 915 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
linter:
rules:
public_member_api_docs: false
| news_toolkit/flutter_news_example/packages/app_ui/gallery/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 44
} | 916 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
class SpacingPage extends StatelessWidget {
const SpacingPage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => const SpacingPage());
}
@override
Widget build(BuildContext context) {
const spacingList = [
_SpacingItem(spacing: AppSpacing.xxxs, name: 'xxxs'),
_SpacingItem(spacing: AppSpacing.xxs, name: 'xxs'),
_SpacingItem(spacing: AppSpacing.xs, name: 'xs'),
_SpacingItem(spacing: AppSpacing.sm, name: 'sm'),
_SpacingItem(spacing: AppSpacing.md, name: 'md'),
_SpacingItem(spacing: AppSpacing.lg, name: 'lg'),
_SpacingItem(spacing: AppSpacing.xlg, name: 'xlg'),
_SpacingItem(spacing: AppSpacing.xxlg, name: 'xxlg'),
_SpacingItem(spacing: AppSpacing.xxxlg, name: 'xxxlg'),
];
return Scaffold(
appBar: AppBar(title: const Text('Spacing')),
body: ListView.builder(
itemCount: spacingList.length,
itemBuilder: (_, index) => spacingList[index],
),
);
}
}
class _SpacingItem extends StatelessWidget {
const _SpacingItem({required this.spacing, required this.name});
final double spacing;
final String name;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(AppSpacing.sm),
child: Row(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
color: AppColors.black,
width: AppSpacing.xxs,
height: AppSpacing.lg,
),
Container(
width: spacing,
height: AppSpacing.lg,
color: AppColors.green,
),
Container(
color: AppColors.black,
width: AppSpacing.xxs,
height: AppSpacing.lg,
),
],
),
const SizedBox(width: AppSpacing.sm),
Text(name),
],
),
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing_page.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/spacing/spacing_page.dart",
"repo_id": "news_toolkit",
"token_count": 1018
} | 917 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
/// {@template app_back_button}
/// IconButton displayed in the application.
/// Navigates back when is pressed.
/// {@endtemplate}
class AppBackButton extends StatelessWidget {
/// Creates a default instance of [AppBackButton].
const AppBackButton({
Key? key,
VoidCallback? onPressed,
}) : this._(
key: key,
isLight: false,
onPressed: onPressed,
);
/// Creates a light instance of [AppBackButton].
const AppBackButton.light({
Key? key,
VoidCallback? onPressed,
}) : this._(
key: key,
isLight: true,
onPressed: onPressed,
);
/// {@macro app_back_button}
const AppBackButton._({required this.isLight, this.onPressed, super.key});
/// Whether this app button is light.
final bool isLight;
/// Called when the back button has been tapped.
/// Defaults to `Navigator.of(context).pop()`
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: onPressed ?? () => Navigator.of(context).pop(),
icon: Assets.icons.backIcon.svg(
colorFilter: ColorFilter.mode(
isLight ? AppColors.white : AppColors.highEmphasisSurface,
BlendMode.srcIn,
),
),
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_back_button.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/widgets/app_back_button.dart",
"repo_id": "news_toolkit",
"token_count": 533
} | 918 |
// ignore_for_file: prefer_const_constructors
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../helpers/helpers.dart';
void main() {
group('AppEmailTextField', () {
const hintText = 'Hint';
group('email', () {
testWidgets('has keyboardType set to emailAddress', (tester) async {
await tester.pumpApp(
AppEmailTextField(),
);
final field = tester.widget<AppTextField>(find.byType(AppTextField));
expect(field.keyboardType, TextInputType.emailAddress);
});
testWidgets('has autocorrect set to false', (tester) async {
await tester.pumpApp(
AppEmailTextField(),
);
final field = tester.widget<AppTextField>(find.byType(AppTextField));
expect(field.autocorrect, false);
});
});
group('renders', () {
testWidgets('hint text', (tester) async {
await tester.pumpApp(
AppEmailTextField(
hintText: hintText,
),
);
expect(find.text(hintText), findsOneWidget);
});
});
});
}
| news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_email_text_field_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/widgets/app_email_text_field_test.dart",
"repo_id": "news_toolkit",
"token_count": 503
} | 919 |
// ignore_for_file: must_be_immutable
import 'dart:async';
import 'package:authentication_client/authentication_client.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:firebase_auth_platform_interface/src/method_channel/method_channel_firebase_auth.dart';
import 'package:firebase_authentication_client/firebase_authentication_client.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'
as facebook_auth;
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:mocktail/mocktail.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:token_storage/token_storage.dart';
import 'package:twitter_login/entity/auth_result.dart' as twitter_auth;
import 'package:twitter_login/twitter_login.dart' as twitter_auth;
class MockFirebaseAuth extends Mock implements firebase_auth.FirebaseAuth {}
class MockFirebaseUser extends Mock implements firebase_auth.User {}
class MockUserMetadata extends Mock implements firebase_auth.UserMetadata {}
class MockGoogleSignIn extends Mock implements GoogleSignIn {}
@immutable
class MockGoogleSignInAccount extends Mock implements GoogleSignInAccount {
@override
bool operator ==(dynamic other) => identical(this, other);
@override
int get hashCode => 0;
}
class MockGoogleSignInAuthentication extends Mock
implements GoogleSignInAuthentication {}
class MockAuthorizationCredentialAppleID extends Mock
implements AuthorizationCredentialAppleID {}
class MockFacebookAuth extends Mock implements facebook_auth.FacebookAuth {}
class MockFacebookLoginResult extends Mock
implements facebook_auth.LoginResult {}
class MockFacebookAccessToken extends Mock
implements facebook_auth.AccessToken {}
class MockFirebaseCore extends Mock
with MockPlatformInterfaceMixin
implements FirebasePlatform {}
class MockUserCredential extends Mock implements firebase_auth.UserCredential {}
class FakeAuthCredential extends Fake implements firebase_auth.AuthCredential {}
class FakeActionCodeSettings extends Fake
implements firebase_auth.ActionCodeSettings {}
class MockTwitterLogin extends Mock implements twitter_auth.TwitterLogin {}
class MockTwitterAuthResult extends Mock implements twitter_auth.AuthResult {}
class MockTokenStorage extends Mock implements TokenStorage {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const options = FirebaseOptions(
apiKey: 'apiKey',
appId: 'appId',
messagingSenderId: 'messagingSenderId',
projectId: 'projectId',
);
const email = '[email protected]';
const emailLink = 'https://email.page.link';
const appPackageName = 'app.package.name';
group('FirebaseAuthenticationClient', () {
late TokenStorage tokenStorage;
late firebase_auth.FirebaseAuth firebaseAuth;
late GoogleSignIn googleSignIn;
late FirebaseAuthenticationClient firebaseAuthenticationClient;
late AuthorizationCredentialAppleID authorizationCredentialAppleID;
late GetAppleCredentials getAppleCredentials;
late List<List<AppleIDAuthorizationScopes>> getAppleCredentialsCalls;
late facebook_auth.FacebookAuth facebookAuth;
late twitter_auth.TwitterLogin twitterLogin;
late StreamController<firebase_auth.User?> authStateChangesController;
setUpAll(() {
registerFallbackValue(FakeAuthCredential());
registerFallbackValue(FakeActionCodeSettings());
});
setUp(() {
final platformApp = FirebaseAppPlatform(defaultFirebaseAppName, options);
final firebaseCore = MockFirebaseCore();
when(() => firebaseCore.apps).thenReturn([platformApp]);
when(firebaseCore.app).thenReturn(platformApp);
when(
() => firebaseCore.initializeApp(
name: defaultFirebaseAppName,
options: options,
),
).thenAnswer((_) async => platformApp);
Firebase.delegatePackingProperty = firebaseCore;
tokenStorage = MockTokenStorage();
firebaseAuth = MockFirebaseAuth();
googleSignIn = MockGoogleSignIn();
authorizationCredentialAppleID = MockAuthorizationCredentialAppleID();
getAppleCredentialsCalls = <List<AppleIDAuthorizationScopes>>[];
getAppleCredentials = ({
List<AppleIDAuthorizationScopes> scopes = const [],
WebAuthenticationOptions? webAuthenticationOptions,
String? nonce,
String? state,
}) async {
getAppleCredentialsCalls.add(scopes);
return authorizationCredentialAppleID;
};
facebookAuth = MockFacebookAuth();
twitterLogin = MockTwitterLogin();
authStateChangesController =
StreamController<firebase_auth.User?>.broadcast();
when(firebaseAuth.authStateChanges)
.thenAnswer((_) => authStateChangesController.stream);
when(() => tokenStorage.saveToken(any())).thenAnswer((_) async {});
when(tokenStorage.clearToken).thenAnswer((_) async {});
firebaseAuthenticationClient = FirebaseAuthenticationClient(
tokenStorage: tokenStorage,
firebaseAuth: firebaseAuth,
googleSignIn: googleSignIn,
getAppleCredentials: getAppleCredentials,
facebookAuth: facebookAuth,
twitterLogin: twitterLogin,
);
});
testWidgets(
'creates FirebaseAuth instance internally when not injected',
(tester) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
MethodChannelFirebaseAuth.channel,
(call) async {
if (call.method == 'Auth#registerIdTokenListener' ||
call.method == 'Auth#registerAuthStateListener') {
return 'mockAuthChannel';
}
return null;
},
);
expect(
() => FirebaseAuthenticationClient(tokenStorage: tokenStorage),
isNot(throwsException),
);
},
);
group('logInWithApple', () {
setUp(() {
when(() => firebaseAuth.signInWithCredential(any()))
.thenAnswer((_) => Future.value(MockUserCredential()));
when(() => authorizationCredentialAppleID.identityToken).thenReturn('');
when(() => authorizationCredentialAppleID.authorizationCode)
.thenReturn('');
});
test('calls getAppleCredentials with correct scopes', () async {
await firebaseAuthenticationClient.logInWithApple();
expect(getAppleCredentialsCalls, [
[
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
]
]);
});
test('calls signInWithCredential with correct credential', () async {
const identityToken = 'identity-token';
const accessToken = 'access-token';
when(() => authorizationCredentialAppleID.identityToken)
.thenReturn(identityToken);
when(() => authorizationCredentialAppleID.authorizationCode)
.thenReturn(accessToken);
await firebaseAuthenticationClient.logInWithApple();
verify(() => firebaseAuth.signInWithCredential(any())).called(1);
});
test('throws LogInWithAppleFailure when exception occurs', () async {
when(() => firebaseAuth.signInWithCredential(any()))
.thenThrow(Exception());
expect(
() => firebaseAuthenticationClient.logInWithApple(),
throwsA(isA<LogInWithAppleFailure>()),
);
});
});
group('logInWithGoogle', () {
const accessToken = 'access-token';
const idToken = 'id-token';
setUp(() {
final googleSignInAuthentication = MockGoogleSignInAuthentication();
final googleSignInAccount = MockGoogleSignInAccount();
when(() => googleSignInAuthentication.accessToken)
.thenReturn(accessToken);
when(() => googleSignInAuthentication.idToken).thenReturn(idToken);
when(() => googleSignInAccount.authentication)
.thenAnswer((_) async => googleSignInAuthentication);
when(() => googleSignIn.signIn())
.thenAnswer((_) async => googleSignInAccount);
when(() => firebaseAuth.signInWithCredential(any()))
.thenAnswer((_) => Future.value(MockUserCredential()));
});
test('calls signIn authentication, and signInWithCredential', () async {
await firebaseAuthenticationClient.logInWithGoogle();
verify(() => googleSignIn.signIn()).called(1);
verify(() => firebaseAuth.signInWithCredential(any())).called(1);
});
test('succeeds when signIn succeeds', () {
expect(firebaseAuthenticationClient.logInWithGoogle(), completes);
});
test('throws LogInWithGoogleFailure when exception occurs', () async {
when(() => firebaseAuth.signInWithCredential(any()))
.thenThrow(Exception());
expect(
firebaseAuthenticationClient.logInWithGoogle(),
throwsA(isA<LogInWithGoogleFailure>()),
);
});
test('throws LogInWithGoogleCanceled when signIn returns null', () async {
when(() => googleSignIn.signIn()).thenAnswer((_) async => null);
expect(
firebaseAuthenticationClient.logInWithGoogle(),
throwsA(isA<LogInWithGoogleCanceled>()),
);
});
});
group('logInWithFacebook', () {
late facebook_auth.LoginResult loginResult;
late facebook_auth.AccessToken accessTokenResult;
const accessToken = 'access-token';
setUp(() {
loginResult = MockFacebookLoginResult();
accessTokenResult = MockFacebookAccessToken();
when(() => accessTokenResult.token).thenReturn(accessToken);
when(() => loginResult.accessToken).thenReturn(accessTokenResult);
when(() => loginResult.status)
.thenReturn(facebook_auth.LoginStatus.success);
when(() => facebookAuth.login()).thenAnswer((_) async => loginResult);
when(() => firebaseAuth.signInWithCredential(any()))
.thenAnswer((_) => Future.value(MockUserCredential()));
});
test('calls login authentication and signInWithCredential', () async {
await firebaseAuthenticationClient.logInWithFacebook();
verify(() => facebookAuth.login()).called(1);
verify(() => firebaseAuth.signInWithCredential(any())).called(1);
});
test('succeeds when login succeeds', () {
expect(firebaseAuthenticationClient.logInWithFacebook(), completes);
});
test(
'throws LogInWithFacebookFailure '
'when signInWithCredential throws', () async {
when(() => firebaseAuth.signInWithCredential(any()))
.thenThrow(Exception());
expect(
firebaseAuthenticationClient.logInWithFacebook(),
throwsA(isA<LogInWithFacebookFailure>()),
);
});
test(
'throws LogInWithFacebookFailure '
'when login result status is failed', () async {
when(() => loginResult.status)
.thenReturn(facebook_auth.LoginStatus.failed);
expect(
firebaseAuthenticationClient.logInWithFacebook(),
throwsA(isA<LogInWithFacebookFailure>()),
);
});
test(
'throws LogInWithFacebookFailure '
'when login result access token is empty', () async {
when(() => loginResult.accessToken).thenReturn(null);
expect(
firebaseAuthenticationClient.logInWithFacebook(),
throwsA(isA<LogInWithFacebookFailure>()),
);
});
test(
'throws LogInWithFacebookCanceled '
'when login result status is cancelled', () async {
when(() => loginResult.status)
.thenReturn(facebook_auth.LoginStatus.cancelled);
expect(
firebaseAuthenticationClient.logInWithFacebook(),
throwsA(isA<LogInWithFacebookCanceled>()),
);
});
});
group('logInWithTwitter', () {
late twitter_auth.AuthResult loginResult;
const accessToken = 'access-token';
const secret = 'secret';
setUp(() {
loginResult = MockTwitterAuthResult();
when(() => loginResult.authToken).thenReturn(accessToken);
when(() => loginResult.authTokenSecret).thenReturn(secret);
when(() => loginResult.status)
.thenReturn(twitter_auth.TwitterLoginStatus.loggedIn);
when(() => twitterLogin.loginV2()).thenAnswer((_) async => loginResult);
when(() => firebaseAuth.signInWithCredential(any()))
.thenAnswer((_) => Future.value(MockUserCredential()));
});
test('calls loginV2 authentication and signInWithCredential', () async {
await firebaseAuthenticationClient.logInWithTwitter();
verify(() => twitterLogin.loginV2()).called(1);
verify(() => firebaseAuth.signInWithCredential(any())).called(1);
});
test('succeeds when login succeeds', () {
expect(firebaseAuthenticationClient.logInWithTwitter(), completes);
});
test(
'throws LogInWithTwitterFailure '
'when signInWithCredential throws', () async {
when(() => firebaseAuth.signInWithCredential(any()))
.thenThrow(Exception());
expect(
firebaseAuthenticationClient.logInWithTwitter(),
throwsA(isA<LogInWithTwitterFailure>()),
);
});
test(
'throws LogInWithTwitterFailure '
'when login result status is error', () async {
when(() => loginResult.status)
.thenReturn(twitter_auth.TwitterLoginStatus.error);
expect(
firebaseAuthenticationClient.logInWithTwitter(),
throwsA(isA<LogInWithTwitterFailure>()),
);
});
test(
'throws LogInWithTwitterFailure '
'when login result auth token is empty', () async {
when(() => loginResult.authToken).thenReturn(null);
expect(
firebaseAuthenticationClient.logInWithTwitter(),
throwsA(isA<LogInWithTwitterFailure>()),
);
});
test(
'throws LogInWithTwitterFailure '
'when login result auth token secret is empty', () async {
when(() => loginResult.authTokenSecret).thenReturn(null);
expect(
firebaseAuthenticationClient.logInWithTwitter(),
throwsA(isA<LogInWithTwitterFailure>()),
);
});
test(
'throws LogInWithTwitterCanceled '
'when login result status is cancelledByUser', () async {
when(() => loginResult.status)
.thenReturn(twitter_auth.TwitterLoginStatus.cancelledByUser);
expect(
firebaseAuthenticationClient.logInWithTwitter(),
throwsA(isA<LogInWithTwitterCanceled>()),
);
});
});
group('sendLoginEmailLink', () {
setUp(() {
when(
() => firebaseAuth.sendSignInLinkToEmail(
email: any(named: 'email'),
actionCodeSettings: any(named: 'actionCodeSettings'),
),
).thenAnswer((_) async {});
});
test('calls sendSignInLinkToEmail', () async {
await firebaseAuthenticationClient.sendLoginEmailLink(
email: email,
appPackageName: appPackageName,
);
verify(
() => firebaseAuth.sendSignInLinkToEmail(
email: email,
actionCodeSettings: any(
named: 'actionCodeSettings',
that: isA<firebase_auth.ActionCodeSettings>()
.having(
(settings) => settings.androidPackageName,
'androidPackageName',
equals(appPackageName),
)
.having(
(settings) => settings.iOSBundleId,
'iOSBundleId',
equals(appPackageName),
)
.having(
(settings) => settings.androidInstallApp,
'androidInstallApp',
isTrue,
)
.having(
(settings) => settings.handleCodeInApp,
'handleCodeInApp',
isTrue,
),
),
),
).called(1);
});
test('succeeds when sendSignInLinkToEmail succeeds', () async {
expect(
firebaseAuthenticationClient.sendLoginEmailLink(
email: email,
appPackageName: appPackageName,
),
completes,
);
});
test(
'throws SendLoginEmailLinkFailure '
'when sendSignInLinkToEmail throws', () async {
when(
() => firebaseAuth.sendSignInLinkToEmail(
email: any(named: 'email'),
actionCodeSettings: any(named: 'actionCodeSettings'),
),
).thenThrow(Exception());
expect(
firebaseAuthenticationClient.sendLoginEmailLink(
email: email,
appPackageName: appPackageName,
),
throwsA(isA<SendLoginEmailLinkFailure>()),
);
});
});
group('isLogInWithEmailLink', () {
setUp(() {
when(
() => firebaseAuth.isSignInWithEmailLink(any()),
).thenAnswer((_) => true);
});
test('calls isSignInWithEmailLink', () {
firebaseAuthenticationClient.isLogInWithEmailLink(
emailLink: emailLink,
);
verify(
() => firebaseAuth.isSignInWithEmailLink(emailLink),
).called(1);
});
test('succeeds when isSignInWithEmailLink succeeds', () async {
expect(
firebaseAuthenticationClient.isLogInWithEmailLink(
emailLink: emailLink,
),
isTrue,
);
});
test(
'throws IsLogInWithEmailLinkFailure '
'when isSignInWithEmailLink throws', () async {
when(
() => firebaseAuth.isSignInWithEmailLink(any()),
).thenThrow(Exception());
expect(
() => firebaseAuthenticationClient.isLogInWithEmailLink(
emailLink: emailLink,
),
throwsA(isA<IsLogInWithEmailLinkFailure>()),
);
});
});
group('logInWithEmailLink', () {
setUp(() {
when(
() => firebaseAuth.signInWithEmailLink(
email: any(named: 'email'),
emailLink: any(named: 'emailLink'),
),
).thenAnswer((_) => Future.value(MockUserCredential()));
});
test('calls signInWithEmailLink', () async {
await firebaseAuthenticationClient.logInWithEmailLink(
email: email,
emailLink: emailLink,
);
verify(
() => firebaseAuth.signInWithEmailLink(
email: email,
emailLink: emailLink,
),
).called(1);
});
test('succeeds when signInWithEmailLink succeeds', () async {
expect(
firebaseAuthenticationClient.logInWithEmailLink(
email: email,
emailLink: emailLink,
),
completes,
);
});
test(
'throws LogInWithEmailLinkFailure '
'when signInWithEmailLink throws', () async {
when(
() => firebaseAuth.signInWithEmailLink(
email: any(named: 'email'),
emailLink: any(named: 'emailLink'),
),
).thenThrow(Exception());
expect(
firebaseAuthenticationClient.logInWithEmailLink(
email: email,
emailLink: emailLink,
),
throwsA(isA<LogInWithEmailLinkFailure>()),
);
});
});
group('logOut', () {
test('calls signOut', () async {
when(() => firebaseAuth.signOut()).thenAnswer((_) async {});
when(() => googleSignIn.signOut()).thenAnswer((_) async => null);
await firebaseAuthenticationClient.logOut();
verify(() => firebaseAuth.signOut()).called(1);
verify(() => googleSignIn.signOut()).called(1);
});
test('throws LogOutFailure when signOut throws', () async {
when(() => firebaseAuth.signOut()).thenThrow(Exception());
expect(
firebaseAuthenticationClient.logOut(),
throwsA(isA<LogOutFailure>()),
);
});
});
group('user', () {
const userId = 'mock-uid';
const email = 'mock-email';
const newUser = AuthenticationUser(id: userId, email: email);
const returningUser =
AuthenticationUser(id: userId, email: email, isNewUser: false);
test('emits anonymous user when firebase user is null', () async {
when(firebaseAuth.authStateChanges)
.thenAnswer((_) => Stream.value(null));
await expectLater(
firebaseAuthenticationClient.user,
emitsInOrder(
const <AuthenticationUser>[AuthenticationUser.anonymous],
),
);
});
test('emits new user when firebase user is not null', () async {
final firebaseUser = MockFirebaseUser();
final userMetadata = MockUserMetadata();
final creationTime = DateTime(2020);
when(() => firebaseUser.uid).thenReturn(userId);
when(() => firebaseUser.email).thenReturn(email);
when(() => userMetadata.creationTime).thenReturn(creationTime);
when(() => userMetadata.lastSignInTime).thenReturn(creationTime);
when(() => firebaseUser.photoURL).thenReturn(null);
when(() => firebaseUser.metadata).thenReturn(userMetadata);
when(firebaseAuth.authStateChanges)
.thenAnswer((_) => Stream.value(firebaseUser));
await expectLater(
firebaseAuthenticationClient.user,
emitsInOrder(const <AuthenticationUser>[newUser]),
);
});
test('emits returningUser user when firebase user is not null', () async {
final firebaseUser = MockFirebaseUser();
final userMetadata = MockUserMetadata();
final creationTime = DateTime(2020);
final lastSignInTime = DateTime(2019);
when(() => firebaseUser.uid).thenReturn(userId);
when(() => firebaseUser.email).thenReturn(email);
when(() => userMetadata.creationTime).thenReturn(creationTime);
when(() => userMetadata.lastSignInTime).thenReturn(lastSignInTime);
when(() => firebaseUser.photoURL).thenReturn(null);
when(() => firebaseUser.metadata).thenReturn(userMetadata);
when(firebaseAuth.authStateChanges)
.thenAnswer((_) => Stream.value(firebaseUser));
await expectLater(
firebaseAuthenticationClient.user,
emitsInOrder(const <AuthenticationUser>[returningUser]),
);
});
test(
'calls saveToken on TokenStorage '
'when user changes to authenticated', () async {
final firebaseUser = MockFirebaseUser();
final userMetadata = MockUserMetadata();
final creationTime = DateTime(2020);
final lastSignInTime = DateTime(2019);
when(() => firebaseUser.uid).thenReturn(userId);
when(() => firebaseUser.email).thenReturn(email);
when(() => userMetadata.creationTime).thenReturn(creationTime);
when(() => userMetadata.lastSignInTime).thenReturn(lastSignInTime);
when(() => firebaseUser.photoURL).thenReturn(null);
when(() => firebaseUser.metadata).thenReturn(userMetadata);
authStateChangesController.add(firebaseUser);
await Future.microtask(() {});
verify(() => tokenStorage.saveToken(userId)).called(1);
verifyNever(tokenStorage.clearToken);
});
test(
'calls clearToken on TokenStorage '
'when user changes to unauthenticated', () async {
authStateChangesController.add(null);
await Future.microtask(() {});
verify(tokenStorage.clearToken).called(1);
verifyNever(() => tokenStorage.saveToken(any()));
});
});
});
}
| news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/test/firebase_authentication_client_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/test/firebase_authentication_client_test.dart",
"repo_id": "news_toolkit",
"token_count": 10007
} | 920 |
export 'src/email_launcher.dart';
| news_toolkit/flutter_news_example/packages/email_launcher/lib/email_launcher.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/email_launcher/lib/email_launcher.dart",
"repo_id": "news_toolkit",
"token_count": 13
} | 921 |
export 'package:flutter_news_example_api/client.dart'
show Subscription, SubscriptionCost, SubscriptionPlan;
export 'src/in_app_purchase_repository.dart';
| news_toolkit/flutter_news_example/packages/in_app_purchase_repository/lib/in_app_purchase_repository.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/in_app_purchase_repository/lib/in_app_purchase_repository.dart",
"repo_id": "news_toolkit",
"token_count": 54
} | 922 |
import 'package:flutter/material.dart';
import 'package:news_blocks/news_blocks.dart';
/// {@template divider_horizontal}
/// A reusable divider horizontal block widget.
/// {@endtemplate}
class DividerHorizontal extends StatelessWidget {
/// {@macro divider_horizontal}
const DividerHorizontal({required this.block, super.key});
/// The associated [DividerHorizontalBlock] instance.
final DividerHorizontalBlock block;
@override
Widget build(BuildContext context) => const Divider();
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/divider_horizontal.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/divider_horizontal.dart",
"repo_id": "news_toolkit",
"token_count": 145
} | 923 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template post_medium_overlaid_layout}
/// A reusable post medium widget that overlays the post content on the image.
/// {@endtemplate}
class PostMediumOverlaidLayout extends StatelessWidget {
/// {@macro post_medium_overlaid_layout}
const PostMediumOverlaidLayout({
required this.title,
required this.imageUrl,
super.key,
});
/// Title of post.
final String title;
/// The url of this post image displayed in overlay.
final String imageUrl;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Stack(
alignment: Alignment.bottomLeft,
children: [
OverlaidImage(
imageUrl: imageUrl,
gradientColor: AppColors.black.withOpacity(0.7),
),
Padding(
padding: const EdgeInsets.all(AppSpacing.sm),
child: Text(
title,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: textTheme.titleSmall
?.copyWith(color: AppColors.highEmphasisPrimary),
),
),
],
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_overlaid_layout.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_medium/post_medium_overlaid_layout.dart",
"repo_id": "news_toolkit",
"token_count": 514
} | 924 |
import 'dart:async';
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart' hide ProgressIndicator;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import 'package:platform/platform.dart' as platform;
/// {@template banner_ad_failed_to_load_exception}
/// An exception thrown when loading a banner ad fails.
/// {@endtemplate}
class BannerAdFailedToLoadException implements Exception {
/// {@macro banner_ad_failed_to_load_exception}
BannerAdFailedToLoadException(this.error);
/// The error which was caught.
final Object error;
}
/// {@template banner_ad_failed_to_get_size_exception}
/// An exception thrown when getting a banner ad size fails.
/// {@endtemplate}
class BannerAdFailedToGetSizeException implements Exception {
/// {@macro banner_ad_failed_to_get_size_exception}
BannerAdFailedToGetSizeException();
}
/// Signature for [BannerAd] builder.
typedef BannerAdBuilder = BannerAd Function({
required AdSize size,
required String adUnitId,
required BannerAdListener listener,
required AdRequest request,
});
/// Signature for [AnchoredAdaptiveBannerAdSize] provider.
typedef AnchoredAdaptiveAdSizeProvider = Future<AnchoredAdaptiveBannerAdSize?>
Function(
Orientation orientation,
int width,
);
/// {@template banner_ad_content}
/// A reusable content of a banner ad.
/// {@endtemplate}
class BannerAdContent extends StatefulWidget {
/// {@macro banner_ad_content}
const BannerAdContent({
required this.size,
this.adFailedToLoadTitle,
this.adsRetryPolicy = const AdsRetryPolicy(),
this.anchoredAdaptiveWidth,
this.adUnitId,
this.adBuilder = BannerAd.new,
this.anchoredAdaptiveAdSizeProvider =
AdSize.getAnchoredAdaptiveBannerAdSize,
this.currentPlatform = const platform.LocalPlatform(),
this.onAdLoaded,
this.showProgressIndicator = true,
super.key,
});
/// The size of this banner ad.
final BannerAdSize size;
/// The title displayed when this ad fails to load.
final String? adFailedToLoadTitle;
/// The retry policy for loading ads.
final AdsRetryPolicy adsRetryPolicy;
/// The width of this banner ad for [BannerAdSize.anchoredAdaptive].
///
/// Defaults to the width of the device.
final int? anchoredAdaptiveWidth;
/// The unit id of this banner ad.
///
/// Defaults to [androidTestUnitId] on Android
/// and [iosTestUnitAd] on iOS.
final String? adUnitId;
/// The builder of this banner ad.
final BannerAdBuilder adBuilder;
/// The provider for this banner ad for [BannerAdSize.anchoredAdaptive].
final AnchoredAdaptiveAdSizeProvider anchoredAdaptiveAdSizeProvider;
/// The current platform where this banner ad is displayed.
final platform.Platform currentPlatform;
/// Called once when this banner ad loads.
final VoidCallback? onAdLoaded;
/// Whether the progress indicator should be shown when the ad is loading.
///
/// Defaults to true.
final bool showProgressIndicator;
/// The Android test unit id of this banner ad.
@visibleForTesting
static const androidTestUnitId = 'ca-app-pub-3940256099942544/6300978111';
/// The iOS test unit id of this banner ad.
@visibleForTesting
static const iosTestUnitAd = 'ca-app-pub-3940256099942544/2934735716';
/// The size values of this banner ad.
///
/// The width of [BannerAdSize.anchoredAdaptive] depends on
/// [anchoredAdaptiveWidth] and is defined in
/// [_BannerAdContentState._getAnchoredAdaptiveAdSize].
/// The height of such an ad is determined by Google.
static const _sizeValues = <BannerAdSize, AdSize>{
BannerAdSize.normal: AdSize.banner,
BannerAdSize.large: AdSize.mediumRectangle,
BannerAdSize.extraLarge: AdSize(width: 300, height: 600),
};
@override
State<BannerAdContent> createState() => _BannerAdContentState();
}
class _BannerAdContentState extends State<BannerAdContent>
with AutomaticKeepAliveClientMixin {
BannerAd? _ad;
AdSize? _adSize;
bool _adLoaded = false;
bool _adFailedToLoad = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
unawaited(_loadAd());
}
@override
void dispose() {
_ad?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
final adFailedToLoadTitle = widget.adFailedToLoadTitle;
return SizedBox(
key: const Key('bannerAdContent_sizedBox'),
width: (_adSize?.width ?? 0).toDouble(),
height: (_adSize?.height ?? 0).toDouble(),
child: Center(
child: _adLoaded
? AdWidget(ad: _ad!)
: _adFailedToLoad && adFailedToLoadTitle != null
? Text(adFailedToLoadTitle)
: widget.showProgressIndicator
? const ProgressIndicator(color: AppColors.transparent)
: const SizedBox(),
),
);
}
@override
bool get wantKeepAlive => true;
Future<void> _loadAd() async {
AdSize? adSize;
if (widget.size == BannerAdSize.anchoredAdaptive) {
adSize = await _getAnchoredAdaptiveAdSize();
} else {
adSize = BannerAdContent._sizeValues[widget.size];
}
setState(() => _adSize = adSize);
if (_adSize == null) {
return _reportError(
BannerAdFailedToGetSizeException(),
StackTrace.current,
);
}
await _loadAdInstance();
}
Future<void> _loadAdInstance({int retry = 0}) async {
if (!mounted) return;
try {
final adCompleter = Completer<Ad>();
setState(
() => _ad = widget.adBuilder(
adUnitId: widget.adUnitId ??
(widget.currentPlatform.isAndroid
? BannerAdContent.androidTestUnitId
: BannerAdContent.iosTestUnitAd),
request: const AdRequest(),
size: _adSize!,
listener: BannerAdListener(
onAdLoaded: adCompleter.complete,
onAdFailedToLoad: (_, error) {
adCompleter.completeError(error);
},
),
)..load(),
);
_onAdLoaded(await adCompleter.future);
} catch (error, stackTrace) {
_reportError(BannerAdFailedToLoadException(error), stackTrace);
if (retry < widget.adsRetryPolicy.maxRetryCount) {
final nextRetry = retry + 1;
await Future<void>.delayed(
widget.adsRetryPolicy.getIntervalForRetry(nextRetry),
);
return _loadAdInstance(retry: nextRetry);
} else {
if (mounted) setState(() => _adFailedToLoad = true);
}
}
}
void _onAdLoaded(Ad ad) {
if (mounted) {
setState(() {
_ad = ad as BannerAd;
_adLoaded = true;
});
widget.onAdLoaded?.call();
}
}
/// Returns an ad size for [BannerAdSize.anchoredAdaptive].
///
/// Only supports the portrait mode.
Future<AnchoredAdaptiveBannerAdSize?> _getAnchoredAdaptiveAdSize() async {
final adWidth = widget.anchoredAdaptiveWidth ??
MediaQuery.of(context).size.width.truncate();
return widget.anchoredAdaptiveAdSizeProvider(
Orientation.portrait,
adWidth,
);
}
void _reportError(Object exception, StackTrace stackTrace) =>
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stackTrace,
),
);
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_content.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/banner_ad_content.dart",
"repo_id": "news_toolkit",
"token_count": 2783
} | 925 |
import 'package:mocktail/mocktail.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
class _MockPathProvider extends Mock
with MockPlatformInterfaceMixin
implements PathProviderPlatform {}
void setUpMockPathProvider() {
final pathProviderPlatform = _MockPathProvider();
PathProviderPlatform.instance = pathProviderPlatform;
when(
pathProviderPlatform.getApplicationSupportPath,
).thenAnswer((_) async => '.');
when(pathProviderPlatform.getTemporaryPath).thenAnswer((_) async => '.');
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/path_provider.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/helpers/path_provider.dart",
"repo_id": "news_toolkit",
"token_count": 182
} | 926 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail_image_network/mocktail_image_network.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() {
group('PostLargeImage', () {
testWidgets(
'renders InlineImage '
'when isContentOverlaid is false', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isContentOverlaid: false,
isLocked: false,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(OverlaidImage), findsNothing);
expect(find.byType(InlineImage), findsOneWidget);
});
testWidgets(
'renders OverlaidImage '
'when isContentOverlaid is true', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isContentOverlaid: true,
isLocked: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(InlineImage), findsNothing);
expect(find.byType(OverlaidImage), findsOneWidget);
});
testWidgets(
'renders LockIcon '
'when isLocked is true and '
'when isContentOverlaid is true', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isLocked: true,
isContentOverlaid: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(LockIcon), findsOneWidget);
});
testWidgets(
'renders LockIcon '
'when isLocked is true and '
'when isContentOverlaid is false', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isLocked: true,
isContentOverlaid: false,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(LockIcon), findsOneWidget);
});
testWidgets(
'does not render LockIcon '
'when isLocked is false and '
'when isContentOverlaid is true', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isLocked: false,
isContentOverlaid: true,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(LockIcon), findsNothing);
});
testWidgets(
'does not render LockIcon '
'when isLocked is false and '
'when isContentOverlaid is false', (tester) async {
final postLargeImage = PostLargeImage(
imageUrl: 'url',
isLocked: false,
isContentOverlaid: false,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(postLargeImage),
);
expect(find.byType(LockIcon), findsNothing);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/post_large/post_large_image_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/post_large/post_large_image_test.dart",
"repo_id": "news_toolkit",
"token_count": 1336
} | 927 |
// ignore_for_file: prefer_const_constructors
import 'package:app_ui/app_ui.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks_ui/src/sliver_grid_custom_delegate.dart';
void main() {
group('SliverGridCustomDelegate', () {
testWidgets('getLayout when crossAxisCount is <=1', (tester) async {
const childAspectRatio = 3 / 2;
const childCrossAxisExtent = 343.0;
const childMainAxisExtent = childCrossAxisExtent * 1 / childAspectRatio;
final customMaxCrossAxisDelegate = CustomMaxCrossAxisDelegate(
maxCrossAxisExtent: 400,
mainAxisSpacing: AppSpacing.md,
crossAxisSpacing: AppSpacing.md,
childAspectRatio: childAspectRatio,
);
final customDelegate = customMaxCrossAxisDelegate.getLayout(
SliverConstraints(
axisDirection: AxisDirection.down,
growthDirection: GrowthDirection.forward,
userScrollDirection: ScrollDirection.idle,
scrollOffset: 0,
precedingScrollExtent: 1525,
overlap: 0,
remainingPaintExtent: 0,
crossAxisExtent: childCrossAxisExtent,
crossAxisDirection: AxisDirection.right,
viewportMainAxisExtent: 505,
remainingCacheExtent: 0,
cacheOrigin: 0,
),
);
final headerDelegate = HeaderGridTileLayout(
crossAxisCount: 1,
mainAxisStride: childMainAxisExtent + AppSpacing.md,
crossAxisStride: childCrossAxisExtent + AppSpacing.md,
childMainAxisExtent: childMainAxisExtent,
childCrossAxisExtent: childCrossAxisExtent,
reverseCrossAxis: false,
);
expect(customDelegate, headerDelegate);
});
testWidgets('getLayout when crossAxisCount is >1', (tester) async {
const childAspectRatio = 3 / 2;
const crossAxisExtent = 400.0;
const maxCrossAxisExtent = 200.0;
const childCrossAxisExtent = maxCrossAxisExtent - AppSpacing.xs / 2;
const childMainAxisExtent = childCrossAxisExtent * 1 / childAspectRatio;
final customMaxCrossAxisDelegate = CustomMaxCrossAxisDelegate(
maxCrossAxisExtent: maxCrossAxisExtent,
mainAxisSpacing: AppSpacing.xs,
crossAxisSpacing: AppSpacing.xs,
childAspectRatio: 3 / 2,
);
final customDelegate = customMaxCrossAxisDelegate.getLayout(
SliverConstraints(
axisDirection: AxisDirection.down,
growthDirection: GrowthDirection.forward,
userScrollDirection: ScrollDirection.idle,
scrollOffset: 0,
precedingScrollExtent: 1525,
overlap: 0,
remainingPaintExtent: 0,
crossAxisExtent: crossAxisExtent,
crossAxisDirection: AxisDirection.right,
viewportMainAxisExtent: 505,
remainingCacheExtent: 0,
cacheOrigin: 0,
),
);
final headerDelegate = HeaderGridTileLayout(
crossAxisCount: (crossAxisExtent / maxCrossAxisExtent).ceil(),
mainAxisStride: childMainAxisExtent + AppSpacing.xs,
crossAxisStride: childCrossAxisExtent + AppSpacing.xs,
childMainAxisExtent: childMainAxisExtent,
childCrossAxisExtent: childCrossAxisExtent,
reverseCrossAxis: false,
);
expect(customDelegate, headerDelegate);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/sliver_grid_custom_delegate_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/sliver_grid_custom_delegate_test.dart",
"repo_id": "news_toolkit",
"token_count": 1466
} | 928 |
// ignore_for_file: 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_ui/src/widgets/widgets.dart';
import '../../helpers/helpers.dart';
void main() {
group('OverlaidImage', () {
testWidgets('renders correctly', (tester) async {
final overlaidImage = OverlaidImage(
imageUrl: 'url',
gradientColor: Colors.black,
);
await mockNetworkImages(
() async => tester.pumpContentThemedApp(overlaidImage),
);
expect(
find.byKey(const Key('overlaidImage_stack')),
findsOneWidget,
);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/overlaid_image_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/overlaid_image_test.dart",
"repo_id": "news_toolkit",
"token_count": 300
} | 929 |
export 'package:flutter_news_example_api/client.dart'
show CategoriesResponse, Category, Feed, FeedResponse;
export 'src/news_repository.dart';
| news_toolkit/flutter_news_example/packages/news_repository/lib/news_repository.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_repository/lib/news_repository.dart",
"repo_id": "news_toolkit",
"token_count": 49
} | 930 |
name: notifications_client
description: A Generic Notifications Client Interface.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dev_dependencies:
test: ^1.21.4
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/pubspec.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/pubspec.yaml",
"repo_id": "news_toolkit",
"token_count": 88
} | 931 |
// ignore_for_file: prefer_const_constructors
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'dart:async';
import 'package:flutter_news_example_api/client.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:notifications_client/notifications_client.dart';
import 'package:notifications_repository/notifications_repository.dart';
import 'package:permission_client/permission_client.dart';
import 'package:storage/storage.dart';
class MockPermissionClient extends Mock implements PermissionClient {}
class MockNotificationsStorage extends Mock implements NotificationsStorage {}
class MockNotificationsClient extends Mock implements NotificationsClient {}
class MockFlutterNewsExampleApiClient extends Mock
implements FlutterNewsExampleApiClient {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('NotificationsRepository', () {
late PermissionClient permissionClient;
late NotificationsStorage storage;
late NotificationsClient notificationsClient;
late FlutterNewsExampleApiClient apiClient;
setUp(() {
permissionClient = MockPermissionClient();
storage = MockNotificationsStorage();
notificationsClient = MockNotificationsClient();
apiClient = MockFlutterNewsExampleApiClient();
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.denied);
when(
() => storage.setNotificationsEnabled(
enabled: any(named: 'enabled'),
),
).thenAnswer((_) async {});
when(
() => storage.setCategoriesPreferences(
categories: any(named: 'categories'),
),
).thenAnswer((_) async {});
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => false);
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => {Category.top});
when(() => notificationsClient.subscribeToCategory(any()))
.thenAnswer((_) async {});
when(() => notificationsClient.unsubscribeFromCategory(any()))
.thenAnswer((_) async {});
when(apiClient.getCategories).thenAnswer(
(_) async => CategoriesResponse(categories: []),
);
});
group('constructor', () {
test(
'initializes categories preferences '
'from FlutterNewsExampleApiClient.getCategories', () async {
when(storage.fetchCategoriesPreferences).thenAnswer((_) async => null);
final completer = Completer<void>();
const categories = [Category.top, Category.technology];
when(apiClient.getCategories).thenAnswer(
(_) async => CategoriesResponse(categories: categories),
);
when(
() => storage.setCategoriesPreferences(
categories: any(named: 'categories'),
),
).thenAnswer((_) async => completer.complete());
final _ = NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
);
await expectLater(completer.future, completes);
verify(
() => storage.setCategoriesPreferences(
categories: categories.toSet(),
),
).called(1);
});
test(
'throws an InitializeCategoriesPreferencesFailure '
'when initialization fails', () async {
Object? caughtError;
await runZonedGuarded(() async {
when(storage.fetchCategoriesPreferences).thenThrow(Exception());
final _ = NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
);
}, (error, stackTrace) {
caughtError = error;
});
expect(
caughtError,
isA<InitializeCategoriesPreferencesFailure>(),
);
});
});
group('toggleNotifications', () {
group('when enable is true', () {
test(
'calls openPermissionSettings on PermissionClient '
'when PermissionStatus is permanentlyDenied', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.permanentlyDenied);
when(permissionClient.openPermissionSettings)
.thenAnswer((_) async => true);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true);
verify(permissionClient.openPermissionSettings).called(1);
});
test(
'calls openPermissionSettings on PermissionClient '
'when PermissionStatus is restricted', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.restricted);
when(permissionClient.openPermissionSettings)
.thenAnswer((_) async => true);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true);
verify(permissionClient.openPermissionSettings).called(1);
});
test(
'calls requestNotifications on PermissionClient '
'when PermissionStatus is denied', () async {
when(permissionClient.requestNotifications)
.thenAnswer((_) async => PermissionStatus.granted);
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.denied);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true);
verify(permissionClient.requestNotifications).called(1);
});
test('subscribes to categories preferences', () async {
const categoriesPreferences = {
Category.top,
Category.technology,
};
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => categoriesPreferences);
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.granted);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true);
for (final category in categoriesPreferences) {
verify(() => notificationsClient.subscribeToCategory(category.name))
.called(1);
}
});
test(
'calls setNotificationsEnabled with true '
'on NotificationsStorage', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.granted);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true);
verify(
() => storage.setNotificationsEnabled(enabled: true),
).called(1);
});
});
group('when enabled is false', () {
test('unsubscribes from categories preferences', () async {
const categoriesPreferences = {
Category.top,
Category.technology,
};
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => categoriesPreferences);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: false);
for (final category in categoriesPreferences) {
verify(
() => notificationsClient.unsubscribeFromCategory(category.name),
).called(1);
}
});
test(
'calls setNotificationsEnabled with false '
'on NotificationsStorage', () async {
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: false);
verify(
() => storage.setNotificationsEnabled(enabled: false),
).called(1);
});
});
test(
'throws a ToggleNotificationsFailure '
'when toggling notifications fails', () async {
when(permissionClient.notificationsStatus).thenThrow(Exception());
expect(
() => NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).toggleNotifications(enable: true),
throwsA(isA<ToggleNotificationsFailure>()),
);
});
});
group('fetchNotificationsEnabled', () {
test(
'returns true '
'when the notification permission is granted '
'and the notification setting is enabled', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.granted);
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => true);
final result = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchNotificationsEnabled();
expect(result, isTrue);
});
test(
'returns false '
'when the notification permission is not granted '
'and the notification setting is enabled', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.denied);
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => true);
final result = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchNotificationsEnabled();
expect(result, isFalse);
});
test(
'returns false '
'when the notification permission is not granted '
'and the notification setting is disabled', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.denied);
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => false);
final result = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchNotificationsEnabled();
expect(result, isFalse);
});
test(
'returns false '
'when the notification permission is granted '
'and the notification setting is disabled', () async {
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.granted);
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => false);
final result = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchNotificationsEnabled();
expect(result, isFalse);
});
test(
'throws a FetchNotificationsEnabledFailure '
'when fetching notifications enabled fails', () async {
when(permissionClient.notificationsStatus).thenThrow(Exception());
expect(
NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchNotificationsEnabled(),
throwsA(isA<FetchNotificationsEnabledFailure>()),
);
});
});
group('setCategoriesPreferences', () {
const categoriesPreferences = {
Category.top,
Category.technology,
};
test('calls setCategoriesPreferences on NotificationsStorage', () async {
when(
() => storage.setCategoriesPreferences(
categories: any(named: 'categories'),
),
).thenAnswer((_) async {});
await expectLater(
NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).setCategoriesPreferences(categoriesPreferences),
completes,
);
verify(
() => storage.setCategoriesPreferences(
categories: categoriesPreferences,
),
).called(1);
});
test('unsubscribes from previous categories preferences', () async {
const previousCategoriesPreferences = {
Category.health,
Category.entertainment,
};
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => previousCategoriesPreferences);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).setCategoriesPreferences(categoriesPreferences);
for (final category in previousCategoriesPreferences) {
verify(
() => notificationsClient.unsubscribeFromCategory(category.name),
).called(1);
}
});
test(
'subscribes to categories preferences '
'when notifications are enabled', () async {
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => categoriesPreferences);
when(storage.fetchNotificationsEnabled).thenAnswer((_) async => true);
when(permissionClient.notificationsStatus)
.thenAnswer((_) async => PermissionStatus.granted);
await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).setCategoriesPreferences(categoriesPreferences);
for (final category in categoriesPreferences) {
verify(() => notificationsClient.subscribeToCategory(category.name))
.called(1);
}
});
test(
'throws a SetCategoriesPreferencesFailure '
'when setting categories preferences fails', () async {
when(
() => storage.setCategoriesPreferences(
categories: any(named: 'categories'),
),
).thenThrow(Exception());
expect(
NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).setCategoriesPreferences(categoriesPreferences),
throwsA(isA<SetCategoriesPreferencesFailure>()),
);
});
});
group('fetchCategoriesPreferences', () {
const categoriesPreferences = {
Category.top,
Category.technology,
};
test('returns categories preferences from NotificationsStorage',
() async {
when(storage.fetchCategoriesPreferences)
.thenAnswer((_) async => categoriesPreferences);
final actualPreferences = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchCategoriesPreferences();
expect(actualPreferences, equals(categoriesPreferences));
});
test(
'returns null '
'when categories preferences do not exist in NotificationsStorage',
() async {
when(storage.fetchCategoriesPreferences).thenAnswer((_) async => null);
final preferences = await NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
).fetchCategoriesPreferences();
expect(preferences, isNull);
});
test(
'throws a FetchCategoriesPreferencesFailure '
'when read fails', () async {
final notificationsRepository = NotificationsRepository(
permissionClient: permissionClient,
storage: storage,
notificationsClient: notificationsClient,
apiClient: apiClient,
);
when(storage.fetchCategoriesPreferences)
.thenThrow(StorageException(Error()));
expect(
notificationsRepository.fetchCategoriesPreferences,
throwsA(isA<FetchCategoriesPreferencesFailure>()),
);
});
});
});
group('NotificationsFailure', () {
final error = Exception('errorMessage');
group('InitializeCategoriesPreferencesFailure', () {
test('has correct props', () {
expect(InitializeCategoriesPreferencesFailure(error).props, [error]);
});
});
group('ToggleNotificationsFailure', () {
test('has correct props', () {
expect(ToggleNotificationsFailure(error).props, [error]);
});
});
group('FetchNotificationsEnabledFailure', () {
test('has correct props', () {
expect(FetchNotificationsEnabledFailure(error).props, [error]);
});
});
group('SetCategoriesPreferencesFailure', () {
test('has correct props', () {
expect(SetCategoriesPreferencesFailure(error).props, [error]);
});
});
group('FetchCategoriesPreferencesFailure', () {
test('has correct props', () {
expect(FetchCategoriesPreferencesFailure(error).props, [error]);
});
});
});
}
| news_toolkit/flutter_news_example/packages/notifications_repository/test/src/notifications_repository_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/test/src/notifications_repository_test.dart",
"repo_id": "news_toolkit",
"token_count": 7509
} | 932 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/storage/persistent_storage/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/storage/persistent_storage/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 933 |
name: storage
description: A Key/Value Storage Client for Dart.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dev_dependencies:
test: ^1.21.4
very_good_analysis: ^5.1.0
| news_toolkit/flutter_news_example/packages/storage/storage/pubspec.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/storage/storage/pubspec.yaml",
"repo_id": "news_toolkit",
"token_count": 78
} | 934 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/ads/ads.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart' as ads;
class FakeRewardItem extends Fake implements ads.RewardItem {}
void main() {
group('FullScreenAdsEvent', () {
group('LoadInterstitialAdRequested', () {
test('supports value comparisons', () {
expect(LoadInterstitialAdRequested(), LoadInterstitialAdRequested());
});
});
group('LoadRewardedAdRequested', () {
test('supports value comparisons', () {
expect(LoadRewardedAdRequested(), LoadRewardedAdRequested());
});
});
group('ShowInterstitialAdRequested', () {
test('supports value comparisons', () {
expect(ShowInterstitialAdRequested(), ShowInterstitialAdRequested());
});
});
group('ShowRewardedAdRequested', () {
test('supports value comparisons', () {
expect(ShowRewardedAdRequested(), ShowRewardedAdRequested());
});
});
group('EarnedReward', () {
test('supports value comparisons', () {
final reward = FakeRewardItem();
expect(EarnedReward(reward), EarnedReward(reward));
});
});
});
}
| news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/ads/bloc/full_screen_ads_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 448
} | 935 |
// 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/ads/ads.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart' as ads;
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:mockingjay/mockingjay.dart';
import 'package:news_blocks_ui/news_blocks_ui.dart';
import 'package:user_repository/user_repository.dart';
import '../../helpers/helpers.dart';
class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState>
implements ArticleBloc {}
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
class MockFullScreenAdsBloc
extends MockBloc<FullScreenAdsEvent, FullScreenAdsState>
implements FullScreenAdsBloc {}
class MockRewardItem extends Mock implements ads.RewardItem {}
void main() {
initMockHydratedStorage();
group('ArticlePage', () {
late FullScreenAdsBloc fullScreenAdsBloc;
late AppBloc appBloc;
setUp(() {
fullScreenAdsBloc = MockFullScreenAdsBloc();
appBloc = MockAppBloc();
whenListen(
fullScreenAdsBloc,
Stream.value(FullScreenAdsState.initial()),
initialState: FullScreenAdsState.initial(),
);
});
test('has a route', () {
expect(ArticlePage.route(id: 'id'), isA<MaterialPageRoute<void>>());
});
testWidgets('renders ArticleView', (tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
ArticlePage(
id: 'id',
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
);
expect(find.byType(ArticleView), findsOneWidget);
});
testWidgets('provides ArticleBloc', (tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
ArticlePage(
id: 'id',
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
);
final BuildContext viewContext = tester.element(find.byType(ArticleView));
expect(viewContext.read<ArticleBloc>(), isNotNull);
});
group('ArticleView', () {
late ArticleBloc articleBloc;
setUp(() {
articleBloc = MockArticleBloc();
when(() => articleBloc.state).thenReturn(ArticleState.initial());
});
testWidgets('renders AppBar', (tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
expect(find.byType(AppBar), findsOneWidget);
});
group('renders ShareButton ', () {
testWidgets('when url is not empty', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(uri: Uri(path: 'notEmptyUrl')),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
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 tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
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 tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
expect(find.byType(ShareButton), findsNothing);
});
});
testWidgets('renders ArticleSubscribeButton', (tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
expect(find.byType(ArticleSubscribeButton), findsOneWidget);
});
group('ArticleSubscribeButton', () {
testWidgets('renders AppButton', (tester) async {
await tester.pumpApp(
Row(
children: [ArticleSubscribeButton()],
),
);
expect(find.byType(AppButton), findsOneWidget);
});
group('opens PurchaseSubscriptionDialog', () {
late InAppPurchaseRepository inAppPurchaseRepository;
setUp(() {
inAppPurchaseRepository = MockInAppPurchaseRepository();
when(() => inAppPurchaseRepository.purchaseUpdate).thenAnswer(
(_) => const Stream.empty(),
);
when(inAppPurchaseRepository.fetchSubscriptions).thenAnswer(
(_) async => [],
);
});
testWidgets('when tapped', (tester) async {
await tester.pumpApp(
Row(children: [ArticleSubscribeButton()]),
inAppPurchaseRepository: inAppPurchaseRepository,
);
await tester.tap(find.byType(ArticleSubscribeButton));
await tester.pump();
expect(find.byType(PurchaseSubscriptionDialog), findsOneWidget);
});
});
testWidgets('does nothing when tapped', (tester) async {
await tester.pumpApp(
Row(
children: [ArticleSubscribeButton()],
),
);
await tester.tap(find.byType(ArticleSubscribeButton));
});
});
testWidgets('renders ArticleContent in ArticleThemeOverride',
(tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
expect(
find.descendant(
of: find.byType(ArticleThemeOverride),
matching: find.byType(ArticleContent),
),
findsOneWidget,
);
});
testWidgets(
'renders AppBar with ShareButton and '
'ArticleSubscribeButton action '
'when user is not a subscriber '
'and uri is provided', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(
uri: Uri(path: 'notEmptyUrl'),
),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
final articleSubscribeButton = find.byType(ArticleSubscribeButton);
final shareButton = find.byKey(Key('articlePage_shareButton'));
expect(articleSubscribeButton, findsOneWidget);
expect(shareButton, findsOneWidget);
final appBar = find.byType(AppBar).first;
expect(
tester.widget<AppBar>(appBar).actions,
containsAll(
<Widget>[
tester.widget<ArticleSubscribeButton>(articleSubscribeButton),
tester.widget(shareButton),
],
),
);
});
testWidgets(
'renders AppBar without ShareButton '
'when user is not a subscriber '
'and uri is not provided', (tester) async {
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
final subscribeButton = tester.widget<ArticleSubscribeButton>(
find.byType(ArticleSubscribeButton),
);
expect(
find.byWidgetPredicate(
(widget) =>
widget is AppBar &&
widget.actions!.isNotEmpty &&
widget.actions!.contains(subscribeButton),
),
findsOneWidget,
);
expect(find.byType(ShareButton), findsNothing);
});
testWidgets(
'renders AppBar with ShareButton '
'action when user is a subscriber '
'and url is not empty', (tester) async {
when(() => appBloc.state).thenReturn(
AppState.authenticated(
User(
id: 'id',
name: 'name',
email: 'email',
subscriptionPlan: SubscriptionPlan.premium,
),
),
);
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(uri: Uri(path: 'notEmptyUrl')),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
appBloc: appBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
final shareButton = find.byKey(Key('articlePage_shareButton'));
expect(shareButton, findsOneWidget);
final appBar = find.byType(AppBar).first;
expect(
tester.widget<AppBar>(appBar).actions,
containsAll(
<Widget>[
tester.widget(shareButton),
],
),
);
});
group('navigates', () {
testWidgets('back when back button is pressed', (tester) async {
final navigator = MockNavigator();
when(navigator.pop).thenAnswer((_) async {});
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
navigator: navigator,
);
await tester.tap(find.byType(AppBackButton));
await tester.pump();
verify(navigator.pop).called(1);
});
});
testWidgets(
'adds ArticleRequested to ArticleBloc '
'when hasReachedArticleViewsLimit changes to false', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable(
[
ArticleState.initial()
.copyWith(hasReachedArticleViewsLimit: true),
ArticleState.initial()
.copyWith(hasReachedArticleViewsLimit: false),
],
),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
verify(() => articleBloc.add(ArticleRequested()));
});
testWidgets(
'adds ShowInterstitialAdRequested to FullScreenAdsBloc '
'when interstitialAdBehavior is onOpen and '
'showInterstitialAd is true', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable(
[
ArticleState.initial().copyWith(showInterstitialAd: false),
ArticleState.initial().copyWith(showInterstitialAd: true),
],
),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
verify(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()))
.called(1);
});
testWidgets(
'verify ShowInterstitialAdRequested is not '
'added to FullScreenAdsBloc when interstitialAdBehavior is onOpen '
'and showInterstitialAd is false', (tester) async {
whenListen(
articleBloc,
Stream.fromIterable(
[
ArticleState.initial().copyWith(showInterstitialAd: false),
],
),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
verifyNever(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()));
});
testWidgets(
'adds ShowInterstitialAdRequested to FullScreenAdsBloc '
'when interstitialAdBehavior in onClose and '
'showInterstitialAd is true', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(showInterstitialAd: true),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onClose,
),
),
);
await tester.tap(find.byType(AppBackButton));
verify(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()))
.called(1);
});
testWidgets(
'adds ShowInterstitialAdRequested to FullScreenAdsBloc '
'when interstitialAdBehavior in onClose and '
'showInterstitialAd is true and '
'user taps system back button', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(showInterstitialAd: true),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onClose,
),
),
);
// Use didPopRoute() to simulate the system back button.
final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp));
// ignore: avoid_dynamic_calls
await widgetsAppState.didPopRoute();
await tester.pump();
verify(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()))
.called(1);
});
testWidgets(
'verify ShowInterstitialAdRequested is not '
'added to FullScreenAdsBloc when interstitialAdBehavior is onClose '
'showInterstitialAd is false ', (tester) async {
when(() => articleBloc.state).thenReturn(ArticleState.initial());
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onClose,
),
),
);
await tester.tap(find.byType(AppBackButton));
verifyNever(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()));
});
testWidgets(
'adds ShowInterstitialAdRequested to FullScreenAdsBloc '
'with video article '
'when interstitialAdBehavior in onClose and '
'showInterstitialAd is true', (tester) async {
when(() => articleBloc.state).thenReturn(
ArticleState.initial().copyWith(showInterstitialAd: true),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: true,
interstitialAdBehavior: InterstitialAdBehavior.onClose,
),
),
);
await tester.tap(find.byType(AppBackButton));
verify(() => fullScreenAdsBloc.add(ShowInterstitialAdRequested()))
.called(1);
});
testWidgets(
'adds ArticleRewardedAdWatched to ArticleBloc '
'when earnedReward is not null', (tester) async {
whenListen(
fullScreenAdsBloc,
Stream.fromIterable([
FullScreenAdsState.initial().copyWith(
earnedReward: MockRewardItem(),
),
]),
initialState: FullScreenAdsState.initial(),
);
await tester.pumpApp(
fullScreenAdsBloc: fullScreenAdsBloc,
BlocProvider.value(
value: articleBloc,
child: ArticleView(
isVideoArticle: false,
interstitialAdBehavior: InterstitialAdBehavior.onOpen,
),
),
);
verify(() => articleBloc.add(ArticleRewardedAdWatched())).called(1);
});
});
});
}
| news_toolkit/flutter_news_example/test/article/view/article_page_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/article/view/article_page_test.dart",
"repo_id": "news_toolkit",
"token_count": 9123
} | 936 |
// ignore_for_file: prefer_const_constructors
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'package:article_repository/article_repository.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart' hide Spacer;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/categories/categories.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/newsletter/newsletter.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 'package:visibility_detector/visibility_detector.dart';
import '../../helpers/helpers.dart';
class MockArticleRepository extends Mock implements ArticleRepository {}
class MockCategoriesBloc extends MockBloc<CategoriesEvent, CategoriesState>
implements CategoriesBloc {}
void main() {
initMockHydratedStorage();
group('CategoryFeedItem', () {
late ArticleRepository articleRepository;
setUp(() {
articleRepository = MockArticleRepository();
when(articleRepository.incrementArticleViews).thenAnswer((_) async {});
when(articleRepository.resetArticleViews).thenAnswer((_) async {});
when(articleRepository.fetchArticleViews)
.thenAnswer((_) async => ArticleViews(0, null));
when(
() => articleRepository.getArticle(
id: any(named: 'id'),
limit: any(named: 'limit'),
offset: any(named: 'offset'),
),
).thenAnswer(
(_) async => ArticleResponse(
title: 'title',
content: [],
totalCount: 0,
url: Uri.parse('https://www.dglobe.com/'),
isPremium: false,
isPreview: false,
),
);
when(
() => articleRepository.getRelatedArticles(
id: any(named: 'id'),
limit: any(named: 'limit'),
offset: any(named: 'offset'),
),
).thenAnswer(
(_) async => RelatedArticlesResponse(
relatedArticles: [],
totalCount: 0,
),
);
});
testWidgets(
'renders DividerHorizontal '
'for DividerHorizontalBlock', (tester) async {
const block = DividerHorizontalBlock();
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(
find.byWidgetPredicate(
(widget) => widget is DividerHorizontal && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders Spacer '
'for SpacerBlock', (tester) async {
const block = SpacerBlock(spacing: Spacing.large);
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(
find.byWidgetPredicate(
(widget) => widget is Spacer && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders SectionHeader '
'for SectionHeaderBlock', (tester) async {
const block = SectionHeaderBlock(title: 'title');
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(
find.byWidgetPredicate(
(widget) => widget is SectionHeader && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders PostLarge '
'for PostLargeBlock', (tester) async {
final block = PostLargeBlock(
id: 'id',
category: PostCategory.technology,
author: 'author',
publishedAt: DateTime(2022, 3, 9),
imageUrl: 'imageUrl',
title: 'title',
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
);
});
expect(
find.byWidgetPredicate(
(widget) => widget is PostLarge && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders PostMedium '
'for PostMediumBlock', (tester) async {
final block = PostMediumBlock(
id: 'id',
category: PostCategory.sports,
author: 'author',
publishedAt: DateTime(2022, 3, 10),
imageUrl: 'imageUrl',
title: 'title',
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
});
expect(
find.byWidgetPredicate(
(widget) => widget is PostMedium && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders PostSmall '
'for PostSmallBlock', (tester) async {
final block = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
});
expect(
find.byWidgetPredicate(
(widget) => widget is PostSmall && widget.block == block,
),
findsOneWidget,
);
});
testWidgets(
'renders PostGrid '
'for PostGridGroupBlock', (tester) async {
final block = PostGridGroupBlock(
category: PostCategory.science,
tiles: [
PostGridTileBlock(
id: 'id',
category: PostCategory.science,
author: 'author',
publishedAt: DateTime(2022, 3, 12),
imageUrl: 'imageUrl',
title: 'title',
)
],
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
);
});
expect(
find.byWidgetPredicate(
(widget) => widget is PostGrid && widget.gridGroupBlock == block,
),
findsOneWidget,
);
});
testWidgets(
'renders Newsletter '
'for NewsletterBlock', (tester) async {
VisibilityDetectorController.instance.updateInterval = Duration.zero;
final block = NewsletterBlock();
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(find.byType(Newsletter), findsOneWidget);
});
testWidgets(
'renders BannerAd '
'for BannerAdBlock', (tester) async {
final block = BannerAdBlock(size: BannerAdSize.normal);
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(find.byType(BannerAd), findsOneWidget);
});
testWidgets(
'renders SizedBox '
'for unsupported block', (tester) async {
final block = UnknownBlock();
await tester.pumpApp(
CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
);
expect(find.byType(SizedBox), findsNothing);
});
group(
'navigates to ArticlePage '
'on NavigateToArticleAction', () {
const articleId = 'articleId';
testWidgets('from PostLarge', (tester) async {
final block = PostLargeBlock(
id: articleId,
category: PostCategory.technology,
author: 'author',
publishedAt: DateTime(2022, 3, 9),
imageUrl: 'imageUrl',
title: 'title',
isContentOverlaid: true,
action: NavigateToArticleAction(articleId: articleId),
);
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
await tester.ensureVisible(find.byType(PostLarge));
await tester.tap(find.byType(PostLarge));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) => widget is ArticlePage && widget.id == articleId,
),
findsOneWidget,
);
});
testWidgets('from PostMedium', (tester) async {
final block = PostMediumBlock(
id: 'id',
category: PostCategory.sports,
author: 'author',
publishedAt: DateTime(2022, 3, 10),
imageUrl: 'imageUrl',
title: 'title',
isContentOverlaid: true,
action: NavigateToArticleAction(articleId: articleId),
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
await tester.ensureVisible(find.byType(PostMedium));
await tester.tap(find.byType(PostMedium));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) => widget is ArticlePage && widget.id == articleId,
),
findsOneWidget,
);
});
testWidgets('from PostSmall', (tester) async {
final block = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
action: NavigateToArticleAction(articleId: articleId),
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
await tester.ensureVisible(find.byType(PostSmallContent));
await tester.tap(find.byType(PostSmallContent));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) => widget is ArticlePage && widget.id == articleId,
),
findsOneWidget,
);
});
testWidgets('from PostGrid', (tester) async {
final block = PostGridGroupBlock(
category: PostCategory.science,
tiles: [
PostGridTileBlock(
id: 'id',
category: PostCategory.science,
author: 'author',
publishedAt: DateTime(2022, 3, 12),
imageUrl: 'imageUrl',
title: 'title',
action: NavigateToArticleAction(articleId: articleId),
)
],
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
// We're tapping on a PostLarge as the first post of the PostGrid
// is displayed as a large post.
await tester.ensureVisible(find.byType(PostLarge));
await tester.tap(find.byType(PostLarge));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) => widget is ArticlePage && widget.id == articleId,
),
findsOneWidget,
);
});
});
group(
'navigates to video ArticlePage '
'on NavigateToVideoArticleAction', () {
const articleId = 'articleId';
testWidgets('from PostLarge', (tester) async {
final block = PostLargeBlock(
id: articleId,
category: PostCategory.technology,
author: 'author',
publishedAt: DateTime(2022, 3, 9),
imageUrl: 'imageUrl',
title: 'title',
isContentOverlaid: true,
action: NavigateToVideoArticleAction(articleId: articleId),
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
await tester.ensureVisible(find.byType(PostLarge));
await tester.tap(find.byType(PostLarge));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) =>
widget is ArticlePage &&
widget.id == articleId &&
widget.isVideoArticle == true,
),
findsOneWidget,
);
});
testWidgets('from PostMedium', (tester) async {
final block = PostMediumBlock(
id: 'id',
category: PostCategory.sports,
author: 'author',
publishedAt: DateTime(2022, 3, 10),
imageUrl: 'imageUrl',
title: 'title',
isContentOverlaid: true,
action: NavigateToVideoArticleAction(articleId: articleId),
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
await tester.ensureVisible(find.byType(PostMedium));
await tester.tap(find.byType(PostMedium));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) =>
widget is ArticlePage &&
widget.id == articleId &&
widget.isVideoArticle == true,
),
findsOneWidget,
);
});
testWidgets('from PostSmall', (tester) async {
final block = PostSmallBlock(
id: 'id',
category: PostCategory.health,
author: 'author',
publishedAt: DateTime(2022, 3, 11),
imageUrl: 'imageUrl',
title: 'title',
action: NavigateToVideoArticleAction(articleId: articleId),
);
await mockNetworkImages(() async {
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
articleRepository: articleRepository,
);
});
await tester.ensureVisible(find.byType(PostSmallContent));
await tester.tap(find.byType(PostSmallContent));
await tester.pumpAndSettle();
expect(
find.byWidgetPredicate(
(widget) =>
widget is ArticlePage &&
widget.id == articleId &&
widget.isVideoArticle == true,
),
findsOneWidget,
);
});
testWidgets('from PostGrid', (tester) async {
final block = PostGridGroupBlock(
category: PostCategory.science,
tiles: [
PostGridTileBlock(
id: 'id',
category: PostCategory.science,
author: 'author',
publishedAt: DateTime(2022, 3, 12),
imageUrl: 'imageUrl',
title: 'title',
action: NavigateToVideoArticleAction(articleId: articleId),
)
],
);
await tester.pumpApp(
CustomScrollView(
slivers: [CategoryFeedItem(block: block)],
),
);
// We're tapping on a PostLarge as the first post of the PostGrid
// is displayed as a large post.
await tester.ensureVisible(find.byType(PostLarge));
await tester.tap(find.byType(PostLarge));
await tester.pump();
await tester.pump(kThemeAnimationDuration);
expect(
find.byWidgetPredicate(
(widget) =>
widget is ArticlePage &&
widget.id == articleId &&
widget.isVideoArticle == true,
),
findsOneWidget,
);
});
});
testWidgets(
'adds CategorySelected to CategoriesBloc '
'on NavigateToFeedCategoryAction', (tester) async {
final categoriesBloc = MockCategoriesBloc();
const category = Category.top;
const block = SectionHeaderBlock(
title: 'title',
action: NavigateToFeedCategoryAction(category: category),
);
await tester.pumpApp(
BlocProvider<CategoriesBloc>.value(
value: categoriesBloc,
child: CustomScrollView(slivers: [CategoryFeedItem(block: block)]),
),
);
await tester.ensureVisible(find.byType(IconButton));
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
verify(() => categoriesBloc.add(CategorySelected(category: category)))
.called(1);
});
});
}
| news_toolkit/flutter_news_example/test/feed/widgets/category_feed_item_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/feed/widgets/category_feed_item_test.dart",
"repo_id": "news_toolkit",
"token_count": 7927
} | 937 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LoginWithEmailLinkState', () {
test('supports value comparisons', () {
expect(LoginWithEmailLinkState(), LoginWithEmailLinkState());
});
test('returns same object when no properties are passed', () {
expect(LoginWithEmailLinkState().copyWith(), LoginWithEmailLinkState());
});
test('returns object with updated status when status is passed', () {
expect(
LoginWithEmailLinkState()
.copyWith(status: LoginWithEmailLinkStatus.success),
LoginWithEmailLinkState(
status: LoginWithEmailLinkStatus.success,
),
);
});
});
}
| news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_state_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/login/bloc/login_with_email_link_state_test.dart",
"repo_id": "news_toolkit",
"token_count": 281
} | 938 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/newsletter/newsletter.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:form_inputs/form_inputs.dart';
void main() {
group('NewsletterState', () {
test('initial has correct status', () {
expect(
NewsletterState().status,
equals(NewsletterStatus.initial),
);
});
group('copyWith', () {
test(
'returns same object '
'when no properties are passed', () {
expect(
NewsletterState().copyWith(),
equals(NewsletterState()),
);
});
test(
'returns object with updated status '
'when status is passed', () {
expect(
NewsletterState().copyWith(
status: NewsletterStatus.loading,
),
equals(
NewsletterState(
status: NewsletterStatus.loading,
),
),
);
});
test(
'returns object with updated email '
'when status is passed', () {
expect(
NewsletterState().copyWith(
email: Email.dirty('email'),
),
equals(
NewsletterState(
email: Email.dirty('email'),
),
),
);
});
test(
'returns object with updated isValid '
'when status is passed', () {
expect(
NewsletterState().copyWith(
isValid: true,
),
equals(
NewsletterState(
isValid: true,
),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_state_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/newsletter/bloc/newsletter_state_test.dart",
"repo_id": "news_toolkit",
"token_count": 833
} | 939 |
import 'dart:async';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
group('SearchFilterChip', () {
testWidgets('renders chipText', (tester) async {
await tester.pumpApp(
SearchFilterChip(
chipText: 'text',
onSelected: (_) {},
),
);
expect(find.text('text'), findsOneWidget);
});
testWidgets('onSelected gets called on tap', (tester) async {
final completer = Completer<String>();
await tester.pumpApp(
SearchFilterChip(
chipText: 'text',
onSelected: completer.complete,
),
);
await tester.tap(find.byType(SearchFilterChip));
expect(completer.isCompleted, isTrue);
});
});
}
| news_toolkit/flutter_news_example/test/search/widgets/search_filter_chip_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/search/widgets/search_filter_chip_test.dart",
"repo_id": "news_toolkit",
"token_count": 363
} | 940 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news_example/theme_selector/theme_selector.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/helpers.dart';
void main() {
initMockHydratedStorage();
group('ThemeModeBloc', () {
test('initial state is ThemeMode.system', () {
expect(ThemeModeBloc().state, ThemeMode.system);
});
blocTest<ThemeModeBloc, ThemeMode>(
'on ThemeModeChanged sets the ThemeMode',
build: ThemeModeBloc.new,
act: (bloc) => bloc.add(const ThemeModeChanged(ThemeMode.dark)),
expect: () => [ThemeMode.dark],
);
test('toJson and fromJson are inverse', () {
for (final mode in ThemeMode.values) {
final bloc = ThemeModeBloc();
expect(bloc.fromJson(bloc.toJson(mode)), mode);
}
});
});
}
| news_toolkit/flutter_news_example/test/theme_selector/bloc/theme_mode_bloc_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/theme_selector/bloc/theme_mode_bloc_test.dart",
"repo_id": "news_toolkit",
"token_count": 346
} | 941 |
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug-{{flavors.name}}"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug-{{flavors.name}}"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "-FIRAnalyticsDebugEnabled"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile-{{flavors.name}}"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug-{{flavors.name}}">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release-{{flavors.name}}"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| news_toolkit/tool/generator/static/ios_flavor.xcscheme/0 | {
"file_path": "news_toolkit/tool/generator/static/ios_flavor.xcscheme",
"repo_id": "news_toolkit",
"token_count": 1350
} | 942 |
#!/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
# Set up a .desktop file pointing to the CIPD-installed Chrome.
readonly LOCAL_DESKTOP_FILE_DIR=~/.local/share/applications
mkdir -p "${LOCAL_DESKTOP_FILE_DIR}"
readonly DESKTOP_FILE_NAME=cipd-chrome.desktop
readonly CIPD_CHROME_DESKTOP_FILE="${LOCAL_DESKTOP_FILE_DIR}/${DESKTOP_FILE_NAME}"
cat << EOF > "${CIPD_CHROME_DESKTOP_FILE}"
[Desktop Entry]
Version=1.0
Name=Google Chrome
GenericName=Web Browser
Comment=Access the Internet
Exec=${CHROME_EXECUTABLE} %U
StartupNotify=true
Terminal=false
Icon=google-chrome
Type=Application
Categories=Network;WebBrowser;
MimeType=application/pdf;application/rdf+xml;application/rss+xml;application/xhtml+xml;application/xhtml_xml;application/xml;image/gif;image/jpeg;image/png;image/webp;text/html;text/xml;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/file;
EOF
# Enable xdg-* commands to work correctly.
export DESKTOP_SESSION=gnome
# Set Chrome as the default handler for http, https, and file, for url_launcher
# tests that expect handlers for those schemes.
xdg-mime default "${DESKTOP_FILE_NAME}" inode/directory
xdg-settings set default-web-browser "${DESKTOP_FILE_NAME}"
| packages/.ci/scripts/set_default_linux_apps.sh/0 | {
"file_path": "packages/.ci/scripts/set_default_linux_apps.sh",
"repo_id": "packages",
"token_count": 455
} | 943 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: custom tests
script: .ci/scripts/tool_runner.sh
args: ["custom-test"]
| packages/.ci/targets/linux_custom_package_tests.yaml/0 | {
"file_path": "packages/.ci/targets/linux_custom_package_tests.yaml",
"repo_id": "packages",
"token_count": 85
} | 944 |
#include "Generated.xcconfig"
| packages/packages/animations/example/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "packages/packages/animations/example/ios/Flutter/Debug.xcconfig",
"repo_id": "packages",
"token_count": 12
} | 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:flutter/material.dart';
import 'package:flutter/scheduler.dart';
/// Signature for `action` callback function provided to [OpenContainer.openBuilder].
///
/// Parameter `returnValue` is the value which will be provided to [OpenContainer.onClosed]
/// when `action` is called.
typedef CloseContainerActionCallback<S> = void Function({S? returnValue});
/// Signature for a function that creates a [Widget] in open state within an
/// [OpenContainer].
///
/// The `action` callback provided to [OpenContainer.openBuilder] can be used
/// to close the container.
typedef OpenContainerBuilder<S> = Widget Function(
BuildContext context,
CloseContainerActionCallback<S> action,
);
/// Signature for a function that creates a [Widget] in closed state within an
/// [OpenContainer].
///
/// The `action` callback provided to [OpenContainer.closedBuilder] can be used
/// to open the container.
typedef CloseContainerBuilder = Widget Function(
BuildContext context,
VoidCallback action,
);
/// The [OpenContainer] widget's fade transition type.
///
/// This determines the type of fade transition that the incoming and outgoing
/// contents will use.
enum ContainerTransitionType {
/// Fades the incoming element in over the outgoing element.
fade,
/// First fades the outgoing element out, and starts fading the incoming
/// element in once the outgoing element has completely faded out.
fadeThrough,
}
/// Callback function which is called when the [OpenContainer]
/// is closed.
typedef ClosedCallback<S> = void Function(S data);
/// A container that grows to fill the screen to reveal new content when tapped.
///
/// While the container is closed, it shows the [Widget] returned by
/// [closedBuilder]. When the container is tapped it grows to fill the entire
/// size of the surrounding [Navigator] while fading out the widget returned by
/// [closedBuilder] and fading in the widget returned by [openBuilder]. When the
/// container is closed again via the callback provided to [openBuilder] or via
/// Android's back button, the animation is reversed: The container shrinks back
/// to its original size while the widget returned by [openBuilder] is faded out
/// and the widget returned by [closedBuilder] is faded back in.
///
/// By default, the container is in the closed state. During the transition from
/// closed to open and vice versa the widgets returned by the [openBuilder] and
/// [closedBuilder] exist in the tree at the same time. Therefore, the widgets
/// returned by these builders cannot include the same global key.
///
/// `T` refers to the type of data returned by the route when the container
/// is closed. This value can be accessed in the `onClosed` function.
///
// TODO(goderbauer): Add example animations and sample code.
///
/// See also:
///
/// * [Transitions with animated containers](https://material.io/design/motion/choreography.html#transformation)
/// in the Material spec.
@optionalTypeArgs
class OpenContainer<T extends Object?> extends StatefulWidget {
/// Creates an [OpenContainer].
///
/// All arguments except for [key] must not be null. The arguments
/// [openBuilder] and [closedBuilder] are required.
const OpenContainer({
super.key,
this.closedColor = Colors.white,
this.openColor = Colors.white,
this.middleColor,
this.closedElevation = 1.0,
this.openElevation = 4.0,
this.closedShape = const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
this.openShape = const RoundedRectangleBorder(),
this.onClosed,
required this.closedBuilder,
required this.openBuilder,
this.tappable = true,
this.transitionDuration = const Duration(milliseconds: 300),
this.transitionType = ContainerTransitionType.fade,
this.useRootNavigator = false,
this.routeSettings,
this.clipBehavior = Clip.antiAlias,
});
/// Background color of the container while it is closed.
///
/// When the container is opened, it will first transition from this color
/// to [middleColor] and then transition from there to [openColor] in one
/// smooth animation. When the container is closed, it will transition back to
/// this color from [openColor] via [middleColor].
///
/// Defaults to [Colors.white].
///
/// See also:
///
/// * [Material.color], which is used to implement this property.
final Color closedColor;
/// Background color of the container while it is open.
///
/// When the container is closed, it will first transition from [closedColor]
/// to [middleColor] and then transition from there to this color in one
/// smooth animation. When the container is closed, it will transition back to
/// [closedColor] from this color via [middleColor].
///
/// Defaults to [Colors.white].
///
/// See also:
///
/// * [Material.color], which is used to implement this property.
final Color openColor;
/// The color to use for the background color during the transition
/// with [ContainerTransitionType.fadeThrough].
///
/// Defaults to [Theme]'s [ThemeData.canvasColor].
///
/// See also:
///
/// * [Material.color], which is used to implement this property.
final Color? middleColor;
/// Elevation of the container while it is closed.
///
/// When the container is opened, it will transition from this elevation to
/// [openElevation]. When the container is closed, it will transition back
/// from [openElevation] to this elevation.
///
/// Defaults to 1.0.
///
/// See also:
///
/// * [Material.elevation], which is used to implement this property.
final double closedElevation;
/// Elevation of the container while it is open.
///
/// When the container is opened, it will transition to this elevation from
/// [closedElevation]. When the container is closed, it will transition back
/// from this elevation to [closedElevation].
///
/// Defaults to 4.0.
///
/// See also:
///
/// * [Material.elevation], which is used to implement this property.
final double openElevation;
/// Shape of the container while it is closed.
///
/// When the container is opened it will transition from this shape to
/// [openShape]. When the container is closed, it will transition back to this
/// shape.
///
/// Defaults to a [RoundedRectangleBorder] with a [Radius.circular] of 4.0.
///
/// See also:
///
/// * [Material.shape], which is used to implement this property.
final ShapeBorder closedShape;
/// Shape of the container while it is open.
///
/// When the container is opened it will transition from [closedShape] to
/// this shape. When the container is closed, it will transition from this
/// shape back to [closedShape].
///
/// Defaults to a rectangular.
///
/// See also:
///
/// * [Material.shape], which is used to implement this property.
final ShapeBorder openShape;
/// Called when the container was popped and has returned to the closed state.
///
/// The return value from the popped screen is passed to this function as an
/// argument.
///
/// If no value is returned via [Navigator.pop] or [OpenContainer.openBuilder.action],
/// `null` will be returned by default.
final ClosedCallback<T?>? onClosed;
/// Called to obtain the child for the container in the closed state.
///
/// The [Widget] returned by this builder is faded out when the container
/// opens and at the same time the widget returned by [openBuilder] is faded
/// in while the container grows to fill the surrounding [Navigator].
///
/// The `action` callback provided to the builder can be called to open the
/// container.
final CloseContainerBuilder closedBuilder;
/// Called to obtain the child for the container in the open state.
///
/// The [Widget] returned by this builder is faded in when the container
/// opens and at the same time the widget returned by [closedBuilder] is
/// faded out while the container grows to fill the surrounding [Navigator].
///
/// The `action` callback provided to the builder can be called to close the
/// container.
final OpenContainerBuilder<T> openBuilder;
/// Whether the entire closed container can be tapped to open it.
///
/// Defaults to true.
///
/// When this is set to false the container can only be opened by calling the
/// `action` callback that is provided to the [closedBuilder].
final bool tappable;
/// The time it will take to animate the container from its closed to its
/// open state and vice versa.
///
/// Defaults to 300ms.
final Duration transitionDuration;
/// The type of fade transition that the container will use for its
/// incoming and outgoing widgets.
///
/// Defaults to [ContainerTransitionType.fade].
final ContainerTransitionType transitionType;
/// The [useRootNavigator] argument is used to determine whether to push the
/// route for [openBuilder] to the Navigator furthest from or nearest to
/// the given context.
///
/// By default, [useRootNavigator] is false and the route created will push
/// to the nearest navigator.
final bool useRootNavigator;
/// Provides additional data to the [openBuilder] route pushed by the Navigator.
final RouteSettings? routeSettings;
/// The [closedBuilder] will be clipped (or not) according to this option.
///
/// Defaults to [Clip.antiAlias], and must not be null.
///
/// See also:
///
/// * [Material.clipBehavior], which is used to implement this property.
final Clip clipBehavior;
@override
State<OpenContainer<T?>> createState() => _OpenContainerState<T>();
}
class _OpenContainerState<T> extends State<OpenContainer<T?>> {
// Key used in [_OpenContainerRoute] to hide the widget returned by
// [OpenContainer.openBuilder] in the source route while the container is
// opening/open. A copy of that widget is included in the
// [_OpenContainerRoute] where it fades out. To avoid issues with double
// shadows and transparency, we hide it in the source route.
final GlobalKey<_HideableState> _hideableKey = GlobalKey<_HideableState>();
// Key used to steal the state of the widget returned by
// [OpenContainer.openBuilder] from the source route and attach it to the
// same widget included in the [_OpenContainerRoute] where it fades out.
final GlobalKey _closedBuilderKey = GlobalKey();
Future<void> openContainer() async {
final Color middleColor =
widget.middleColor ?? Theme.of(context).canvasColor;
final T? data = await Navigator.of(
context,
rootNavigator: widget.useRootNavigator,
).push(_OpenContainerRoute<T>(
closedColor: widget.closedColor,
openColor: widget.openColor,
middleColor: middleColor,
closedElevation: widget.closedElevation,
openElevation: widget.openElevation,
closedShape: widget.closedShape,
openShape: widget.openShape,
closedBuilder: widget.closedBuilder,
openBuilder: widget.openBuilder,
hideableKey: _hideableKey,
closedBuilderKey: _closedBuilderKey,
transitionDuration: widget.transitionDuration,
transitionType: widget.transitionType,
useRootNavigator: widget.useRootNavigator,
routeSettings: widget.routeSettings,
));
if (widget.onClosed != null) {
widget.onClosed!(data);
}
}
@override
Widget build(BuildContext context) {
return _Hideable(
key: _hideableKey,
child: GestureDetector(
onTap: widget.tappable ? openContainer : null,
child: Material(
clipBehavior: widget.clipBehavior,
color: widget.closedColor,
elevation: widget.closedElevation,
shape: widget.closedShape,
child: Builder(
key: _closedBuilderKey,
builder: (BuildContext context) {
return widget.closedBuilder(context, openContainer);
},
),
),
),
);
}
}
/// Controls the visibility of its child.
///
/// The child can be in one of three states:
///
/// * It is included in the tree and fully visible. (The `placeholderSize` is
/// null and `isVisible` is true.)
/// * It is included in the tree, but not visible; its size is maintained.
/// (The `placeholderSize` is null and `isVisible` is false.)
/// * It is not included in the tree. Instead a [SizedBox] of dimensions
/// specified by `placeholderSize` is included in the tree. (The value of
/// `isVisible` is ignored).
class _Hideable extends StatefulWidget {
const _Hideable({
super.key,
required this.child,
});
final Widget child;
@override
State<_Hideable> createState() => _HideableState();
}
class _HideableState extends State<_Hideable> {
/// When non-null the child is replaced by a [SizedBox] of the set size.
Size? get placeholderSize => _placeholderSize;
Size? _placeholderSize;
set placeholderSize(Size? value) {
if (_placeholderSize == value) {
return;
}
setState(() {
_placeholderSize = value;
});
}
/// When true the child is not visible, but will maintain its size.
///
/// The value of this property is ignored when [placeholderSize] is non-null
/// (i.e. [isInTree] returns false).
bool get isVisible => _visible;
bool _visible = true;
set isVisible(bool value) {
if (_visible == value) {
return;
}
setState(() {
_visible = value;
});
}
/// Whether the child is currently included in the tree.
///
/// When it is included, it may be visible or not according to [isVisible].
bool get isInTree => _placeholderSize == null;
@override
Widget build(BuildContext context) {
if (_placeholderSize != null) {
return SizedBox.fromSize(size: _placeholderSize);
}
return Visibility(
visible: _visible,
maintainSize: true,
maintainState: true,
maintainAnimation: true,
child: widget.child,
);
}
}
class _OpenContainerRoute<T> extends ModalRoute<T> {
_OpenContainerRoute({
required this.closedColor,
required this.openColor,
required this.middleColor,
required double closedElevation,
required this.openElevation,
required ShapeBorder closedShape,
required this.openShape,
required this.closedBuilder,
required this.openBuilder,
required this.hideableKey,
required this.closedBuilderKey,
required this.transitionDuration,
required this.transitionType,
required this.useRootNavigator,
required RouteSettings? routeSettings,
}) : _elevationTween = Tween<double>(
begin: closedElevation,
end: openElevation,
),
_shapeTween = ShapeBorderTween(
begin: closedShape,
end: openShape,
),
_colorTween = _getColorTween(
transitionType: transitionType,
closedColor: closedColor,
openColor: openColor,
middleColor: middleColor,
),
_closedOpacityTween = _getClosedOpacityTween(transitionType),
_openOpacityTween = _getOpenOpacityTween(transitionType),
super(settings: routeSettings);
static _FlippableTweenSequence<Color?> _getColorTween({
required ContainerTransitionType transitionType,
required Color closedColor,
required Color openColor,
required Color middleColor,
}) {
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<Color?>(
<TweenSequenceItem<Color?>>[
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(closedColor),
weight: 1 / 5,
),
TweenSequenceItem<Color?>(
tween: ColorTween(begin: closedColor, end: openColor),
weight: 1 / 5,
),
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(openColor),
weight: 3 / 5,
),
],
);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<Color?>(
<TweenSequenceItem<Color?>>[
TweenSequenceItem<Color?>(
tween: ColorTween(begin: closedColor, end: middleColor),
weight: 1 / 5,
),
TweenSequenceItem<Color?>(
tween: ColorTween(begin: middleColor, end: openColor),
weight: 4 / 5,
),
],
);
}
}
static _FlippableTweenSequence<double> _getClosedOpacityTween(
ContainerTransitionType transitionType) {
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<double>(
<TweenSequenceItem<double>>[
TweenSequenceItem<double>(
tween: ConstantTween<double>(1.0),
weight: 1,
),
],
);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<double>(
<TweenSequenceItem<double>>[
TweenSequenceItem<double>(
tween: Tween<double>(begin: 1.0, end: 0.0),
weight: 1 / 5,
),
TweenSequenceItem<double>(
tween: ConstantTween<double>(0.0),
weight: 4 / 5,
),
],
);
}
}
static _FlippableTweenSequence<double> _getOpenOpacityTween(
ContainerTransitionType transitionType) {
switch (transitionType) {
case ContainerTransitionType.fade:
return _FlippableTweenSequence<double>(
<TweenSequenceItem<double>>[
TweenSequenceItem<double>(
tween: ConstantTween<double>(0.0),
weight: 1 / 5,
),
TweenSequenceItem<double>(
tween: Tween<double>(begin: 0.0, end: 1.0),
weight: 1 / 5,
),
TweenSequenceItem<double>(
tween: ConstantTween<double>(1.0),
weight: 3 / 5,
),
],
);
case ContainerTransitionType.fadeThrough:
return _FlippableTweenSequence<double>(
<TweenSequenceItem<double>>[
TweenSequenceItem<double>(
tween: ConstantTween<double>(0.0),
weight: 1 / 5,
),
TweenSequenceItem<double>(
tween: Tween<double>(begin: 0.0, end: 1.0),
weight: 4 / 5,
),
],
);
}
}
final Color closedColor;
final Color openColor;
final Color middleColor;
final double openElevation;
final ShapeBorder openShape;
final CloseContainerBuilder closedBuilder;
final OpenContainerBuilder<T> openBuilder;
// See [_OpenContainerState._hideableKey].
final GlobalKey<_HideableState> hideableKey;
// See [_OpenContainerState._closedBuilderKey].
final GlobalKey closedBuilderKey;
@override
final Duration transitionDuration;
final ContainerTransitionType transitionType;
final bool useRootNavigator;
final Tween<double> _elevationTween;
final ShapeBorderTween _shapeTween;
final _FlippableTweenSequence<double> _closedOpacityTween;
final _FlippableTweenSequence<double> _openOpacityTween;
final _FlippableTweenSequence<Color?> _colorTween;
static final TweenSequence<Color?> _scrimFadeInTween = TweenSequence<Color?>(
<TweenSequenceItem<Color?>>[
TweenSequenceItem<Color?>(
tween: ColorTween(begin: Colors.transparent, end: Colors.black54),
weight: 1 / 5,
),
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(Colors.black54),
weight: 4 / 5,
),
],
);
static final Tween<Color?> _scrimFadeOutTween = ColorTween(
begin: Colors.transparent,
end: Colors.black54,
);
// Key used for the widget returned by [OpenContainer.openBuilder] to keep
// its state when the shape of the widget tree is changed at the end of the
// animation to remove all the craft that was necessary to make the animation
// work.
final GlobalKey _openBuilderKey = GlobalKey();
// Defines the position and the size of the (opening) [OpenContainer] within
// the bounds of the enclosing [Navigator].
final RectTween _rectTween = RectTween();
AnimationStatus? _lastAnimationStatus;
AnimationStatus? _currentAnimationStatus;
@override
TickerFuture didPush() {
_takeMeasurements(navigatorContext: hideableKey.currentContext!);
animation!.addStatusListener((AnimationStatus status) {
_lastAnimationStatus = _currentAnimationStatus;
_currentAnimationStatus = status;
switch (status) {
case AnimationStatus.dismissed:
_toggleHideable(hide: false);
case AnimationStatus.completed:
_toggleHideable(hide: true);
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
}
});
return super.didPush();
}
@override
bool didPop(T? result) {
_takeMeasurements(
navigatorContext: subtreeContext!,
delayForSourceRoute: true,
);
return super.didPop(result);
}
@override
void dispose() {
if (hideableKey.currentState?.isVisible == false) {
// This route may be disposed without dismissing its animation if it is
// removed by the navigator.
SchedulerBinding.instance
.addPostFrameCallback((Duration d) => _toggleHideable(hide: false));
}
super.dispose();
}
void _toggleHideable({required bool hide}) {
if (hideableKey.currentState != null) {
hideableKey.currentState!
..placeholderSize = null
..isVisible = !hide;
}
}
void _takeMeasurements({
required BuildContext navigatorContext,
bool delayForSourceRoute = false,
}) {
final RenderBox navigator = Navigator.of(
navigatorContext,
rootNavigator: useRootNavigator,
).context.findRenderObject()! as RenderBox;
final Size navSize = _getSize(navigator);
_rectTween.end = Offset.zero & navSize;
void takeMeasurementsInSourceRoute([Duration? _]) {
if (!navigator.attached || hideableKey.currentContext == null) {
return;
}
_rectTween.begin = _getRect(hideableKey, navigator);
hideableKey.currentState!.placeholderSize = _rectTween.begin!.size;
}
if (delayForSourceRoute) {
SchedulerBinding.instance
.addPostFrameCallback(takeMeasurementsInSourceRoute);
} else {
takeMeasurementsInSourceRoute();
}
}
Size _getSize(RenderBox render) {
assert(render.hasSize);
return render.size;
}
// Returns the bounds of the [RenderObject] identified by `key` in the
// coordinate system of `ancestor`.
Rect _getRect(GlobalKey key, RenderBox ancestor) {
assert(key.currentContext != null);
assert(ancestor.hasSize);
final RenderBox render =
key.currentContext!.findRenderObject()! as RenderBox;
assert(render.hasSize);
return MatrixUtils.transformRect(
render.getTransformTo(ancestor),
Offset.zero & render.size,
);
}
bool get _transitionWasInterrupted {
bool wasInProgress = false;
bool isInProgress = false;
switch (_currentAnimationStatus) {
case AnimationStatus.completed:
case AnimationStatus.dismissed:
isInProgress = false;
case AnimationStatus.forward:
case AnimationStatus.reverse:
isInProgress = true;
case null:
break;
}
switch (_lastAnimationStatus) {
case AnimationStatus.completed:
case AnimationStatus.dismissed:
wasInProgress = false;
case AnimationStatus.forward:
case AnimationStatus.reverse:
wasInProgress = true;
case null:
break;
}
return wasInProgress && isInProgress;
}
void closeContainer({T? returnValue}) {
Navigator.of(subtreeContext!).pop(returnValue);
}
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return Align(
alignment: Alignment.topLeft,
child: AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
if (animation.isCompleted) {
return SizedBox.expand(
child: Material(
color: openColor,
elevation: openElevation,
shape: openShape,
child: Builder(
key: _openBuilderKey,
builder: (BuildContext context) {
return openBuilder(context, closeContainer);
},
),
),
);
}
final Animation<double> curvedAnimation = CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
reverseCurve:
_transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped,
);
TweenSequence<Color?>? colorTween;
TweenSequence<double>? closedOpacityTween, openOpacityTween;
Animatable<Color?>? scrimTween;
switch (animation.status) {
case AnimationStatus.dismissed:
case AnimationStatus.forward:
closedOpacityTween = _closedOpacityTween;
openOpacityTween = _openOpacityTween;
colorTween = _colorTween;
scrimTween = _scrimFadeInTween;
case AnimationStatus.reverse:
if (_transitionWasInterrupted) {
closedOpacityTween = _closedOpacityTween;
openOpacityTween = _openOpacityTween;
colorTween = _colorTween;
scrimTween = _scrimFadeInTween;
break;
}
closedOpacityTween = _closedOpacityTween.flipped;
openOpacityTween = _openOpacityTween.flipped;
colorTween = _colorTween.flipped;
scrimTween = _scrimFadeOutTween;
case AnimationStatus.completed:
assert(false); // Unreachable.
}
assert(colorTween != null);
assert(closedOpacityTween != null);
assert(openOpacityTween != null);
assert(scrimTween != null);
final Rect rect = _rectTween.evaluate(curvedAnimation)!;
return SizedBox.expand(
child: Container(
color: scrimTween!.evaluate(curvedAnimation),
child: Align(
alignment: Alignment.topLeft,
child: Transform.translate(
offset: Offset(rect.left, rect.top),
child: SizedBox(
width: rect.width,
height: rect.height,
child: Material(
clipBehavior: Clip.antiAlias,
animationDuration: Duration.zero,
color: colorTween!.evaluate(animation),
shape: _shapeTween.evaluate(curvedAnimation),
elevation: _elevationTween.evaluate(curvedAnimation),
child: Stack(
fit: StackFit.passthrough,
children: <Widget>[
// Closed child fading out.
FittedBox(
fit: BoxFit.fitWidth,
alignment: Alignment.topLeft,
child: SizedBox(
width: _rectTween.begin!.width,
height: _rectTween.begin!.height,
child: (hideableKey.currentState?.isInTree ??
false)
? null
: FadeTransition(
opacity: closedOpacityTween!
.animate(animation),
child: Builder(
key: closedBuilderKey,
builder: (BuildContext context) {
// Use dummy "open container" callback
// since we are in the process of opening.
return closedBuilder(context, () {});
},
),
),
),
),
// Open child fading in.
FittedBox(
fit: BoxFit.fitWidth,
alignment: Alignment.topLeft,
child: SizedBox(
width: _rectTween.end!.width,
height: _rectTween.end!.height,
child: FadeTransition(
opacity: openOpacityTween!.animate(animation),
child: Builder(
key: _openBuilderKey,
builder: (BuildContext context) {
return openBuilder(context, closeContainer);
},
),
),
),
),
],
),
),
),
),
),
),
);
},
),
);
}
@override
bool get maintainState => true;
@override
Color? get barrierColor => null;
@override
bool get opaque => true;
@override
bool get barrierDismissible => false;
@override
String? get barrierLabel => null;
}
class _FlippableTweenSequence<T> extends TweenSequence<T> {
_FlippableTweenSequence(this._items) : super(_items);
final List<TweenSequenceItem<T>> _items;
_FlippableTweenSequence<T>? _flipped;
_FlippableTweenSequence<T>? get flipped {
if (_flipped == null) {
final List<TweenSequenceItem<T>> newItems = <TweenSequenceItem<T>>[];
for (int i = 0; i < _items.length; i++) {
newItems.add(TweenSequenceItem<T>(
tween: _items[i].tween,
weight: _items[_items.length - 1 - i].weight,
));
}
_flipped = _FlippableTweenSequence<T>(newItems);
}
return _flipped;
}
}
| packages/packages/animations/lib/src/open_container.dart/0 | {
"file_path": "packages/packages/animations/lib/src/open_container.dart",
"repo_id": "packages",
"token_count": 12137
} | 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.
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:camera/camera.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';
void main() {
late Directory testDir;
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
final Directory extDir = await getTemporaryDirectory();
testDir = await Directory('${extDir.path}/test').create(recursive: true);
});
tearDownAll(() async {
await testDir.delete(recursive: true);
});
final Map<ResolutionPreset, Size> presetExpectedSizes =
<ResolutionPreset, Size>{
ResolutionPreset.low:
Platform.isAndroid ? const Size(240, 320) : const Size(288, 352),
ResolutionPreset.medium:
Platform.isAndroid ? const Size(480, 720) : const Size(480, 640),
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 least 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('Capture specific image resolutions',
(WidgetTester tester) async {
final List<CameraDescription> cameras = await 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);
assert(!(!previousPresetExactlySupported && presetExactlySupported),
'The camera took higher resolution pictures at a lower resolution.');
previousPresetExactlySupported = presetExactlySupported;
await controller.dispose();
}
}
});
// 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> testCaptureVideoResolution(
CameraController controller, ResolutionPreset preset) async {
final Size expectedSize = presetExpectedSizes[preset]!;
// Take Video
await controller.startVideoRecording();
sleep(const Duration(milliseconds: 300));
final XFile file = await controller.stopVideoRecording();
// Load video metadata
final File videoFile = File(file.path);
final VideoPlayerController videoController =
VideoPlayerController.file(videoFile);
await videoController.initialize();
final Size video = videoController.value.size;
// Verify image dimensions are as expected
expect(video, isNotNull);
return assertExpectedDimensions(
expectedSize, Size(video.height, video.width));
}
testWidgets(
'Capture specific video resolutions',
(WidgetTester tester) async {
final List<CameraDescription> cameras = await 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();
await controller.prepareForVideoRecording();
final bool presetExactlySupported =
await testCaptureVideoResolution(controller, preset.key);
assert(!(!previousPresetExactlySupported && presetExactlySupported),
'The camera took higher resolution pictures at a lower resolution.');
previousPresetExactlySupported = presetExactlySupported;
await controller.dispose();
}
}
},
// TODO(egarciad): Fix https://github.com/flutter/flutter/issues/93686.
skip: true,
);
testWidgets('Pause and resume video recording', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.isEmpty) {
return;
}
final CameraController controller = CameraController(
cameras[0],
ResolutionPreset.low,
enableAudio: false,
);
await controller.initialize();
await controller.prepareForVideoRecording();
int startPause;
int timePaused = 0;
await controller.startVideoRecording();
final int recordingStart = DateTime.now().millisecondsSinceEpoch;
sleep(const Duration(milliseconds: 500));
await controller.pauseVideoRecording();
startPause = DateTime.now().millisecondsSinceEpoch;
sleep(const Duration(milliseconds: 500));
await controller.resumeVideoRecording();
timePaused += DateTime.now().millisecondsSinceEpoch - startPause;
sleep(const Duration(milliseconds: 500));
await controller.pauseVideoRecording();
startPause = DateTime.now().millisecondsSinceEpoch;
sleep(const Duration(milliseconds: 500));
await controller.resumeVideoRecording();
timePaused += DateTime.now().millisecondsSinceEpoch - startPause;
sleep(const Duration(milliseconds: 500));
final XFile file = await controller.stopVideoRecording();
final int recordingTime =
DateTime.now().millisecondsSinceEpoch - recordingStart;
final File videoFile = File(file.path);
final VideoPlayerController videoController = VideoPlayerController.file(
videoFile,
);
await videoController.initialize();
final int duration = videoController.value.duration.inMilliseconds;
await videoController.dispose();
expect(duration, lessThan(recordingTime - timePaused));
}, skip: !Platform.isAndroid);
testWidgets(
'Android image streaming',
(WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.isEmpty) {
return;
}
final CameraController controller = CameraController(
cameras[0],
ResolutionPreset.low,
enableAudio: false,
);
await controller.initialize();
bool isDetecting = false;
await controller.startImageStream((CameraImage image) {
if (isDetecting) {
return;
}
isDetecting = true;
expectLater(image, isNotNull).whenComplete(() => isDetecting = false);
});
expect(controller.value.isStreamingImages, true);
sleep(const Duration(milliseconds: 500));
await controller.stopImageStream();
await controller.dispose();
},
skip: !Platform.isAndroid,
);
/// Start streaming with specifying the ImageFormatGroup.
Future<CameraImage> startStreaming(List<CameraDescription> cameras,
ImageFormatGroup? imageFormatGroup) async {
final CameraController controller = CameraController(
cameras.first,
ResolutionPreset.low,
enableAudio: false,
imageFormatGroup: imageFormatGroup,
);
await controller.initialize();
final Completer<CameraImage> completer = Completer<CameraImage>();
await controller.startImageStream((CameraImage image) {
if (!completer.isCompleted) {
Future<void>(() async {
await controller.stopImageStream();
await controller.dispose();
}).then((Object? value) {
completer.complete(image);
});
}
});
return completer.future;
}
testWidgets('Set description while recording', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.length < 2) {
return;
}
final CameraController controller = CameraController(
cameras[0],
ResolutionPreset.low,
enableAudio: false,
);
await controller.initialize();
await controller.prepareForVideoRecording();
await controller.startVideoRecording();
await controller.setDescription(cameras[1]);
expect(controller.description, cameras[1]);
});
testWidgets('Set description', (WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.length < 2) {
return;
}
final CameraController controller = CameraController(
cameras[0],
ResolutionPreset.low,
enableAudio: false,
);
await controller.initialize();
await controller.setDescription(cameras[1]);
expect(controller.description, cameras[1]);
});
testWidgets(
'iOS image streaming with imageFormatGroup',
(WidgetTester tester) async {
final List<CameraDescription> cameras = await availableCameras();
if (cameras.isEmpty) {
return;
}
CameraImage image = await startStreaming(cameras, null);
expect(image, isNotNull);
expect(image.format.group, ImageFormatGroup.bgra8888);
expect(image.planes.length, 1);
image = await startStreaming(cameras, ImageFormatGroup.yuv420);
expect(image, isNotNull);
expect(image.format.group, ImageFormatGroup.yuv420);
expect(image.planes.length, 2);
image = await startStreaming(cameras, ImageFormatGroup.bgra8888);
expect(image, isNotNull);
expect(image.format.group, ImageFormatGroup.bgra8888);
expect(image.planes.length, 1);
},
skip: !Platform.isIOS,
);
}
| packages/packages/camera/camera/example/integration_test/camera_test.dart/0 | {
"file_path": "packages/packages/camera/camera/example/integration_test/camera_test.dart",
"repo_id": "packages",
"token_count": 3779
} | 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:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
// TODO(stuartmorgan): Remove all of these classes in a breaking change, and
// vend the platform interface versions directly. See
// https://github.com/flutter/flutter/issues/104188
/// A single color plane of image data.
///
/// The number and meaning of the planes in an image are determined by the
/// format of the Image.
class Plane {
Plane._fromPlatformInterface(CameraImagePlane plane)
: bytes = plane.bytes,
bytesPerPixel = plane.bytesPerPixel,
bytesPerRow = plane.bytesPerRow,
height = plane.height,
width = plane.width;
// Only used by the deprecated codepath that's kept to avoid breaking changes.
// Never called by the plugin itself.
Plane._fromPlatformData(Map<dynamic, dynamic> data)
: bytes = data['bytes'] as Uint8List,
bytesPerPixel = data['bytesPerPixel'] as int?,
bytesPerRow = data['bytesPerRow'] as int,
height = data['height'] as int?,
width = data['width'] as int?;
/// Bytes representing this plane.
final Uint8List bytes;
/// The distance between adjacent pixel samples on Android, in bytes.
///
/// Will be `null` on iOS.
final int? bytesPerPixel;
/// The row stride for this color plane, in bytes.
final int bytesPerRow;
/// Height of the pixel buffer on iOS.
///
/// Will be `null` on Android
final int? height;
/// Width of the pixel buffer on iOS.
///
/// Will be `null` on Android.
final int? width;
}
/// Describes how pixels are represented in an image.
class ImageFormat {
ImageFormat._fromPlatformInterface(CameraImageFormat format)
: group = format.group,
raw = format.raw;
// Only used by the deprecated codepath that's kept to avoid breaking changes.
// Never called by the plugin itself.
ImageFormat._fromPlatformData(this.raw) : group = _asImageFormatGroup(raw);
/// Describes the format group the raw image format falls into.
final ImageFormatGroup group;
/// Raw version of the format from the Android or iOS platform.
///
/// On Android, this is an `int` from class `android.graphics.ImageFormat`. See
/// https://developer.android.com/reference/android/graphics/ImageFormat
///
/// On iOS, this is a `FourCharCode` constant from Pixel Format Identifiers.
/// See https://developer.apple.com/documentation/corevideo/1563591-pixel_format_identifiers?language=objc
final dynamic raw;
}
// Only used by the deprecated codepath that's kept to avoid breaking changes.
// Never called by the plugin itself.
ImageFormatGroup _asImageFormatGroup(dynamic rawFormat) {
if (defaultTargetPlatform == TargetPlatform.android) {
switch (rawFormat) {
// android.graphics.ImageFormat.YUV_420_888
case 35:
return ImageFormatGroup.yuv420;
// android.graphics.ImageFormat.JPEG
case 256:
return ImageFormatGroup.jpeg;
// android.graphics.ImageFormat.NV21
case 17:
return ImageFormatGroup.nv21;
}
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
switch (rawFormat) {
// kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
case 875704438:
return ImageFormatGroup.yuv420;
// kCVPixelFormatType_32BGRA
case 1111970369:
return ImageFormatGroup.bgra8888;
}
}
return ImageFormatGroup.unknown;
}
/// A single complete image buffer from the platform camera.
///
/// This class allows for direct application access to the pixel data of an
/// Image through one or more [Uint8List]. Each buffer is encapsulated in a
/// [Plane] that describes the layout of the pixel data in that plane. The
/// [CameraImage] is not directly usable as a UI resource.
///
/// Although not all image formats are planar on iOS, we treat 1-dimensional
/// images as single planar images.
class CameraImage {
/// Creates a [CameraImage] from the platform interface version.
CameraImage.fromPlatformInterface(CameraImageData data)
: format = ImageFormat._fromPlatformInterface(data.format),
height = data.height,
width = data.width,
planes = List<Plane>.unmodifiable(data.planes.map<Plane>(
(CameraImagePlane plane) => Plane._fromPlatformInterface(plane))),
lensAperture = data.lensAperture,
sensorExposureTime = data.sensorExposureTime,
sensorSensitivity = data.sensorSensitivity;
/// Creates a [CameraImage] from method channel data.
@Deprecated('Use fromPlatformInterface instead')
CameraImage.fromPlatformData(Map<dynamic, dynamic> data)
: format = ImageFormat._fromPlatformData(data['format']),
height = data['height'] as int,
width = data['width'] as int,
lensAperture = data['lensAperture'] as double?,
sensorExposureTime = data['sensorExposureTime'] as int?,
sensorSensitivity = data['sensorSensitivity'] as double?,
planes = List<Plane>.unmodifiable((data['planes'] as List<dynamic>)
.map<Plane>((dynamic planeData) =>
Plane._fromPlatformData(planeData as Map<dynamic, dynamic>)));
/// Format of the image provided.
///
/// Determines the number of planes needed to represent the image, and
/// the general layout of the pixel data in each [Uint8List].
final ImageFormat format;
/// Height of the image in pixels.
///
/// For formats where some color channels are subsampled, this is the height
/// of the largest-resolution plane.
final int height;
/// Width of the image in pixels.
///
/// For formats where some color channels are subsampled, this is the width
/// of the largest-resolution plane.
final int width;
/// The pixels planes for this image.
///
/// The number of planes is determined by the format of the image.
final List<Plane> planes;
/// The aperture settings for this image.
///
/// Represented as an f-stop value.
final double? lensAperture;
/// The sensor exposure time for this image in nanoseconds.
final int? sensorExposureTime;
/// The sensor sensitivity in standard ISO arithmetic units.
final double? sensorSensitivity;
}
| packages/packages/camera/camera/lib/src/camera_image.dart/0 | {
"file_path": "packages/packages/camera/camera/lib/src/camera_image.dart",
"repo_id": "packages",
"token_count": 1995
} | 948 |
// 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.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper;
/**
* A callback object for tracking the progress of a {@link android.hardware.camera2.CaptureRequest}
* submitted to the camera device.
*/
class CameraCaptureCallback extends CaptureCallback {
private static final String TAG = "CameraCaptureCallback";
private final CameraCaptureStateListener cameraStateListener;
private CameraState cameraState;
private final CaptureTimeoutsWrapper captureTimeouts;
private final CameraCaptureProperties captureProps;
// Lookup keys for state; overrideable for unit tests since Mockito can't mock them.
@VisibleForTesting @NonNull
CaptureResult.Key<Integer> aeStateKey = CaptureResult.CONTROL_AE_STATE;
@VisibleForTesting @NonNull
CaptureResult.Key<Integer> afStateKey = CaptureResult.CONTROL_AF_STATE;
private CameraCaptureCallback(
@NonNull CameraCaptureStateListener cameraStateListener,
@NonNull CaptureTimeoutsWrapper captureTimeouts,
@NonNull CameraCaptureProperties captureProps) {
cameraState = CameraState.STATE_PREVIEW;
this.cameraStateListener = cameraStateListener;
this.captureTimeouts = captureTimeouts;
this.captureProps = captureProps;
}
/**
* Creates a new instance of the {@link CameraCaptureCallback} class.
*
* @param cameraStateListener instance which will be called when the camera state changes.
* @param captureTimeouts specifying the different timeout counters that should be taken into
* account.
* @return a configured instance of the {@link CameraCaptureCallback} class.
*/
public static CameraCaptureCallback create(
@NonNull CameraCaptureStateListener cameraStateListener,
@NonNull CaptureTimeoutsWrapper captureTimeouts,
@NonNull CameraCaptureProperties captureProps) {
return new CameraCaptureCallback(cameraStateListener, captureTimeouts, captureProps);
}
/**
* Gets the current {@link CameraState}.
*
* @return the current {@link CameraState}.
*/
public CameraState getCameraState() {
return cameraState;
}
/**
* Sets the {@link CameraState}.
*
* @param state the camera is currently in.
*/
public void setCameraState(@NonNull CameraState state) {
cameraState = state;
}
private void process(CaptureResult result) {
Integer aeState = result.get(aeStateKey);
Integer afState = result.get(afStateKey);
// Update capture properties
if (result instanceof TotalCaptureResult) {
Float lensAperture = result.get(CaptureResult.LENS_APERTURE);
Long sensorExposureTime = result.get(CaptureResult.SENSOR_EXPOSURE_TIME);
Integer sensorSensitivity = result.get(CaptureResult.SENSOR_SENSITIVITY);
this.captureProps.setLastLensAperture(lensAperture);
this.captureProps.setLastSensorExposureTime(sensorExposureTime);
this.captureProps.setLastSensorSensitivity(sensorSensitivity);
}
if (cameraState != CameraState.STATE_PREVIEW) {
Log.d(
TAG,
"CameraCaptureCallback | state: "
+ cameraState
+ " | afState: "
+ afState
+ " | aeState: "
+ aeState);
}
switch (cameraState) {
case STATE_PREVIEW:
{
// We have nothing to do when the camera preview is working normally.
break;
}
case STATE_WAITING_FOCUS:
{
if (afState == null) {
return;
} else if (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED
|| afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
handleWaitingFocusState(aeState);
} else if (captureTimeouts.getPreCaptureFocusing().getIsExpired()) {
Log.w(TAG, "Focus timeout, moving on with capture");
handleWaitingFocusState(aeState);
}
break;
}
case STATE_WAITING_PRECAPTURE_START:
{
// CONTROL_AE_STATE can be null on some devices
if (aeState == null
|| aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED
|| aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE
|| aeState == CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED) {
setCameraState(CameraState.STATE_WAITING_PRECAPTURE_DONE);
} else if (captureTimeouts.getPreCaptureMetering().getIsExpired()) {
Log.w(TAG, "Metering timeout waiting for pre-capture to start, moving on with capture");
setCameraState(CameraState.STATE_WAITING_PRECAPTURE_DONE);
}
break;
}
case STATE_WAITING_PRECAPTURE_DONE:
{
// CONTROL_AE_STATE can be null on some devices
if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
cameraStateListener.onConverged();
} else if (captureTimeouts.getPreCaptureMetering().getIsExpired()) {
Log.w(
TAG, "Metering timeout waiting for pre-capture to finish, moving on with capture");
cameraStateListener.onConverged();
}
break;
}
}
}
private void handleWaitingFocusState(Integer aeState) {
// CONTROL_AE_STATE can be null on some devices
if (aeState == null || aeState == CaptureRequest.CONTROL_AE_STATE_CONVERGED) {
cameraStateListener.onConverged();
} else {
cameraStateListener.onPrecapture();
}
}
@Override
public void onCaptureProgressed(
@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull CaptureResult partialResult) {
process(partialResult);
}
@Override
public void onCaptureCompleted(
@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
process(result);
}
/** An interface that describes the different state changes implementers can be informed about. */
interface CameraCaptureStateListener {
/** Called when the {@link android.hardware.camera2.CaptureRequest} has been converged. */
void onConverged();
/**
* Called when the {@link android.hardware.camera2.CaptureRequest} enters the pre-capture state.
*/
void onPrecapture();
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraCaptureCallback.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraCaptureCallback.java",
"repo_id": "packages",
"token_count": 2507
} | 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.
package io.flutter.plugins.camera.features.resolution;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.hardware.camera2.CaptureRequest;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.os.Build;
import android.util.Size;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.SdkCapabilityChecker;
import io.flutter.plugins.camera.features.CameraFeature;
import java.util.List;
/**
* Controls the resolutions configuration on the {@link android.hardware.camera2} API.
*
* <p>The {@link ResolutionFeature} is responsible for converting the platform independent {@link
* ResolutionPreset} into a {@link android.media.CamcorderProfile} which contains all the properties
* required to configure the resolution using the {@link android.hardware.camera2} API.
*/
public class ResolutionFeature extends CameraFeature<ResolutionPreset> {
@Nullable private Size captureSize;
@Nullable private Size previewSize;
private CamcorderProfile recordingProfileLegacy;
private EncoderProfiles recordingProfile;
@NonNull private ResolutionPreset currentSetting;
private int cameraId;
/**
* Creates a new instance of the {@link ResolutionFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
* @param resolutionPreset Platform agnostic enum containing resolution information.
* @param cameraName Camera identifier of the camera for which to configure the resolution.
*/
public ResolutionFeature(
@NonNull CameraProperties cameraProperties,
@NonNull ResolutionPreset resolutionPreset,
@NonNull String cameraName) {
super(cameraProperties);
this.currentSetting = resolutionPreset;
try {
this.cameraId = Integer.parseInt(cameraName, 10);
} catch (NumberFormatException e) {
this.cameraId = -1;
return;
}
configureResolution(resolutionPreset, cameraId);
}
/**
* Gets the {@link android.media.CamcorderProfile} containing the information to configure the
* resolution using the {@link android.hardware.camera2} API.
*
* @return Resolution information to configure the {@link android.hardware.camera2} API.
*/
@Nullable
public CamcorderProfile getRecordingProfileLegacy() {
return this.recordingProfileLegacy;
}
@Nullable
public EncoderProfiles getRecordingProfile() {
return this.recordingProfile;
}
/**
* Gets the optimal preview size based on the configured resolution.
*
* @return The optimal preview size.
*/
@Nullable
public Size getPreviewSize() {
return this.previewSize;
}
/**
* Gets the optimal capture size based on the configured resolution.
*
* @return The optimal capture size.
*/
@Nullable
public Size getCaptureSize() {
return this.captureSize;
}
@NonNull
@Override
public String getDebugName() {
return "ResolutionFeature";
}
@SuppressLint("KotlinPropertyAccess")
@NonNull
@Override
public ResolutionPreset getValue() {
return currentSetting;
}
@Override
public void setValue(@NonNull ResolutionPreset value) {
this.currentSetting = value;
configureResolution(currentSetting, cameraId);
}
@Override
public boolean checkIsSupported() {
return cameraId >= 0;
}
@Override
public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) {
// No-op: when setting a resolution there is no need to update the request builder.
}
@VisibleForTesting
static Size computeBestPreviewSize(int cameraId, ResolutionPreset preset)
throws IndexOutOfBoundsException {
if (preset.ordinal() > ResolutionPreset.high.ordinal()) {
preset = ResolutionPreset.high;
}
if (SdkCapabilityChecker.supportsEncoderProfiles()) {
EncoderProfiles profile =
getBestAvailableCamcorderProfileForResolutionPreset(cameraId, preset);
List<EncoderProfiles.VideoProfile> videoProfiles = profile.getVideoProfiles();
EncoderProfiles.VideoProfile defaultVideoProfile = videoProfiles.get(0);
if (defaultVideoProfile != null) {
return new Size(defaultVideoProfile.getWidth(), defaultVideoProfile.getHeight());
}
}
// TODO(camsim99): Suppression is currently safe because legacy code is used as a fallback for SDK < S.
// This should be removed when reverting that fallback behavior: https://github.com/flutter/flutter/issues/119668.
CamcorderProfile profile =
getBestAvailableCamcorderProfileForResolutionPresetLegacy(cameraId, preset);
return new Size(profile.videoFrameWidth, profile.videoFrameHeight);
}
/**
* Gets the best possible {@link android.media.CamcorderProfile} for the supplied {@link
* ResolutionPreset}. Supports SDK < 31.
*
* @param cameraId Camera identifier which indicates the device's camera for which to select a
* {@link android.media.CamcorderProfile}.
* @param preset The {@link ResolutionPreset} for which is to be translated to a {@link
* android.media.CamcorderProfile}.
* @return The best possible {@link android.media.CamcorderProfile} that matches the supplied
* {@link ResolutionPreset}.
*/
@TargetApi(Build.VERSION_CODES.R)
// All of these cases deliberately fall through to get the best available profile.
@SuppressWarnings({"fallthrough", "deprecation"})
@NonNull
public static CamcorderProfile getBestAvailableCamcorderProfileForResolutionPresetLegacy(
int cameraId, @NonNull ResolutionPreset preset) {
if (cameraId < 0) {
throw new AssertionError(
"getBestAvailableCamcorderProfileForResolutionPreset can only be used with valid (>=0) camera identifiers.");
}
switch (preset) {
case max:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_HIGH)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH);
}
// fall through
case ultraHigh:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_2160P)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_2160P);
}
// fall through
case veryHigh:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_1080P)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_1080P);
}
// fall through
case high:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_720P);
}
// fall through
case medium:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_480P);
}
// fall through
case low:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_QVGA)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_QVGA);
}
// fall through
default:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_LOW)) {
return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW);
} else {
throw new IllegalArgumentException(
"No capture session available for current capture session.");
}
}
}
@TargetApi(Build.VERSION_CODES.S)
// All of these cases deliberately fall through to get the best available profile.
@SuppressWarnings("fallthrough")
@NonNull
public static EncoderProfiles getBestAvailableCamcorderProfileForResolutionPreset(
int cameraId, @NonNull ResolutionPreset preset) {
if (cameraId < 0) {
throw new AssertionError(
"getBestAvailableCamcorderProfileForResolutionPreset can only be used with valid (>=0) camera identifiers.");
}
String cameraIdString = Integer.toString(cameraId);
switch (preset) {
case max:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_HIGH)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_HIGH);
}
// fall through
case ultraHigh:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_2160P)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_2160P);
}
// fall through
case veryHigh:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_1080P)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_1080P);
}
// fall through
case high:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_720P);
}
// fall through
case medium:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_480P);
}
// fall through
case low:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_QVGA)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_QVGA);
}
// fall through
default:
if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_LOW)) {
return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_LOW);
}
throw new IllegalArgumentException(
"No capture session available for current capture session.");
}
}
private void configureResolution(ResolutionPreset resolutionPreset, int cameraId)
throws IndexOutOfBoundsException {
if (!checkIsSupported()) {
return;
}
boolean captureSizeCalculated = false;
if (SdkCapabilityChecker.supportsEncoderProfiles()) {
recordingProfileLegacy = null;
recordingProfile =
getBestAvailableCamcorderProfileForResolutionPreset(cameraId, resolutionPreset);
List<EncoderProfiles.VideoProfile> videoProfiles = recordingProfile.getVideoProfiles();
EncoderProfiles.VideoProfile defaultVideoProfile = videoProfiles.get(0);
if (defaultVideoProfile != null) {
captureSizeCalculated = true;
captureSize = new Size(defaultVideoProfile.getWidth(), defaultVideoProfile.getHeight());
}
}
if (!captureSizeCalculated) {
recordingProfile = null;
CamcorderProfile camcorderProfile =
getBestAvailableCamcorderProfileForResolutionPresetLegacy(cameraId, resolutionPreset);
recordingProfileLegacy = camcorderProfile;
captureSize =
new Size(recordingProfileLegacy.videoFrameWidth, recordingProfileLegacy.videoFrameHeight);
}
previewSize = computeBestPreviewSize(cameraId, resolutionPreset);
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java",
"repo_id": "packages",
"token_count": 3900
} | 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.
package io.flutter.plugins.camerax;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.annotation.VisibleForTesting;
import androidx.camera.camera2.interop.Camera2CameraControl;
import androidx.camera.camera2.interop.CaptureRequestOptions;
import androidx.camera.core.CameraControl;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Camera2CameraControlHostApi;
import java.util.Objects;
/**
* Host API implementation for {@link Camera2CameraControl}.
*
* <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 Camera2CameraControlHostApiImpl implements Camera2CameraControlHostApi {
private final InstanceManager instanceManager;
private final Camera2CameraControlProxy proxy;
/** Proxy for constructor and methods of {@link Camera2CameraControl}. */
@VisibleForTesting
public static class Camera2CameraControlProxy {
Context context;
/**
* Creates an instance of {@link Camera2CameraControl} derived from specified {@link
* CameraControl} instance.
*/
@OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class)
public @NonNull Camera2CameraControl create(@NonNull CameraControl cameraControl) {
return Camera2CameraControl.from(cameraControl);
}
/**
* Adds a {@link CaptureRequestOptions} to update the capture session with the options it
* contains.
*/
@OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class)
public void addCaptureRequestOptions(
@NonNull Camera2CameraControl camera2CameraControl,
@NonNull CaptureRequestOptions bundle,
@NonNull GeneratedCameraXLibrary.Result<Void> result) {
if (context == null) {
throw new IllegalStateException("Context must be set to add capture request options.");
}
ListenableFuture<Void> addCaptureRequestOptionsFuture =
camera2CameraControl.addCaptureRequestOptions(bundle);
Futures.addCallback(
addCaptureRequestOptionsFuture,
new FutureCallback<Void>() {
public void onSuccess(Void voidResult) {
result.success(null);
}
public void onFailure(Throwable t) {
result.error(t);
}
},
ContextCompat.getMainExecutor(context));
}
}
/**
* Constructs a {@link Camera2CameraControlHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param context {@link Context} used to retrieve {@code Executor}
*/
public Camera2CameraControlHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull Context context) {
this(instanceManager, new Camera2CameraControlProxy(), context);
}
/**
* Constructs a {@link Camera2CameraControlHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor and methods of {@link Camera2CameraControl}
* @param context {@link Context} used to retrieve {@code Executor}
*/
@VisibleForTesting
Camera2CameraControlHostApiImpl(
@NonNull InstanceManager instanceManager,
@NonNull Camera2CameraControlProxy proxy,
@NonNull Context context) {
this.instanceManager = instanceManager;
this.proxy = proxy;
proxy.context = context;
}
/**
* Sets the context that the {@code Camera2CameraControl} will use to listen for the result of
* setting capture request options.
*
* <p>If using the camera plugin in an add-to-app context, ensure that this is called anytime that
* the context changes.
*/
public void setContext(@NonNull Context context) {
this.proxy.context = context;
}
@Override
public void create(@NonNull Long identifier, @NonNull Long cameraControlIdentifier) {
instanceManager.addDartCreatedInstance(
proxy.create(Objects.requireNonNull(instanceManager.getInstance(cameraControlIdentifier))),
identifier);
}
@Override
public void addCaptureRequestOptions(
@NonNull Long identifier,
@NonNull Long captureRequestOptionsIdentifier,
@NonNull GeneratedCameraXLibrary.Result<Void> result) {
proxy.addCaptureRequestOptions(
getCamera2CameraControlInstance(identifier),
Objects.requireNonNull(instanceManager.getInstance(captureRequestOptionsIdentifier)),
result);
}
/**
* Retrieves the {@link Camera2CameraControl} instance associated with the specified {@code
* identifier}.
*/
private Camera2CameraControl getCamera2CameraControlInstance(@NonNull Long identifier) {
return Objects.requireNonNull(instanceManager.getInstance(identifier));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java",
"repo_id": "packages",
"token_count": 1663
} | 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.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerFlutterApi;
public class DeviceOrientationManagerFlutterApiImpl extends DeviceOrientationManagerFlutterApi {
public DeviceOrientationManagerFlutterApiImpl(@NonNull BinaryMessenger binaryMessenger) {
super(binaryMessenger);
}
public void sendDeviceOrientationChangedEvent(
@NonNull String orientation, @NonNull Reply<Void> reply) {
super.onDeviceOrientationChanged(orientation, reply);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java",
"repo_id": "packages",
"token_count": 233
} | 952 |
// 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.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.DisplayOrientedMeteringPointFactory;
import androidx.camera.core.MeteringPoint;
import androidx.camera.core.MeteringPointFactory;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointHostApi;
import java.util.Objects;
/**
* Host API implementation for {@link MeteringPoint}.
*
* <p>This class handles instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class MeteringPointHostApiImpl implements MeteringPointHostApi {
private final InstanceManager instanceManager;
private final MeteringPointProxy proxy;
/** Proxy for constructor and static methods of {@link MeteringPoint}. */
@VisibleForTesting
public static class MeteringPointProxy {
Activity activity;
/**
* Creates a surface oriented {@link MeteringPoint} with the specified x, y, and size.
*
* <p>A {@link DisplayOrientedMeteringPointFactory} is used to construct the {@link
* MeteringPoint} because this factory handles the transformation of specified coordinates based
* on camera information and the device orientation automatically.
*/
@NonNull
public MeteringPoint create(
@NonNull Double x,
@NonNull Double y,
@Nullable Double size,
@NonNull CameraInfo cameraInfo) {
Display display = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
display = activity.getDisplay();
} else {
display = getDefaultDisplayForAndroidVersionBelowR(activity);
}
DisplayOrientedMeteringPointFactory factory =
getDisplayOrientedMeteringPointFactory(display, cameraInfo, 1f, 1f);
if (size == null) {
return factory.createPoint(x.floatValue(), y.floatValue());
} else {
return factory.createPoint(x.floatValue(), y.floatValue(), size.floatValue());
}
}
@NonNull
@SuppressWarnings("deprecation")
private Display getDefaultDisplayForAndroidVersionBelowR(@NonNull Activity activity) {
return ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
}
@VisibleForTesting
@NonNull
public DisplayOrientedMeteringPointFactory getDisplayOrientedMeteringPointFactory(
@NonNull Display display, @NonNull CameraInfo cameraInfo, float width, float height) {
return new DisplayOrientedMeteringPointFactory(display, cameraInfo, width, height);
}
/**
* Returns the default point size of the {@link MeteringPoint} width and height, which is a
* normalized percentage of the sensor width/height.
*/
@NonNull
public float getDefaultPointSize() {
return MeteringPointFactory.getDefaultPointSize();
}
}
/**
* Constructs a {@link MeteringPointHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public MeteringPointHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new MeteringPointProxy());
}
/**
* Constructs a {@link MeteringPointHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor and static methods of {@link MeteringPoint}
*/
@VisibleForTesting
MeteringPointHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull MeteringPointProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
public void setActivity(@NonNull Activity activity) {
this.proxy.activity = activity;
}
@Override
public void create(
@NonNull Long identifier,
@NonNull Double x,
@NonNull Double y,
@Nullable Double size,
@NonNull Long cameraInfoId) {
MeteringPoint meteringPoint =
proxy.create(
x,
y,
size,
(CameraInfo) Objects.requireNonNull(instanceManager.getInstance(cameraInfoId)));
instanceManager.addDartCreatedInstance(meteringPoint, identifier);
}
@Override
@NonNull
public Double getDefaultPointSize() {
return (double) proxy.getDefaultPointSize();
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java",
"repo_id": "packages",
"token_count": 1540
} | 953 |
// 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.util.Size;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.resolutionselector.ResolutionStrategy;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionStrategyHostApi;
/**
* Host API implementation for {@link ResolutionStrategy}.
*
* <p>This class handles instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class ResolutionStrategyHostApiImpl implements ResolutionStrategyHostApi {
private final InstanceManager instanceManager;
private final ResolutionStrategyProxy proxy;
/** Proxy for constructor of {@link ResolutionStrategy}. */
@VisibleForTesting
public static class ResolutionStrategyProxy {
/** Creates an instance of {@link ResolutionStrategy}. */
@NonNull
public ResolutionStrategy create(@NonNull Size boundSize, @NonNull Long fallbackRule) {
return new ResolutionStrategy(boundSize, fallbackRule.intValue());
}
}
/**
* Constructs a {@link ResolutionStrategyHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public ResolutionStrategyHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new ResolutionStrategyProxy());
}
/**
* Constructs a {@link ResolutionStrategyHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor of {@link ResolutionStrategy}
*/
@VisibleForTesting
ResolutionStrategyHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull ResolutionStrategyProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
/**
* Creates a {@link ResolutionStrategy} instance with the {@link
* GeneratedCameraXLibrary.ResolutionInfo} bound size and {@code fallbackRule} if specified.
*/
@Override
public void create(
@NonNull Long identifier,
@Nullable GeneratedCameraXLibrary.ResolutionInfo boundSize,
@Nullable Long fallbackRule) {
ResolutionStrategy resolutionStrategy;
if (boundSize == null && fallbackRule == null) {
// Strategy that chooses the highest available resolution does not have a bound size or fallback rule.
resolutionStrategy = ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY;
} else if (boundSize == null) {
throw new IllegalArgumentException(
"A bound size must be specified if a non-null fallback rule is specified to create a valid ResolutionStrategy.");
} else {
resolutionStrategy =
proxy.create(
new Size(boundSize.getWidth().intValue(), boundSize.getHeight().intValue()),
fallbackRule);
}
instanceManager.addDartCreatedInstance(resolutionStrategy, identifier);
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java",
"repo_id": "packages",
"token_count": 941
} | 954 |
// 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.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraControl;
import androidx.camera.core.CameraInfo;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Objects;
import org.junit.After;
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 CameraTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public Camera camera;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void getCameraInfo_retrievesExpectedCameraInfoInstance() {
final CameraHostApiImpl cameraHostApiImpl =
new CameraHostApiImpl(mockBinaryMessenger, testInstanceManager);
final CameraInfo mockCameraInfo = mock(CameraInfo.class);
final Long cameraIdentifier = 34L;
final Long mockCameraInfoIdentifier = 97L;
testInstanceManager.addDartCreatedInstance(camera, cameraIdentifier);
testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier);
when(camera.getCameraInfo()).thenReturn(mockCameraInfo);
assertEquals(cameraHostApiImpl.getCameraInfo(cameraIdentifier), mockCameraInfoIdentifier);
verify(camera).getCameraInfo();
}
@Test
public void getCameraControl_retrievesExpectedCameraControlInstance() {
final CameraHostApiImpl cameraHostApiImpl =
new CameraHostApiImpl(mockBinaryMessenger, testInstanceManager);
final CameraControl mockCameraControl = mock(CameraControl.class);
final Long cameraIdentifier = 43L;
final Long mockCameraControlIdentifier = 79L;
testInstanceManager.addDartCreatedInstance(camera, cameraIdentifier);
testInstanceManager.addDartCreatedInstance(mockCameraControl, mockCameraControlIdentifier);
when(camera.getCameraControl()).thenReturn(mockCameraControl);
assertEquals(cameraHostApiImpl.getCameraControl(cameraIdentifier), mockCameraControlIdentifier);
verify(camera).getCameraControl();
}
@Test
public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() {
final CameraFlutterApiImpl spyFlutterApi =
spy(new CameraFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
spyFlutterApi.create(camera, reply -> {});
final long identifier =
Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(camera));
verify(spyFlutterApi).create(eq(identifier), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java",
"repo_id": "packages",
"token_count": 1017
} | 955 |
// 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.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.camera.video.PendingRecording;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoRecordEvent;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Objects;
import java.util.concurrent.Executor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class PendingRecordingTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public PendingRecording mockPendingRecording;
@Mock public Recording mockRecording;
@Mock public RecordingFlutterApiImpl mockRecordingFlutterApi;
@Mock public Context mockContext;
@Mock public SystemServicesFlutterApiImpl mockSystemServicesFlutterApi;
@Mock public VideoRecordEvent.Finalize event;
@Mock public Throwable throwable;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = spy(InstanceManager.create(identifier -> {}));
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void testStart() {
final Long mockPendingRecordingId = 3L;
final Long mockRecordingId = testInstanceManager.addHostCreatedInstance(mockRecording);
testInstanceManager.addDartCreatedInstance(mockPendingRecording, mockPendingRecordingId);
doReturn(mockRecording).when(mockPendingRecording).start(any(), any());
doNothing().when(mockRecordingFlutterApi).create(any(Recording.class), any());
PendingRecordingHostApiImpl spy =
spy(new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext));
doReturn(mock(Executor.class)).when(spy).getExecutor();
spy.recordingFlutterApi = mockRecordingFlutterApi;
assertEquals(spy.start(mockPendingRecordingId), mockRecordingId);
verify(mockRecordingFlutterApi).create(eq(mockRecording), any());
testInstanceManager.remove(mockPendingRecordingId);
testInstanceManager.remove(mockRecordingId);
}
@Test
public void testHandleVideoRecordEventSendsError() {
PendingRecordingHostApiImpl pendingRecordingHostApi =
new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext);
pendingRecordingHostApi.systemServicesFlutterApi = mockSystemServicesFlutterApi;
final String eventMessage = "example failure message";
when(event.hasError()).thenReturn(true);
when(event.getCause()).thenReturn(throwable);
when(throwable.toString()).thenReturn(eventMessage);
doNothing().when(mockSystemServicesFlutterApi).sendCameraError(any(), any());
pendingRecordingHostApi.handleVideoRecordEvent(event);
verify(mockSystemServicesFlutterApi).sendCameraError(eq(eventMessage), any());
}
@Test
public void flutterApiCreateTest() {
final PendingRecordingFlutterApiImpl spyPendingRecordingFlutterApi =
spy(new PendingRecordingFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
spyPendingRecordingFlutterApi.create(mockPendingRecording, reply -> {});
final long identifier =
Objects.requireNonNull(
testInstanceManager.getIdentifierForStrongReference(mockPendingRecording));
verify(spyPendingRecordingFlutterApi).create(eq(identifier), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java",
"repo_id": "packages",
"token_count": 1361
} | 956 |
buildscript {
// This version should intentionally be a 1.7.* version and lower than the
// version of kotlin-bom defined in packages/camera/camera_android_camerax/android/build.gradle.
// This tests that the kotlin version resolution continues to work.
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
// See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info.
def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY'
if (System.getenv().containsKey(artifactRepoKey)) {
println "Using artifact hub"
maven { url System.getenv(artifactRepoKey) }
}
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
// Build the plugin project with warnings enabled. This is here rather than
// in the plugin itself to avoid breaking clients that have different
// warnings (e.g., deprecation warnings from a newer SDK than this project
// builds with).
gradle.projectsEvaluated {
project(":camera_android_camerax") {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:all" << "-Werror"
}
}
}
| packages/packages/camera/camera_android_camerax/example/android/build.gradle/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/example/android/build.gradle",
"repo_id": "packages",
"token_count": 630
} | 957 |
// 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 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// The aspect ratio of a UseCase.
///
/// Aspect ratio is the ratio of width to height.
///
/// See https://developer.android.com/reference/androidx/camera/core/AspectRatio.
class AspectRatio {
AspectRatio._();
/// 4:3 standard aspect ratio.
///
/// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_4_3().
static const int ratio4To3 = 0;
/// 16:9 standard aspect ratio.
///
/// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_16_9().
static const int ratio16To9 = 1;
/// The aspect ratio representing no preference for aspect ratio.
///
/// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_DEFAULT().
static const int ratioDefault = -1;
}
/// The aspect ratio strategy defines the sequence of aspect ratios that are
/// used to select the best size for a particular image.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy.
@immutable
class AspectRatioStrategy extends JavaObject {
/// Construct a [AspectRatioStrategy].
AspectRatioStrategy({
required this.preferredAspectRatio,
required this.fallbackRule,
super.binaryMessenger,
super.instanceManager,
}) : _api = _AspectRatioStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached() {
_api.createFromInstances(this, preferredAspectRatio, fallbackRule);
}
/// Instantiates a [AspectRatioStrategy] without creating and attaching to an
/// instance of the associated native class.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an [InstanceManager].
AspectRatioStrategy.detached({
required this.preferredAspectRatio,
required this.fallbackRule,
super.binaryMessenger,
super.instanceManager,
}) : _api = _AspectRatioStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached();
/// CameraX doesn't fall back to select sizes of any other aspect ratio when
/// this fallback rule is used.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_NONE().
static const int fallbackRuleNone = 0;
/// CameraX automatically chooses the next best aspect ratio which contains
/// the closest field of view (FOV) of the camera sensor, from the remaining
/// options.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_AUTO().
static const int fallbackRuleAuto = 1;
final _AspectRatioStrategyHostApiImpl _api;
/// The preferred aspect ratio captured by the camera.
final int preferredAspectRatio;
/// The specified fallback rule for choosing the aspect ratio when the
/// preferred aspect ratio is not available.
final int fallbackRule;
}
/// Host API implementation of [AspectRatioStrategy].
class _AspectRatioStrategyHostApiImpl extends AspectRatioStrategyHostApi {
/// Constructs an [_AspectRatioStrategyHostApiImpl].
///
/// 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].
_AspectRatioStrategyHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
/// Creates a [AspectRatioStrategy] on the native side with the preferred
/// aspect ratio and fallback rule specified.
Future<void> createFromInstances(
AspectRatioStrategy instance,
int preferredAspectRatio,
int fallbackRule,
) {
return create(
instanceManager.addDartCreatedInstance(
instance,
onCopy: (AspectRatioStrategy original) => AspectRatioStrategy.detached(
preferredAspectRatio: original.preferredAspectRatio,
fallbackRule: original.fallbackRule,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
),
preferredAspectRatio,
fallbackRule,
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart",
"repo_id": "packages",
"token_count": 1598
} | 958 |
// 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 'analyzer.dart';
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'resolution_selector.dart';
import 'use_case.dart';
/// Use case for providing CPU accessible images for performing image analysis.
///
/// See https://developer.android.com/reference/androidx/camera/core/ImageAnalysis.
@immutable
class ImageAnalysis extends UseCase {
/// Creates an [ImageAnalysis].
ImageAnalysis(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.initialTargetRotation,
this.resolutionSelector})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _ImageAnalysisHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstances(this, initialTargetRotation, resolutionSelector);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
/// Constructs an [ImageAnalysis] that is not automatically attached to a
/// native object.
ImageAnalysis.detached(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.initialTargetRotation,
this.resolutionSelector})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _ImageAnalysisHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final _ImageAnalysisHostApiImpl _api;
/// Initial target rotation of the camera used for the preview stream.
///
/// Should be specified in terms of one of the [Surface]
/// rotation constants that represents the counter-clockwise degrees of
/// rotation relative to [DeviceOrientation.portraitUp].
// TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664
final int? initialTargetRotation;
/// Target resolution of the camera preview stream.
///
/// If not set, this [UseCase] will default to the behavior described in:
/// https://developer.android.com/reference/androidx/camera/core/ImageAnalysis.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector).
final ResolutionSelector? resolutionSelector;
/// 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);
/// Sets an [Analyzer] to receive and analyze images.
Future<void> setAnalyzer(Analyzer analyzer) =>
_api.setAnalyzerFromInstances(this, analyzer);
/// Removes a previously set [Analyzer].
Future<void> clearAnalyzer() => _api.clearAnalyzerFromInstances(this);
}
/// Host API implementation of [ImageAnalysis].
class _ImageAnalysisHostApiImpl extends ImageAnalysisHostApi {
/// Constructor for [_ImageAnalysisHostApiImpl].
///
/// 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].
_ImageAnalysisHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
final BinaryMessenger? binaryMessenger;
final InstanceManager instanceManager;
/// Creates an [ImageAnalysis] instance with the specified target resolution
/// on the native side.
Future<void> createFromInstances(
ImageAnalysis instance,
int? targetRotation,
ResolutionSelector? resolutionSelector,
) {
return create(
instanceManager.addDartCreatedInstance(
instance,
onCopy: (ImageAnalysis original) => ImageAnalysis.detached(
initialTargetRotation: original.initialTargetRotation,
resolutionSelector: original.resolutionSelector,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
),
targetRotation,
resolutionSelector == null
? null
: instanceManager.getIdentifier(resolutionSelector),
);
}
/// Dynamically sets the target rotation of [instance] to [rotation].
Future<void> setTargetRotationFromInstances(
ImageAnalysis instance, int rotation) {
return setTargetRotation(
instanceManager.getIdentifier(instance)!, rotation);
}
/// Sets the [analyzer] to receive and analyze images on the [instance].
Future<void> setAnalyzerFromInstances(
ImageAnalysis instance,
Analyzer analyzer,
) {
return setAnalyzer(
instanceManager.getIdentifier(instance)!,
instanceManager.getIdentifier(analyzer)!,
);
}
/// Removes a previously set analyzer from the [instance].
Future<void> clearAnalyzerFromInstances(
ImageAnalysis instance,
) {
return clearAnalyzer(
instanceManager.getIdentifier(instance)!,
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/image_analysis.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/image_analysis.dart",
"repo_id": "packages",
"token_count": 1784
} | 959 |
// 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 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// The resolution strategy defines the resolution selection sequence to select
/// the best size.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy.
@immutable
class ResolutionStrategy extends JavaObject {
/// Constructs a [ResolutionStrategy].
ResolutionStrategy({
required Size this.boundSize,
this.fallbackRule,
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached() {
_api.createFromInstances(this, boundSize, fallbackRule);
}
/// Constructs a [ResolutionStrategy] that represents the strategy that
/// chooses the highest available resolution.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#HIGHEST_AVAILABLE_STRATEGY().
ResolutionStrategy.highestAvailableStrategy({
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
boundSize = null,
fallbackRule = null,
super.detached() {
_api.createFromInstances(this, boundSize, fallbackRule);
}
/// Instantiates a [ResolutionStrategy] without creating and attaching to an
/// instance of the associated native class.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an [InstanceManager].
ResolutionStrategy.detached({
required this.boundSize,
this.fallbackRule,
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
super.detached();
/// Instantiates a [ResolutionStrategy] that represents the strategy that
/// chooses the highest available resolution without creating and attaching to
/// an instance of the associated native class.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an [InstanceManager].
ResolutionStrategy.detachedHighestAvailableStrategy({
super.binaryMessenger,
super.instanceManager,
}) : _api = _ResolutionStrategyHostApiImpl(
instanceManager: instanceManager,
binaryMessenger: binaryMessenger,
),
boundSize = null,
fallbackRule = null,
super.detached();
/// CameraX doesn't select an alternate size when the specified bound size is
/// unavailable.
///
/// Applications will receive [PlatformException] when binding the [UseCase]s
/// with this fallback rule if the device doesn't support the specified bound
/// size.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_NONE().
static const int fallbackRuleNone = 0;
/// When the specified bound size is unavailable, CameraX falls back to select
/// the closest higher resolution size.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER().
static const int fallbackRuleClosestHigherThenLower = 1;
/// When the specified bound size is unavailable, CameraX falls back to the
/// closest higher resolution size.
///
/// If CameraX still cannot find any available resolution, it will fallback to
/// select other lower resolutions.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_HIGHER().
static const int fallbackRuleClosestHigher = 2;
/// When the specified bound size is unavailable, CameraX falls back to select
/// the closest lower resolution size.
///
/// If CameraX still cannot find any available resolution, it will fallback to
/// select other higher resolutions.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER().
static const int fallbackRuleClosestLowerThenHigher = 3;
/// When the specified bound size is unavailable, CameraX falls back to the
/// closest lower resolution size.
///
/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_LOWER().
static const int fallbackRuleClosestLower = 4;
final _ResolutionStrategyHostApiImpl _api;
/// The specified bound size for the desired resolution of the camera.
///
/// If left null, [fallbackRule] must also be left null in order to create a
/// valid [ResolutionStrategy]. This will create the [ResolutionStrategy]
/// that chooses the highest available resolution, which can also be retrieved
/// by calling [getHighestAvailableStrategy].
final Size? boundSize;
/// The fallback rule for choosing an alternate size when the specified bound
/// size is unavailable.
///
/// Must be left null if [boundSize] is specified as null. This will create
/// the [ResolutionStrategy] that chooses the highest available resolution,
/// which can also be retrieved by calling [getHighestAvailableStrategy].
final int? fallbackRule;
}
/// Host API implementation of [ResolutionStrategy].
class _ResolutionStrategyHostApiImpl extends ResolutionStrategyHostApi {
/// Constructs an [_ResolutionStrategyHostApiImpl].
///
/// 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].
_ResolutionStrategyHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
/// Creates a [ResolutionStrategy] on the native side with the bound [Size]
/// and fallback rule, if specified.
Future<void> createFromInstances(
ResolutionStrategy instance,
Size? boundSize,
int? fallbackRule,
) {
return create(
instanceManager.addDartCreatedInstance(
instance,
onCopy: (ResolutionStrategy original) => ResolutionStrategy.detached(
boundSize: original.boundSize,
fallbackRule: original.fallbackRule,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
),
boundSize == null
? null
: ResolutionInfo(
width: boundSize.width.toInt(),
height: boundSize.height.toInt(),
),
fallbackRule,
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart",
"repo_id": "packages",
"token_count": 2304
} | 960 |
// 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/camera_control.dart';
import 'package:camera_android_camerax/src/focus_metering_action.dart';
import 'package:camera_android_camerax/src/focus_metering_result.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'camera_control_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
TestCameraControlHostApi,
TestInstanceManagerHostApi,
FocusMeteringAction
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('CameraControl', () {
tearDown(() => TestCameraHostApi.setup(null));
test('enableTorch makes call on Java side to enable torch', () async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 22;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
const bool enableTorch = true;
await cameraControl.enableTorch(enableTorch);
verify(mockApi.enableTorch(cameraControlIdentifier, enableTorch));
});
test('setZoomRatio makes call on Java side to set zoom ratio', () async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 45;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
const double zoom = 0.2;
await cameraControl.setZoomRatio(zoom);
verify(mockApi.setZoomRatio(cameraControlIdentifier, zoom));
});
test(
'startFocusAndMetering makes call on Java side to start focus and metering and returns expected result',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 75;
final FocusMeteringAction action = MockFocusMeteringAction();
const int actionId = 5;
final FocusMeteringResult result =
FocusMeteringResult.detached(instanceManager: instanceManager);
const int resultId = 2;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
instanceManager.addHostCreatedInstance(
action,
actionId,
onCopy: (_) => MockFocusMeteringAction(),
);
instanceManager.addHostCreatedInstance(
result,
resultId,
onCopy: (_) =>
FocusMeteringResult.detached(instanceManager: instanceManager),
);
when(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId))
.thenAnswer((_) => Future<int>.value(resultId));
expect(await cameraControl.startFocusAndMetering(action), equals(result));
verify(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId));
});
test('startFocusAndMetering returns null result if operation was canceled',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 75;
final FocusMeteringAction action = MockFocusMeteringAction();
const int actionId = 5;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
instanceManager.addHostCreatedInstance(
action,
actionId,
onCopy: (_) => MockFocusMeteringAction(),
);
when(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId))
.thenAnswer((_) => Future<int?>.value());
expect(await cameraControl.startFocusAndMetering(action), isNull);
verify(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId));
});
test(
'cancelFocusAndMetering makes call on Java side to cancel focus and metering',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 45;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
await cameraControl.cancelFocusAndMetering();
verify(mockApi.cancelFocusAndMetering(cameraControlIdentifier));
});
test(
'setExposureCompensationIndex makes call on Java side to set index and returns expected target exposure value',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 40;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
const int index = 3;
const int fakeTargetExposureValue = 2;
when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index))
.thenAnswer((_) => Future<int>.value(fakeTargetExposureValue));
expect(await cameraControl.setExposureCompensationIndex(index),
equals(fakeTargetExposureValue));
verify(
mockApi.setExposureCompensationIndex(cameraControlIdentifier, index));
});
test(
'setExposureCompensationIndex returns null when operation was canceled',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 40;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
const int index = 2;
when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index))
.thenAnswer((_) => Future<int?>.value());
expect(await cameraControl.setExposureCompensationIndex(index), isNull);
verify(
mockApi.setExposureCompensationIndex(cameraControlIdentifier, index));
});
test(
'setExposureCompensationIndex throws PlatformException when one is thrown from native side',
() async {
final MockTestCameraControlHostApi mockApi =
MockTestCameraControlHostApi();
TestCameraControlHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControl cameraControl = CameraControl.detached(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 40;
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
const int index = 1;
when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index))
.thenThrow(PlatformException(
code: 'TEST_ERROR',
details: 'Platform exception thrown from Java side.'));
expect(() => cameraControl.setExposureCompensationIndex(index),
throwsA(isA<PlatformException>()));
verify(
mockApi.setExposureCompensationIndex(cameraControlIdentifier, index));
});
test('flutterApiCreate makes call to add instance to instance manager', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraControlFlutterApiImpl flutterApi =
CameraControlFlutterApiImpl(
instanceManager: instanceManager,
);
const int cameraControlIdentifier = 67;
flutterApi.create(cameraControlIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(cameraControlIdentifier),
isA<CameraControl>());
});
});
}
| packages/packages/camera/camera_android_camerax/test/camera_control_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/camera_control_test.dart",
"repo_id": "packages",
"token_count": 3826
} | 961 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/live_data_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3;
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 [TestLiveDataHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestLiveDataHostApi extends _i1.Mock
implements _i2.TestLiveDataHostApi {
MockTestLiveDataHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void observe(
int? identifier,
int? observerIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#observe,
[
identifier,
observerIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void removeObservers(int? identifier) => super.noSuchMethod(
Invocation.method(
#removeObservers,
[identifier],
),
returnValueForMissingStub: null,
);
@override
int? getValue(
int? identifier,
_i3.LiveDataSupportedTypeData? type,
) =>
(super.noSuchMethod(Invocation.method(
#getValue,
[
identifier,
type,
],
)) as int?);
}
/// 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/live_data_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart",
"repo_id": "packages",
"token_count": 985
} | 962 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/recorder_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i7;
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2;
import 'package:camera_android_camerax/src/pending_recording.dart' as _i6;
import 'package:camera_android_camerax/src/quality_selector.dart' as _i4;
import 'package:camera_android_camerax/src/recording.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i5;
// 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
class _FakeResolutionInfo_0 extends _i1.SmartFake
implements _i2.ResolutionInfo {
_FakeResolutionInfo_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeRecording_1 extends _i1.SmartFake implements _i3.Recording {
_FakeRecording_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [QualitySelector].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockQualitySelector extends _i1.Mock implements _i4.QualitySelector {
MockQualitySelector() {
_i1.throwOnMissingStub(this);
}
@override
List<_i2.VideoQualityData> get qualityList => (super.noSuchMethod(
Invocation.getter(#qualityList),
returnValue: <_i2.VideoQualityData>[],
) as List<_i2.VideoQualityData>);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i5.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestFallbackStrategyHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestFallbackStrategyHostApi extends _i1.Mock
implements _i5.TestFallbackStrategyHostApi {
MockTestFallbackStrategyHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
_i2.VideoQuality? quality,
_i2.VideoResolutionFallbackRule? fallbackRule,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
quality,
fallbackRule,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestRecorderHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestRecorderHostApi extends _i1.Mock
implements _i5.TestRecorderHostApi {
MockTestRecorderHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? aspectRatio,
int? bitRate,
int? qualitySelectorId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
aspectRatio,
bitRate,
qualitySelectorId,
],
),
returnValueForMissingStub: null,
);
@override
int getAspectRatio(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getAspectRatio,
[identifier],
),
returnValue: 0,
) as int);
@override
int getTargetVideoEncodingBitRate(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getTargetVideoEncodingBitRate,
[identifier],
),
returnValue: 0,
) as int);
@override
int prepareRecording(
int? identifier,
String? path,
) =>
(super.noSuchMethod(
Invocation.method(
#prepareRecording,
[
identifier,
path,
],
),
returnValue: 0,
) as int);
}
/// A class which mocks [TestQualitySelectorHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestQualitySelectorHostApi extends _i1.Mock
implements _i5.TestQualitySelectorHostApi {
MockTestQualitySelectorHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
List<_i2.VideoQualityData?>? videoQualityDataList,
int? fallbackStrategyId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
videoQualityDataList,
fallbackStrategyId,
],
),
returnValueForMissingStub: null,
);
@override
_i2.ResolutionInfo getResolution(
int? cameraInfoId,
_i2.VideoQuality? quality,
) =>
(super.noSuchMethod(
Invocation.method(
#getResolution,
[
cameraInfoId,
quality,
],
),
returnValue: _FakeResolutionInfo_0(
this,
Invocation.method(
#getResolution,
[
cameraInfoId,
quality,
],
),
),
) as _i2.ResolutionInfo);
}
/// A class which mocks [PendingRecording].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockPendingRecording extends _i1.Mock implements _i6.PendingRecording {
MockPendingRecording() {
_i1.throwOnMissingStub(this);
}
@override
_i7.Future<_i3.Recording> start() => (super.noSuchMethod(
Invocation.method(
#start,
[],
),
returnValue: _i7.Future<_i3.Recording>.value(_FakeRecording_1(
this,
Invocation.method(
#start,
[],
),
)),
) as _i7.Future<_i3.Recording>);
}
| packages/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart",
"repo_id": "packages",
"token_count": 2846
} | 963 |
// 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;
NS_ASSUME_NONNULL_BEGIN
/// Creates an `FLTCam` that runs its capture session operations on a given queue.
/// @param captureSessionQueue the capture session queue
/// @return an FLTCam object.
extern FLTCam *FLTCreateCamWithCaptureSessionQueue(dispatch_queue_t captureSessionQueue);
/// Creates an `FLTCam` with a given captureSession and resolutionPreset
/// @param captureSession AVCaptureSession for video
/// @param resolutionPreset preset for camera's captureSession resolution
/// @return an FLTCam object.
extern FLTCam *FLTCreateCamWithVideoCaptureSession(AVCaptureSession *captureSession,
NSString *resolutionPreset);
/// Creates an `FLTCam` with a given captureSession and resolutionPreset.
/// Allows to inject a capture device and a block to compute the video dimensions.
/// @param captureSession AVCaptureSession for video
/// @param resolutionPreset preset for camera's captureSession resolution
/// @param captureDevice AVCaptureDevice to be used
/// @param videoDimensionsForFormat custom code to determine video dimensions
/// @return an FLTCam object.
extern FLTCam *FLTCreateCamWithVideoDimensionsForFormat(
AVCaptureSession *captureSession, NSString *resolutionPreset, AVCaptureDevice *captureDevice,
VideoDimensionsForFormat videoDimensionsForFormat);
/// Creates a test sample buffer.
/// @return a test sample buffer.
extern CMSampleBufferRef FLTCreateTestSampleBuffer(void);
/// Creates a test audio sample buffer.
/// @return a test audio sample buffer.
extern CMSampleBufferRef FLTCreateTestAudioSampleBuffer(void);
NS_ASSUME_NONNULL_END
| packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.h/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.h",
"repo_id": "packages",
"token_count": 519
} | 964 |
name: camera_platform_interface
description: A common platform interface for the camera plugin.
repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 2.7.4
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
cross_file: ^0.3.1
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.7
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
topics:
- camera
| packages/packages/camera/camera_platform_interface/pubspec.yaml/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/pubspec.yaml",
"repo_id": "packages",
"token_count": 275
} | 965 |
// 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:typed_data';
import 'package:meta/meta.dart';
import './base.dart';
// ignore_for_file: avoid_unused_constructor_parameters
/// A CrossFile is a cross-platform, simplified File abstraction.
///
/// It wraps the bytes of a selected file, and its (platform-dependant) path.
class XFile extends XFileBase {
/// Construct a CrossFile object from its path.
///
/// Optionally, this can be initialized with `bytes` and `length`
/// so no http requests are performed to retrieve data later.
///
/// `name` may be passed from the outside, for those cases where the effective
/// `path` of the file doesn't match what the user sees when selecting it
/// (like in web)
XFile(
String super.path, {
String? mimeType,
String? name,
int? length,
Uint8List? bytes,
DateTime? lastModified,
@visibleForTesting CrossFileTestOverrides? overrides,
}) {
throw UnimplementedError(
'CrossFile is not available in your current platform.');
}
/// Construct a CrossFile object from its data
XFile.fromData(
Uint8List bytes, {
String? mimeType,
String? name,
int? length,
DateTime? lastModified,
String? path,
@visibleForTesting CrossFileTestOverrides? overrides,
}) : super(path) {
throw UnimplementedError(
'CrossFile is not available in your current platform.');
}
}
/// Overrides some functions of CrossFile for testing purposes
@visibleForTesting
class CrossFileTestOverrides {
/// Default constructor for overrides
CrossFileTestOverrides({required this.createAnchorElement});
/// For overriding the creation of the file input element.
dynamic Function(String href, String suggestedName) createAnchorElement;
}
| packages/packages/cross_file/lib/src/types/interface.dart/0 | {
"file_path": "packages/packages/cross_file/lib/src/types/interface.dart",
"repo_id": "packages",
"token_count": 582
} | 966 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/dynamic_layouts/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "packages/packages/dynamic_layouts/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 967 |
// 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 androidx.test.espresso.flutter.action;
import static com.google.common.base.Preconditions.checkNotNull;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import androidx.test.espresso.action.CoordinatesProvider;
import java.util.Arrays;
/** Provides coordinates of a Flutter widget. */
final class WidgetCoordinatesCalculator implements CoordinatesProvider {
private static final String TAG = WidgetCoordinatesCalculator.class.getSimpleName();
private final Rect widgetRectInDp;
/**
* Constructs with the local (as relative to the outer Flutter view) coordinates of a Flutter
* widget in the unit of dp.
*
* @param widgetRectInDp the local widget coordinates in dp.
*/
public WidgetCoordinatesCalculator(Rect widgetRectInDp) {
this.widgetRectInDp = checkNotNull(widgetRectInDp);
}
@Override
public float[] calculateCoordinates(View flutterView) {
int deviceDensityDpi = flutterView.getContext().getResources().getDisplayMetrics().densityDpi;
Rect widgetRectInPixel = convertDpToPixel(widgetRectInDp, deviceDensityDpi);
float widgetCenterX = (widgetRectInPixel.left + widgetRectInPixel.right) / 2;
float widgetCenterY = (widgetRectInPixel.top + widgetRectInPixel.bottom) / 2;
int[] viewCords = new int[] {0, 0};
flutterView.getLocationOnScreen(viewCords);
float[] coords = new float[] {viewCords[0] + widgetCenterX, viewCords[1] + widgetCenterY};
Log.d(
TAG,
String.format(
"Clicks on widget[%s] on Flutter View[%d, %d][width:%d, height:%d] at coordinates"
+ " [%s] on screen",
widgetRectInPixel,
viewCords[0],
viewCords[1],
flutterView.getWidth(),
flutterView.getHeight(),
Arrays.toString(coords)));
return coords;
}
private static Rect convertDpToPixel(Rect rectInDp, int densityDpi) {
checkNotNull(rectInDp);
int left = (int) convertDpToPixel(rectInDp.left, densityDpi);
int top = (int) convertDpToPixel(rectInDp.top, densityDpi);
int right = (int) convertDpToPixel(rectInDp.right, densityDpi);
int bottom = (int) convertDpToPixel(rectInDp.bottom, densityDpi);
return new Rect(left, top, right, bottom);
}
private static float convertDpToPixel(float dp, int densityDpi) {
return dp * ((float) densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WidgetCoordinatesCalculator.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/WidgetCoordinatesCalculator.java",
"repo_id": "packages",
"token_count": 953
} | 968 |
// 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 androidx.test.espresso.flutter.internal.idgenerator;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
/** Generates unique IDs of the parameterized type. */
public interface IdGenerator<T> {
/**
* Returns a new, unique ID.
*
* @throws IdException if there were any errors in getting an ID.
*/
@CanIgnoreReturnValue
T next();
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerator.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/idgenerator/IdGenerator.java",
"repo_id": "packages",
"token_count": 160
} | 969 |
// 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 androidx.test.espresso.flutter.internal.protocol.impl;
/** Represents a condition that waits until no transient callbacks in the Flutter framework. */
class NoTransientCallbacksCondition extends WaitCondition {
public NoTransientCallbacksCondition() {
super("NoTransientCallbacksCondition");
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/NoTransientCallbacksCondition.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/NoTransientCallbacksCondition.java",
"repo_id": "packages",
"token_count": 124
} | 970 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/espresso/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/espresso/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 971 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/extension_google_sign_in_as_googleapis_auth/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 972 |
name: extension_google_sign_in_example
description: Example of Google Sign-In plugin and googleapis.
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
extension_google_sign_in_as_googleapis_auth:
# When depending on this package from a real application you should use:
# extension_google_sign_in_as_googleapis_auth: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
flutter:
sdk: flutter
google_sign_in: ^6.0.0
googleapis: ^10.1.0
googleapis_auth: ^1.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 293
} | 973 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/file_selector/file_selector/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/file_selector/file_selector/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 974 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/file_selector_api.g.dart',
javaOut:
'android/src/main/java/dev/flutter/packages/file_selector_android/GeneratedFileSelectorApi.java',
javaOptions: JavaOptions(
package: 'dev.flutter.packages.file_selector_android',
className: 'GeneratedFileSelectorApi',
),
copyrightHeader: 'pigeons/copyright.txt',
),
)
class FileResponse {
late final String path;
late final String? mimeType;
late final String? name;
late final int size;
late final Uint8List bytes;
}
class FileTypes {
late List<String?> mimeTypes;
late List<String?> extensions;
}
/// An API to call to native code to select files or directories.
@HostApi()
abstract class FileSelectorApi {
/// Opens a file dialog for loading files and returns a file path.
///
/// Returns `null` if user cancels the operation.
@async
FileResponse? openFile(String? initialDirectory, FileTypes allowedTypes);
/// Opens a file dialog for loading files and returns a list of file responses
/// chosen by the user.
@async
List<FileResponse?> openFiles(
String? initialDirectory,
FileTypes allowedTypes,
);
/// Opens a file dialog for loading directories and returns a directory path.
///
/// Returns `null` if user cancels the operation.
@async
String? getDirectoryPath(String? initialDirectory);
}
| packages/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart",
"repo_id": "packages",
"token_count": 509
} | 975 |
name: file_selector_linux
description: Liunx implementation of the file_selector plugin.
repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_linux
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.9.2+1
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: file_selector
platforms:
linux:
pluginClass: FileSelectorPlugin
dartPluginClass: FileSelectorLinux
dependencies:
cross_file: ^0.3.1
file_selector_platform_interface: ^2.6.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- files
- file-selection
- file-selector
| packages/packages/file_selector/file_selector_linux/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_linux/pubspec.yaml",
"repo_id": "packages",
"token_count": 304
} | 976 |
name: example
description: Example for file_selector_macos implementation.
publish_to: 'none'
version: 1.0.0
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
file_selector_macos:
# When depending on this package from a real application you should use:
# file_selector_macos: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ..
file_selector_platform_interface: ^2.6.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/file_selector/file_selector_macos/example/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 254
} | 977 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 0.9.3+1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters.
## 0.9.3
* Adds `getSaveLocation` and deprecates `getSavePath`.
## 0.9.2
* Adds `getDirectoryPaths` implementation.
## 0.9.1+8
* Sets a cmake_policy compatibility version to fix build warnings.
* Updates minimum Flutter version to 3.3.
## 0.9.1+7
* Updates to `pigeon` version 9.
## 0.9.1+6
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 0.9.1+5
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates example code for `use_build_context_synchronously` lint.
* Updates minimum Flutter version to 3.0.
## 0.9.1+4
* Changes XTypeGroup initialization from final to const.
## 0.9.1+3
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 0.9.1+2
* Fixes the problem that the initial directory does not work after completing a file selection.
## 0.9.1+1
* Updates README for endorsement.
* Updates `flutter_test` to be a `dev_dependencies` entry.
## 0.9.1
* Converts the method channel to Pigeon.
## 0.9.0
* **BREAKING CHANGE**: Methods that take `XTypeGroup`s now throw an
`ArgumentError` if any group is not a wildcard (all filter types null or
empty), but doesn't include any of the filter types supported by Windows.
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.8.2+2
* Updates references to the obsolete master branch.
## 0.8.2+1
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.8.2
* Moves source to flutter/plugins, and restructures to allow for unit testing.
* Switches to an internal method channel implementation.
## 0.0.2+1
* Update README
## 0.0.2
* Update SDK constraint to signal compatibility with null safety.
## 0.0.1
* Initial Windows implementation of `file_selector`.
| packages/packages/file_selector/file_selector_windows/CHANGELOG.md/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/CHANGELOG.md",
"repo_id": "packages",
"token_count": 699
} | 978 |
// 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.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
class TypeGroup {
TypeGroup({
required this.label,
required this.extensions,
});
String label;
List<String?> extensions;
Object encode() {
return <Object?>[
label,
extensions,
];
}
static TypeGroup decode(Object result) {
result as List<Object?>;
return TypeGroup(
label: result[0]! as String,
extensions: (result[1] as List<Object?>?)!.cast<String?>(),
);
}
}
class SelectionOptions {
SelectionOptions({
required this.allowMultiple,
required this.selectFolders,
required this.allowedTypes,
});
bool allowMultiple;
bool selectFolders;
List<TypeGroup?> allowedTypes;
Object encode() {
return <Object?>[
allowMultiple,
selectFolders,
allowedTypes,
];
}
static SelectionOptions decode(Object result) {
result as List<Object?>;
return SelectionOptions(
allowMultiple: result[0]! as bool,
selectFolders: result[1]! as bool,
allowedTypes: (result[2] as List<Object?>?)!.cast<TypeGroup?>(),
);
}
}
/// The result from an open or save dialog.
class FileDialogResult {
FileDialogResult({
required this.paths,
this.typeGroupIndex,
});
/// The selected paths.
///
/// Empty if the dialog was canceled.
List<String?> paths;
/// The type group index (into the list provided in [SelectionOptions]) of
/// the group that was selected when the dialog was confirmed.
///
/// Null if no type groups were provided, or the dialog was canceled.
int? typeGroupIndex;
Object encode() {
return <Object?>[
paths,
typeGroupIndex,
];
}
static FileDialogResult decode(Object result) {
result as List<Object?>;
return FileDialogResult(
paths: (result[0] as List<Object?>?)!.cast<String?>(),
typeGroupIndex: result[1] as int?,
);
}
}
class _FileSelectorApiCodec extends StandardMessageCodec {
const _FileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileDialogResult) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is SelectionOptions) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is TypeGroup) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileDialogResult.decode(readValue(buffer)!);
case 129:
return SelectionOptions.decode(readValue(buffer)!);
case 130:
return TypeGroup.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class FileSelectorApi {
/// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
FileSelectorApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _FileSelectorApiCodec();
Future<FileDialogResult> showOpenDialog(SelectionOptions arg_options,
String? arg_initialDirectory, String? arg_confirmButtonText) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showOpenDialog', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(
<Object?>[arg_options, arg_initialDirectory, arg_confirmButtonText])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as FileDialogResult?)!;
}
}
Future<FileDialogResult> showSaveDialog(
SelectionOptions arg_options,
String? arg_initialDirectory,
String? arg_suggestedName,
String? arg_confirmButtonText) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showSaveDialog', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_options,
arg_initialDirectory,
arg_suggestedName,
arg_confirmButtonText
]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as FileDialogResult?)!;
}
}
}
| packages/packages/file_selector/file_selector_windows/lib/src/messages.g.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/lib/src/messages.g.dart",
"repo_id": "packages",
"token_count": 2298
} | 979 |
// 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.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#ifndef PIGEON_MESSAGES_G_H_
#define PIGEON_MESSAGES_G_H_
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace file_selector_windows {
// Generated class from Pigeon.
class FlutterError {
public:
explicit FlutterError(const std::string& code) : code_(code) {}
explicit FlutterError(const std::string& code, const std::string& message)
: code_(code), message_(message) {}
explicit FlutterError(const std::string& code, const std::string& message,
const flutter::EncodableValue& details)
: code_(code), message_(message), details_(details) {}
const std::string& code() const { return code_; }
const std::string& message() const { return message_; }
const flutter::EncodableValue& details() const { return details_; }
private:
std::string code_;
std::string message_;
flutter::EncodableValue details_;
};
template <class T>
class ErrorOr {
public:
ErrorOr(const T& rhs) : v_(rhs) {}
ErrorOr(const T&& rhs) : v_(std::move(rhs)) {}
ErrorOr(const FlutterError& rhs) : v_(rhs) {}
ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {}
bool has_error() const { return std::holds_alternative<FlutterError>(v_); }
const T& value() const { return std::get<T>(v_); };
const FlutterError& error() const { return std::get<FlutterError>(v_); };
private:
friend class FileSelectorApi;
ErrorOr() = default;
T TakeValue() && { return std::get<T>(std::move(v_)); }
std::variant<T, FlutterError> v_;
};
// Generated class from Pigeon that represents data sent in messages.
class TypeGroup {
public:
// Constructs an object setting all fields.
explicit TypeGroup(const std::string& label,
const flutter::EncodableList& extensions);
const std::string& label() const;
void set_label(std::string_view value_arg);
const flutter::EncodableList& extensions() const;
void set_extensions(const flutter::EncodableList& value_arg);
private:
static TypeGroup FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class FileSelectorApi;
friend class FileSelectorApiCodecSerializer;
std::string label_;
flutter::EncodableList extensions_;
};
// Generated class from Pigeon that represents data sent in messages.
class SelectionOptions {
public:
// Constructs an object setting all fields.
explicit SelectionOptions(bool allow_multiple, bool select_folders,
const flutter::EncodableList& allowed_types);
bool allow_multiple() const;
void set_allow_multiple(bool value_arg);
bool select_folders() const;
void set_select_folders(bool value_arg);
const flutter::EncodableList& allowed_types() const;
void set_allowed_types(const flutter::EncodableList& value_arg);
private:
static SelectionOptions FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class FileSelectorApi;
friend class FileSelectorApiCodecSerializer;
bool allow_multiple_;
bool select_folders_;
flutter::EncodableList allowed_types_;
};
// The result from an open or save dialog.
//
// Generated class from Pigeon that represents data sent in messages.
class FileDialogResult {
public:
// Constructs an object setting all non-nullable fields.
explicit FileDialogResult(const flutter::EncodableList& paths);
// Constructs an object setting all fields.
explicit FileDialogResult(const flutter::EncodableList& paths,
const int64_t* type_group_index);
// The selected paths.
//
// Empty if the dialog was canceled.
const flutter::EncodableList& paths() const;
void set_paths(const flutter::EncodableList& value_arg);
// The type group index (into the list provided in [SelectionOptions]) of
// the group that was selected when the dialog was confirmed.
//
// Null if no type groups were provided, or the dialog was canceled.
const int64_t* type_group_index() const;
void set_type_group_index(const int64_t* value_arg);
void set_type_group_index(int64_t value_arg);
private:
static FileDialogResult FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class FileSelectorApi;
friend class FileSelectorApiCodecSerializer;
flutter::EncodableList paths_;
std::optional<int64_t> type_group_index_;
};
class FileSelectorApiCodecSerializer : public flutter::StandardCodecSerializer {
public:
FileSelectorApiCodecSerializer();
inline static FileSelectorApiCodecSerializer& GetInstance() {
static FileSelectorApiCodecSerializer sInstance;
return sInstance;
}
void WriteValue(const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const override;
protected:
flutter::EncodableValue ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const override;
};
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class FileSelectorApi {
public:
FileSelectorApi(const FileSelectorApi&) = delete;
FileSelectorApi& operator=(const FileSelectorApi&) = delete;
virtual ~FileSelectorApi() {}
virtual ErrorOr<FileDialogResult> ShowOpenDialog(
const SelectionOptions& options, const std::string* initial_directory,
const std::string* confirm_button_text) = 0;
virtual ErrorOr<FileDialogResult> ShowSaveDialog(
const SelectionOptions& options, const std::string* initial_directory,
const std::string* suggested_name,
const std::string* confirm_button_text) = 0;
// The codec used by FileSelectorApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `FileSelectorApi` to handle messages through the
// `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
FileSelectorApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
FileSelectorApi() = default;
};
} // namespace file_selector_windows
#endif // PIGEON_MESSAGES_G_H_
| packages/packages/file_selector/file_selector_windows/windows/messages.g.h/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/windows/messages.g.h",
"repo_id": "packages",
"token_count": 2171
} | 980 |
# 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: 4f9d92fbbdf072a70a70d2179a9f87392b94104c
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 4f9d92fbbdf072a70a70d2179a9f87392b94104c
base_revision: 4f9d92fbbdf072a70a70d2179a9f87392b94104c
- platform: windows
create_revision: 4f9d92fbbdf072a70a70d2179a9f87392b94104c
base_revision: 4f9d92fbbdf072a70a70d2179a9f87392b94104c
# 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_adaptive_scaffold/example/.metadata/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/.metadata",
"repo_id": "packages",
"token_count": 361
} | 981 |
#include "Generated.xcconfig"
| packages/packages/flutter_adaptive_scaffold/example/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/ios/Flutter/Debug.xcconfig",
"repo_id": "packages",
"token_count": 12
} | 982 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/flutter_adaptive_scaffold/example/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 983 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 4.1.11
* Replaces deprecated loadBuffer API usage.
## 4.1.10
* Fixes image asset link to use image within package.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Updates README to improve example of using `NetworkImageWithRetry`.
## 4.1.9
* Adds an example app.
## 4.1.8
* Adds pub topics to package metadata.
## 4.1.7
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Migrates deprecated `ImageProvider.load` to `ImageProvider.loadBuffer`.
## 4.1.6
* Fixes unawaited_futures violations.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
* Aligns Dart and Flutter SDK constraints.
## 4.1.5
* Removes use of `runtimeType.toString()`.
## 4.1.4
* Ignores lint warnings from new changes in Flutter master.
* Suppresses more deprecation warnings for changes to Flutter master.
* Removes duplicate test from test script.
* Fixes lint warnings.
## 4.1.3
* Suppresses deprecation warnings.
## 4.1.2
* Migrates from `ui.hash*` to `Object.hash*`.
## 4.1.1
* Updates package description.
* Updates for non-nullable bindings.
## 4.1.0
- Added custom header support.
## 4.0.1
- Moved source to flutter/packages
## 4.0.0
- Migrates to null safety
- **Breaking change**: `NetworkImageWithRetry.load` now throws a `FetchFailure` if the fetched image data is zero bytes.
## 3.0.0
* **Breaking change**. Updates for Flutter 1.10.15.
## 2.0.1
- Update Flutter SDK version constraint.
## 2.0.0
* **Breaking change**. Updates for Flutter 1.5.9.
## 1.0.0
* **Breaking change**. SDK constraints to support Flutter beta versions and Dart 2 only.
## 0.0.3
- Moved `flutter_test` to dev_dependencies in `pubspec.yaml`, and fixed issues
flagged by the analyzer.
## 0.0.2
- Add `NetworkImageWithRetry`, an `ImageProvider` with a retry mechanism.
## 0.0.1
- Contains no useful code.
| packages/packages/flutter_image/CHANGELOG.md/0 | {
"file_path": "packages/packages/flutter_image/CHANGELOG.md",
"repo_id": "packages",
"token_count": 660
} | 984 |
// 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.
/// Utilities for loading images from the network.
///
/// This library expands the capabilities of the basic [Image.network] and
/// [NetworkImage] provided by Flutter core libraries, to include a retry
/// mechanism and connectivity detection.
library network;
import 'dart:async';
import 'dart:io' as io;
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
// Method signature for _loadWithRetry decode callbacks.
typedef _SimpleDecoderCallback = Future<ui.Codec> Function(
ui.ImmutableBuffer buffer);
/// Fetches the image from the given URL, associating it with the given scale.
///
/// If [fetchStrategy] is specified, uses it instead of the
/// [defaultFetchStrategy] to obtain instructions for fetching the URL.
///
/// The image will be cached regardless of cache headers from the server.
@immutable
class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
/// Creates an object that fetches the image at the given [url].
const NetworkImageWithRetry(
this.url, {
this.scale = 1.0,
this.fetchStrategy = defaultFetchStrategy,
this.headers,
});
/// The HTTP client used to download images.
static final io.HttpClient _client = io.HttpClient();
/// The URL from which the image will be fetched.
final String url;
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
/// The strategy used to fetch the [url] and retry when the fetch fails.
///
/// This function is called at least once and may be called multiple times.
/// The first time it is called, it is passed a null [FetchFailure], which
/// indicates that this is the first attempt to fetch the [url]. Subsequent
/// calls pass non-null [FetchFailure] values, which indicate that previous
/// fetch attempts failed.
final FetchStrategy fetchStrategy;
/// HTTP Headers applied to the request.
///
/// Keys from this map will be used as header field names and the
/// values will be used as header values. A list of header names can
/// be found at https://datatracker.ietf.org/doc/html/rfc7231#section-8.3
///
/// If the value is a DateTime, an HTTP date format will be applied.
/// If the value is an Iterable, each element will be added separately.
/// For all other types the default Object.toString method will be used.
///
/// Header names are converted to lower-case. If two header names are
/// the same when converted to lower-case, they are considered to be
/// the same header, with one set of values.
///
/// For example, to add an authorization header to the request:
///
/// final NetworkImageWithRetry subject = NetworkImageWithRetry(
/// Uri.parse('https://www.flutter.com/top_secret.png'),
/// headers: <String, Object>{
/// 'Authorization': base64Encode(utf8.encode('user:password'))
/// },
/// );
final Map<String, Object>? headers;
/// Used by [defaultFetchStrategy].
///
/// This indirection is necessary because [defaultFetchStrategy] is used as
/// the default constructor argument value, which requires that it be a const
/// expression.
static final FetchStrategy _defaultFetchStrategyFunction =
const FetchStrategyBuilder().build();
/// The [FetchStrategy] that [NetworkImageWithRetry] uses by default.
static Future<FetchInstructions> defaultFetchStrategy(
Uri uri, FetchFailure? failure) {
return _defaultFetchStrategyFunction(uri, failure);
}
@override
Future<NetworkImageWithRetry> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<NetworkImageWithRetry>(this);
}
@override
ImageStreamCompleter loadImage(
NetworkImageWithRetry key,
ImageDecoderCallback decode,
) {
return OneFrameImageStreamCompleter(_loadWithRetry(key, decode),
informationCollector: () sync* {
yield ErrorDescription('Image provider: $this');
yield ErrorDescription('Image key: $key');
});
}
void _debugCheckInstructions(FetchInstructions? instructions) {
assert(() {
if (instructions == null) {
if (fetchStrategy == defaultFetchStrategy) {
throw StateError(
'The default FetchStrategy returned null FetchInstructions. This\n'
'is likely a bug in $runtimeType. Please file a bug at\n'
'https://github.com/flutter/flutter/issues.');
} else {
throw StateError(
'The custom FetchStrategy used to fetch $url returned null\n'
'FetchInstructions. FetchInstructions must never be null, but\n'
'instead instruct to either make another fetch attempt or give up.');
}
}
return true;
}());
}
Future<ImageInfo> _loadWithRetry(
NetworkImageWithRetry key, _SimpleDecoderCallback decode) async {
assert(key == this);
final Stopwatch stopwatch = Stopwatch()..start();
final Uri resolved = Uri.base.resolve(key.url);
FetchInstructions instructions = await fetchStrategy(resolved, null);
_debugCheckInstructions(instructions);
int attemptCount = 0;
FetchFailure? lastFailure;
while (!instructions.shouldGiveUp) {
attemptCount += 1;
io.HttpClientRequest? request;
try {
request = await _client
.getUrl(instructions.uri)
.timeout(instructions.timeout);
headers?.forEach((String key, Object value) {
request?.headers.add(key, value);
});
final io.HttpClientResponse response =
await request.close().timeout(instructions.timeout);
if (response.statusCode != 200) {
throw FetchFailure._(
totalDuration: stopwatch.elapsed,
attemptCount: attemptCount,
httpStatusCode: response.statusCode,
);
}
final _Uint8ListBuilder builder = await response
.fold(
_Uint8ListBuilder(),
(_Uint8ListBuilder buffer, List<int> bytes) => buffer..add(bytes),
)
.timeout(instructions.timeout);
final Uint8List bytes = builder.data;
if (bytes.lengthInBytes == 0) {
throw FetchFailure._(
totalDuration: stopwatch.elapsed,
attemptCount: attemptCount,
httpStatusCode: response.statusCode,
);
}
final ui.Codec codec =
await decode(await ui.ImmutableBuffer.fromUint8List(bytes));
final ui.Image image = (await codec.getNextFrame()).image;
return ImageInfo(
image: image,
scale: key.scale,
);
} catch (error) {
await request?.close();
lastFailure = error is FetchFailure
? error
: FetchFailure._(
totalDuration: stopwatch.elapsed,
attemptCount: attemptCount,
originalException: error,
);
instructions = await fetchStrategy(instructions.uri, lastFailure);
_debugCheckInstructions(instructions);
}
}
if (instructions.alternativeImage != null) {
return instructions.alternativeImage!;
}
assert(lastFailure != null);
if (FlutterError.onError != null) {
FlutterError.onError!(FlutterErrorDetails(
exception: lastFailure!,
library: 'package:flutter_image',
context: ErrorDescription(
'${objectRuntimeType(this, 'NetworkImageWithRetry')} failed to load ${instructions.uri}'),
));
}
throw lastFailure!;
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is NetworkImageWithRetry &&
url == other.url &&
scale == other.scale;
}
@override
int get hashCode => Object.hash(url, scale);
@override
String toString() =>
'${objectRuntimeType(this, 'NetworkImageWithRetry')}("$url", scale: $scale)';
}
/// This function is called to get [FetchInstructions] to fetch an image.
///
/// The instructions are executed as soon as possible after the returned
/// [Future] resolves. If a delay in necessary between retries, use a delayed
/// [Future], such as [Future.delayed]. This is useful for implementing
/// back-off strategies and for recovering from lack of connectivity.
///
/// [uri] is the last requested image URI. A [FetchStrategy] may choose to use
/// a different URI (see [FetchInstructions.uri]).
///
/// If [failure] is `null`, then this is the first attempt to fetch the image.
///
/// If the [failure] is not `null`, it contains the information about the
/// previous attempt to fetch the image. A [FetchStrategy] may attempt to
/// recover from the failure by returning [FetchInstructions] that instruct
/// [NetworkImageWithRetry] to try again.
///
/// See [NetworkImageWithRetry.defaultFetchStrategy] for an example.
typedef FetchStrategy = Future<FetchInstructions> Function(
Uri uri, FetchFailure? failure);
/// Instructions [NetworkImageWithRetry] uses to fetch the image.
@immutable
class FetchInstructions {
/// Instructs [NetworkImageWithRetry] to give up trying to download the image.
const FetchInstructions.giveUp({
required this.uri,
this.alternativeImage,
}) : shouldGiveUp = true,
timeout = Duration.zero;
/// Instructs [NetworkImageWithRetry] to attempt to download the image from
/// the given [uri] and [timeout] if it takes too long.
const FetchInstructions.attempt({
required this.uri,
required this.timeout,
}) : shouldGiveUp = false,
alternativeImage = null;
/// Instructs to give up trying.
///
/// If [alternativeImage] is `null` reports the latest [FetchFailure] to
/// [FlutterError].
final bool shouldGiveUp;
/// Timeout for the next network call.
final Duration timeout;
/// The URI to use on the next attempt.
final Uri uri;
/// Instructs to give up and use this image instead.
final Future<ImageInfo>? alternativeImage;
@override
String toString() {
return '${objectRuntimeType(this, 'FetchInstructions')}(\n'
' shouldGiveUp: $shouldGiveUp\n'
' timeout: $timeout\n'
' uri: $uri\n'
' alternativeImage?: ${alternativeImage != null ? 'yes' : 'no'}\n'
')';
}
}
/// Contains information about a failed attempt to fetch an image.
@immutable
class FetchFailure implements Exception {
const FetchFailure._({
required this.totalDuration,
required this.attemptCount,
this.httpStatusCode,
this.originalException,
}) : assert(attemptCount > 0);
/// The total amount of time it has taken so far to download the image.
final Duration totalDuration;
/// The number of times [NetworkImageWithRetry] attempted to fetch the image
/// so far.
///
/// This value starts with 1 and grows by 1 with each attempt to fetch the
/// image.
final int attemptCount;
/// HTTP status code, such as 500.
final int? httpStatusCode;
/// The exception that caused the fetch failure.
final dynamic originalException;
@override
String toString() {
return '${objectRuntimeType(this, 'FetchFailure')}(\n'
' attemptCount: $attemptCount\n'
' httpStatusCode: $httpStatusCode\n'
' totalDuration: $totalDuration\n'
' originalException: $originalException\n'
')';
}
}
/// An indefinitely growing builder of a [Uint8List].
class _Uint8ListBuilder {
static const int _kInitialSize = 100000; // 100KB-ish
int _usedLength = 0;
Uint8List _buffer = Uint8List(_kInitialSize);
Uint8List get data => Uint8List.view(_buffer.buffer, 0, _usedLength);
void add(List<int> bytes) {
_ensureCanAdd(bytes.length);
_buffer.setAll(_usedLength, bytes);
_usedLength += bytes.length;
}
void _ensureCanAdd(int byteCount) {
final int totalSpaceNeeded = _usedLength + byteCount;
int newLength = _buffer.length;
while (totalSpaceNeeded > newLength) {
newLength *= 2;
}
if (newLength != _buffer.length) {
final Uint8List newBuffer = Uint8List(newLength);
newBuffer.setAll(0, _buffer);
newBuffer.setRange(0, _usedLength, _buffer);
_buffer = newBuffer;
}
}
}
/// Determines whether the given HTTP [statusCode] is transient.
typedef TransientHttpStatusCodePredicate = bool Function(int statusCode);
/// Builds a [FetchStrategy] function that retries up to a certain amount of
/// times for up to a certain amount of time.
///
/// Pauses between retries with pauses growing exponentially (known as
/// exponential backoff). Each attempt is subject to a [timeout]. Retries only
/// those HTTP status codes considered transient by a
/// [transientHttpStatusCodePredicate] function.
class FetchStrategyBuilder {
/// Creates a fetch strategy builder.
///
/// All parameters must be non-null.
const FetchStrategyBuilder({
this.timeout = const Duration(seconds: 30),
this.totalFetchTimeout = const Duration(minutes: 1),
this.maxAttempts = 5,
this.initialPauseBetweenRetries = const Duration(seconds: 1),
this.exponentialBackoffMultiplier = 2,
this.transientHttpStatusCodePredicate =
defaultTransientHttpStatusCodePredicate,
});
/// A list of HTTP status codes that can generally be retried.
///
/// You may want to use a different list depending on the needs of your
/// application.
static const List<int> defaultTransientHttpStatusCodes = <int>[
0, // Network error
408, // Request timeout
500, // Internal server error
502, // Bad gateway
503, // Service unavailable
504 // Gateway timeout
];
/// Maximum amount of time a single fetch attempt is allowed to take.
final Duration timeout;
/// A strategy built by this builder will retry for up to this amount of time
/// before giving up.
final Duration totalFetchTimeout;
/// Maximum number of attempts a strategy will make before giving up.
final int maxAttempts;
/// Initial amount of time between retries.
final Duration initialPauseBetweenRetries;
/// The pause between retries is multiplied by this number with each attempt,
/// causing it to grow exponentially.
final num exponentialBackoffMultiplier;
/// A function that determines whether a given HTTP status code should be
/// retried.
final TransientHttpStatusCodePredicate transientHttpStatusCodePredicate;
/// Uses [defaultTransientHttpStatusCodes] to determine if the [statusCode] is
/// transient.
static bool defaultTransientHttpStatusCodePredicate(int statusCode) {
return defaultTransientHttpStatusCodes.contains(statusCode);
}
/// Builds a [FetchStrategy] that operates using the properties of this
/// builder.
FetchStrategy build() {
return (Uri uri, FetchFailure? failure) async {
if (failure == null) {
// First attempt. Just load.
return FetchInstructions.attempt(
uri: uri,
timeout: timeout,
);
}
final bool isRetriableFailure = (failure.httpStatusCode != null &&
transientHttpStatusCodePredicate(failure.httpStatusCode!)) ||
failure.originalException is io.SocketException;
// If cannot retry, give up.
if (!isRetriableFailure || // retrying will not help
failure.totalDuration > totalFetchTimeout || // taking too long
failure.attemptCount > maxAttempts) {
// too many attempts
return FetchInstructions.giveUp(uri: uri);
}
// Exponential back-off.
final Duration pauseBetweenRetries = initialPauseBetweenRetries *
math.pow(exponentialBackoffMultiplier, failure.attemptCount - 1);
await Future<void>.delayed(pauseBetweenRetries);
// Retry.
return FetchInstructions.attempt(
uri: uri,
timeout: timeout,
);
};
}
}
| packages/packages/flutter_image/lib/network.dart/0 | {
"file_path": "packages/packages/flutter_image/lib/network.dart",
"repo_id": "packages",
"token_count": 5421
} | 985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.