text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
import 'package:api_client/api_client.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/share/share.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 _MockShareResource extends Mock implements ShareResource {}
void main() {
Card card(String id) => Card(
id: id,
name: id,
description: 'description',
image: '',
rarity: false,
power: 1,
suit: Suit.air,
);
final cards = [card('1'), card('2'), card('3')];
group('CardInspector', () {
Widget buildSubject() => CardInspectorDialog(
cards: cards,
playerCardIds: const ['1', '2', '3'],
startingIndex: 0,
);
testWidgets('renders', (tester) async {
await tester.pumpSubject(buildSubject());
expect(find.byType(CardInspectorDialog), findsOneWidget);
});
testWidgets('renders a GameCard', (tester) async {
await tester.pumpSubject(buildSubject());
expect(find.byType(GameCard), findsOneWidget);
});
testWidgets('renders a share button', (tester) async {
await tester.pumpSubject(buildSubject());
expect(find.byIcon(Icons.share_outlined), findsOneWidget);
});
testWidgets('can go to the next card by tapping forward button',
(tester) async {
await tester.pumpSubject(buildSubject());
final card = find.byWidgetPredicate(
(widget) => widget is GameCard && widget.name == '1',
);
expect(card, findsOneWidget);
await tester.tap(find.byIcon(Icons.arrow_forward));
await tester.pumpAndSettle();
final nextCard = find.byWidgetPredicate(
(widget) => widget is GameCard && widget.name == '2',
);
expect(nextCard, findsOneWidget);
});
testWidgets('can go to the previous card by back button', (tester) async {
await tester.pumpSubject(buildSubject());
final card = find.byWidgetPredicate(
(widget) => widget is GameCard && widget.name == '1',
);
expect(card, findsOneWidget);
await tester.tap(find.byIcon(Icons.arrow_back));
await tester.pumpAndSettle();
final previousCard = find.byWidgetPredicate(
(widget) => widget is GameCard && widget.name == '3',
);
expect(previousCard, findsOneWidget);
});
testWidgets(
'pops navigation when around the card is tapped ',
(tester) async {
final goRouter = MockGoRouter();
await tester.pumpSubject(
buildSubject(),
router: goRouter,
);
final containerFinder = find.byType(GameCard);
final containerBox = tester.getRect(containerFinder);
final tapPosition =
Offset(containerBox.right + 10, containerBox.top + 10);
await tester.tapAt(tapPosition);
await tester.pumpAndSettle();
verify(goRouter.pop).called(1);
},
);
testWidgets(
'does not pop navigation when the card is tapped ',
(tester) async {
final goRouter = MockGoRouter();
await tester.pumpSubject(
buildSubject(),
router: goRouter,
);
await tester.tap(find.byType(GameCard));
await tester.pumpAndSettle();
verifyNever(goRouter.pop);
},
);
testWidgets('renders a dialog on share button tapped', (tester) async {
final shareResource = _MockShareResource();
when(() => shareResource.facebookShareCardUrl(any())).thenReturn('');
when(() => shareResource.twitterShareCardUrl(any())).thenReturn('');
await tester.pumpSubject(buildSubject(), shareResource: shareResource);
await tester.tap(find.byIcon(Icons.share_outlined));
await tester.pumpAndSettle();
expect(find.byType(ShareDialog), findsOneWidget);
});
});
}
extension CardInspectorTest on WidgetTester {
Future<void> pumpSubject(
Widget widget, {
GoRouter? router,
ShareResource? shareResource,
}) async {
await mockNetworkImages(() {
return pumpApp(widget, router: router, shareResource: shareResource);
});
}
}
| io_flip/test/game/views/card_inspector_test.dart/0 | {
"file_path": "io_flip/test/game/views/card_inspector_test.dart",
"repo_id": "io_flip",
"token_count": 1767
} | 922 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/how_to_play/how_to_play.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class _MockHowToPlayBloc extends MockBloc<HowToPlayEvent, HowToPlayState>
implements HowToPlayBloc {}
void main() {
group('HowToPlayView', () {
late HowToPlayBloc bloc;
setUp(() {
bloc = _MockHowToPlayBloc();
});
void mockStates(List<HowToPlayState> states) {
whenListen(
bloc,
Stream.fromIterable(states),
initialState: states.isNotEmpty ? states.first : null,
);
}
group('renders', () {
testWidgets('step view', (tester) async {
mockStates([HowToPlayState()]);
await tester.pumpSubject(bloc);
expect(find.byType(HowToPlayStepView), findsOneWidget);
});
testWidgets('page indicator', (tester) async {
mockStates([HowToPlayState()]);
await tester.pumpSubject(bloc);
expect(find.byKey(Key('how_to_play_page_indicator')), findsOneWidget);
});
testWidgets('navigation buttons', (tester) async {
mockStates([HowToPlayState()]);
await tester.pumpSubject(bloc);
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
expect(find.byIcon(Icons.arrow_forward), findsOneWidget);
});
testWidgets('first step when initially showing', (tester) async {
mockStates([HowToPlayState()]);
await tester.pumpSubject(bloc);
expect(find.byType(HowToPlayIntro), findsOneWidget);
});
});
testWidgets('can navigate the entire tutorial', (tester) async {
final goRouter = MockGoRouter();
when(goRouter.canPop).thenReturn(true);
await tester.pumpSubject(
HowToPlayBloc(),
goRouter: goRouter,
);
expect(find.byType(HowToPlayIntro), findsOneWidget);
final nextButton = find.byIcon(Icons.arrow_forward);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(HowToPlayHandBuilding), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(HowToPlaySuitsIntro), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(SuitsWheel), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(SuitsWheel), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(SuitsWheel), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(SuitsWheel), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
expect(find.byType(SuitsWheel), findsOneWidget);
await tester.tap(nextButton);
await tester.pumpAndSettle();
verify(goRouter.pop).called(1);
});
testWidgets('can navigate back', (tester) async {
final goRouter = MockGoRouter();
when(goRouter.canPop).thenReturn(true);
await tester.pumpSubject(
HowToPlayBloc(),
goRouter: goRouter,
);
final nextButton = find.byIcon(Icons.arrow_forward);
final backButton = find.byIcon(Icons.arrow_back);
await tester.tap(nextButton);
await tester.pumpAndSettle();
await tester.tap(backButton);
await tester.pumpAndSettle();
expect(find.byType(HowToPlayIntro), findsOneWidget);
await tester.tap(backButton);
await tester.pumpAndSettle();
verify(goRouter.pop).called(1);
});
});
}
extension HowToPlayViewTest on WidgetTester {
Future<void> pumpSubject(
HowToPlayBloc bloc, {
GoRouter? goRouter,
}) {
return pumpApp(
Dialog(
child: BlocProvider<HowToPlayBloc>.value(
value: bloc,
child: HowToPlayView(),
),
),
router: goRouter,
);
}
}
| io_flip/test/how_to_play/view/how_to_play_view_test.dart/0 | {
"file_path": "io_flip/test/how_to_play/view/how_to_play_view_test.dart",
"repo_id": "io_flip",
"token_count": 1781
} | 923 |
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
import 'dart:math';
void main(List<String> args) async {
const batchNumber = 10;
const batchSize = 4;
final rng = Random();
for (var i = 0; i < batchNumber; i++) {
final proccessesFuture = List.generate(batchSize, (i) async {
await Future<void>.delayed(
Duration(seconds: (2 * rng.nextDouble()).round()),
);
return Process.start('open', [
'https://a16e0900d-fe2c-3609-b43c-87093e447b78.web.app/#/match_making',
]);
});
final processes = await Future.wait(proccessesFuture);
print('Running ${processes.length} processes');
for (final p in processes) {
p.stderr.listen((event) {
print(utf8.decode(event));
});
}
await Future.wait(
processes.map((p) => p.exitCode),
);
await Future<void>.delayed(
Duration(seconds: (4 * rng.nextDouble()).round()),
);
print('Done!');
}
}
| io_flip/test/match_making/stress_test_runner.dart/0 | {
"file_path": "io_flip/test/match_making/stress_test_runner.dart",
"repo_id": "io_flip",
"token_count": 410
} | 924 |
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/settings/persistence/persistence.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
group('LocalStorageSettingsPersistence', () {
setUp(() {
SharedPreferences.setMockInitialValues({});
});
test('getMusicOn', () async {
SharedPreferences.setMockInitialValues({
'musicOn': false,
});
final persistence = LocalStorageSettingsPersistence();
final value = await persistence.getMusicOn();
expect(value, isFalse);
});
test('getSoundsOn', () async {
SharedPreferences.setMockInitialValues({
'soundsOn': false,
});
final persistence = LocalStorageSettingsPersistence();
final value = await persistence.getSoundsOn();
expect(value, isFalse);
});
test('getMuted', () async {
SharedPreferences.setMockInitialValues({
'mute': false,
});
final persistence = LocalStorageSettingsPersistence();
final value = await persistence.getMuted(defaultValue: false);
expect(value, isFalse);
});
test('getMuted returns default value if null', () async {
final persistence = LocalStorageSettingsPersistence();
final value = await persistence.getMuted(defaultValue: false);
expect(value, isFalse);
});
test('saveMuted', () async {
final persistence = LocalStorageSettingsPersistence();
await persistence.saveMuted(active: true);
expect(
await persistence.getMuted(defaultValue: false),
isTrue,
);
});
test('saveMusicOn', () async {
final persistence = LocalStorageSettingsPersistence();
await persistence.saveMusicOn(active: true);
expect(
await persistence.getMusicOn(),
isTrue,
);
});
test('saveSoundsOn', () async {
final persistence = LocalStorageSettingsPersistence();
await persistence.saveSoundsOn(active: true);
expect(
await persistence.getSoundsOn(),
isTrue,
);
});
});
}
| io_flip/test/settings/persistence/local_storage_settings_persistence_test.dart/0 | {
"file_path": "io_flip/test/settings/persistence/local_storage_settings_persistence_test.dart",
"repo_id": "io_flip",
"token_count": 766
} | 925 |
/**
* @type {import('@types/eslint').Linter.BaseConfig}
*/
module.exports = {
extends: ['plugin:@docusaurus/recommended'],
plugins: ['@docusaurus'],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
parser: '@babel/eslint-parser',
};
| news_toolkit/docs/.eslintrc.js/0 | {
"file_path": "news_toolkit/docs/.eslintrc.js",
"repo_id": "news_toolkit",
"token_count": 105
} | 926 |
---
sidebar_position: 4
description: Learn how to customize the look and feel of your Flutter news application.
---
# Theming
## Splash Screen
Flutter's [Adding a Splash Screen to Your Mobile App](https://docs.flutter.dev/development/ui/advanced/splash-screen) documentation provides the most up-to-date and in-depth guidance on customizing the splash screen in your mobile app.
### Android
Within the `android/app/src/main/res` folder, replace `launch_image.png` inside the
- `mipmap-mdpi`
- `mipmap-hdpi`
- `mipmap-xhdpi`
- `mipmap-xxhdpi`
folders with the image asset you want featured on your Android splash screen. The `launch_image.png` you provide inside the `mipmap` folders should have an appropriate size for that folder.
The background color of your splash screen can be changed by editing the hex code value with `name="splash_background"` in `android/app/src/main/res/values/colors.xml`.
### iOS
You should configure your iOS splash screen using an Xcode storyboard. To begin, add your splash screen image assets named
- `LaunchImage.png`
- `LaunchImage@2x.png`
- `LaunchImage@3x.png`
with sizes corresponding to the filename inside the `ios/Runner/Assets.xcassets/LaunchImage.imageset` folder.
Open your project's `ios` folder in Xcode and open `Runner/LaunchScreen.storyboard` in the editor. Specify your desired splash screen image and background by selecting those elements and editing their properties in the Xcode inspectors window. Feel free to further edit the splash screen properties in the Xcode inspectors window to customize the exact look of your splash screen.
## App Launcher Icon
You can use the [Flutter Launcher Icons](https://pub.dev/packages/flutter_launcher_icons) package to streamline adding your new app launcher icon.
Alternatively, you may want to manually update your app's launcher icon. Flutter's documentation contains information on how to accomplish this for both [iOS](https://docs.flutter.dev/deployment/ios#add-an-app-icon) and [Android](https://docs.flutter.dev/deployment/android#adding-a-launcher-icon).
## App Logo
App logo image assets are displayed at both the top of the feed view and at the top of the app navigation drawer. To replace these with your custom assets, replace the following files:
- `packages/app_ui/assets/images/logo_dark.png`
- `packages/app_ui/assets/images/logo_light.png`
Change the dimensions specified in the `AppLogo` widget (`packages/app_ui/lib/src/widgets/app_logo.dart`) to match your new image dimensions.
## App Colors
The colors used throughout your app are specified in the `app_colors.dart` file found in `packages/app_ui/lib/src/colors`. Add custom colors to this file and reference them as an attribute of the `AppColors` class inside your app (e.g. `AppColors.orange`). The role of colors within your app can be specified as either theme information or as an inline color.
### Theme Colors
Some colors are assigned to themes, which allow colors to be shared throughout your app based on their intended role in the user interface. For additional information on specifying theme colors, reference the Flutter [Use Themes to Share Colors and Font Styles](https://docs.flutter.dev/cookbook/design/themes) cookbook.
App themes are laid out in the `app_theme.dart` file inside the `packages/app_ui/lib/src/theme` folder. For example, the widget-specific theme `_appBarTheme` allow you to specify the colors and theme information for your [AppBar](https://api.flutter.dev/flutter/material/AppBar-class.html).
### In-line Colors
Not all of your desired color assignments can be specified by changing the app's theme data. You may want to use a color only on certain instances of a widget or specify colors with more granularity than the theme information supports. There are several existing inline color specifications in your app:
_Specifying Button Colors_
The colors of an app button are specified by the named constructors laid out in `packages/app_ui/lib/src/widgets/app_button.dart`. To specify new button colors, create a new color constructor. For example, to create an orange app button create the constructor
```dart
const AppButton.orange({
Key? key,
VoidCallback? onPressed,
double? elevation,
TextStyle? textStyle,
required Widget child,
}) : this._(
key: key,
onPressed: onPressed,
buttonColor: AppColors.orange,
child: child,
foregroundColor: AppColors.white,
elevation: elevation,
textStyle: textStyle,
);
```
You can then call the new `AppButton.orange` constructor in your app wherever you want to add an orange button, or replace an existing constructor call such as `AppButton.redWine` with your new constructor to update the button color.
_Specifying TabBar Colors_
The `TabBarTheme` specified in `app_theme.dart` does not provide a `backgroundColor` property. To specify a specific color for the `CategoriesTabBar` rendered below the `AppBar`, edit `CategoriesTabBar`'s `build()` method inside `lib/categories/widgets/categories_tab_bar.dart` to place the `TabBar` widget inside a `ColoredBox`:
```dart
return ColoredBox(
color: AppColors.orange,
child: TabBar(
controller: controller,
isScrollable: true,
tabs: tabs,
),
);
```
Other widgets with in-line specified colors include:
- `PostContentPremiumCategory`
- `SlideshowCategory`
- `PostContentCategory`
- `MagicLinkPromptSubtitle`
- `ManageSubscriptionView`
- `AppTextField`
- `ArticleIntroduction`
## Typography
### Fonts
For general details regarding font customization, reference Flutter's [Use a Custom Font](https://docs.flutter.dev/cookbook/design/fonts) documentation.
To change the fonts used in your app, first add your font assets inside `packages/app_ui/assets/fonts`, then list the added fonts under the `fonts` section of `packages/app_ui/pubspec.yaml`.
You can specify which fonts you want used in different elements of your app in the `packages/app_ui/lib/src/typography/app_text_styles.dart` file.
You can specify the fonts used in your app by changing the `fontFamily` value at the following locations inside the `app_text_styles.dart` file to match the name of your desired font family:
- `UITextStyle._baseTextStyle`
- Specifies the default font used in UI elements.
- `ContentTextStyle._baseTextStyle`
- Specifies the default font used in news content.
- `button`
- Specifies the font used in buttons.
- `caption`
- Specifies the font used in your caption text.
- `overline`
- Specifies the font used in overline text elements such as category labels.
- `labelSmall`
- Specifies the font used in label text (_not referenced in the template out-of-the-box_).
### Additional Customization
To customize your app's typography further, you can add and edit various `TextStyle` values, such as `fontWeight`, `fontSize`, and others in the `packages/app_ui/lib/src/typography/app_text_styles.dart` file.
The correspondence between selected `TextStyles` and visual elements in the app is illustrated below.
For styling text contained in `HtmlBlocks`, you can edit the `style` map in `packages/news_blocks_ui/lib/src/html.dart` to associate HTML selectors with the `TextStyle` you want to be utilized when the HTML is rendered.
### Text Style Visualization
<img src="https://user-images.githubusercontent.com/61138206/191820826-7ef6c873-94ee-49e8-bcd6-25e35421c055.png"/>
| news_toolkit/docs/docs/flutter_development/theming.md/0 | {
"file_path": "news_toolkit/docs/docs/flutter_development/theming.md",
"repo_id": "news_toolkit",
"token_count": 2084
} | 927 |
---
sidebar_position: 5
description: Learn how to configure your own newsletter.
---
# Creating a newsletter
The current [implementation](https://github.com/flutter/news_toolkit/blob/main/flutter_news_example/api/routes/api/v1/newsletter/subscription.dart) of a newsletter email subscription always returns true and the response is handled in the app as a success state. Be aware that the current implementation of this feature doesn't store the subscriber state for a user.
```dart
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
Response onRequest(RequestContext context) {
if (context.request.method != HttpMethod.post) {
return Response(statusCode: HttpStatus.methodNotAllowed);
}
return Response(statusCode: HttpStatus.created);
}
```
To fully use the newsletter subscription feature, please add your API handling logic or an already existing email service, such as [mailchimp.](https://mailchimp.com/)
| news_toolkit/docs/docs/server_development/newsletter.md/0 | {
"file_path": "news_toolkit/docs/docs/server_development/newsletter.md",
"repo_id": "news_toolkit",
"token_count": 263
} | 928 |
/// Flutter News Example API Server-Side Library
library api;
export 'src/data/in_memory_news_data_source.dart' show InMemoryNewsDataSource;
export 'src/data/models/models.dart'
show
Article,
Category,
Feed,
RelatedArticles,
Subscription,
SubscriptionCost,
SubscriptionPlan,
User;
export 'src/data/news_data_source.dart' show NewsDataSource;
export 'src/middleware/middleware.dart'
show RequestUser, newsDataSourceProvider, userProvider;
export 'src/models/models.dart'
show
ArticleResponse,
CategoriesResponse,
CurrentUserResponse,
FeedResponse,
PopularSearchResponse,
RelatedArticlesResponse,
RelevantSearchResponse,
SubscriptionsResponse;
| news_toolkit/flutter_news_example/api/lib/api.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/api.dart",
"repo_id": "news_toolkit",
"token_count": 313
} | 929 |
import 'package:flutter_news_example_api/api.dart';
import 'package:news_blocks/news_blocks.dart';
/// {@template news_data_source}
/// An interface for a news content data source.
/// {@endtemplate}
abstract class NewsDataSource {
/// {@macro news_data_source}
const NewsDataSource();
/// Returns a news [Article] for the provided article [id].
///
/// In addition, the contents can be paginated by supplying
/// [limit] and [offset].
///
/// * [limit] - The number of content blocks to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
/// * [preview] - Whether to return a preview of the article.
///
/// Returns `null` if there is no article with the provided [id].
Future<Article?> getArticle({
required String id,
int limit = 20,
int offset = 0,
bool preview = false,
});
/// Returns whether the article with the associated [id] is a premium article.
///
/// Returns `null` if there is no article with the provided [id].
Future<bool?> isPremiumArticle({required String id});
/// Returns a list of current popular topics.
Future<List<String>> getPopularTopics();
/// Returns a list of current relevant topics
/// based on the provided [term].
Future<List<String>> getRelevantTopics({required String term});
/// Returns a list of current popular article blocks.
Future<List<NewsBlock>> getPopularArticles();
/// Returns a list of relevant article blocks
/// based on the provided [term].
Future<List<NewsBlock>> getRelevantArticles({required String term});
/// Returns [RelatedArticles] for the provided article [id].
///
/// In addition, the contents can be paginated by supplying
/// [limit] and [offset].
///
/// * [limit] - The number of content blocks to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
Future<RelatedArticles> getRelatedArticles({
required String id,
int limit = 20,
int offset = 0,
});
/// Returns a news [Feed] for the provided [category].
/// By default [Category.top] is used.
///
/// In addition, the feed can be paginated by supplying
/// [limit] and [offset].
///
/// * [limit] - The number of results to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
Future<Feed> getFeed({
Category category = Category.top,
int limit = 20,
int offset = 0,
});
/// Returns a list of all available news categories.
Future<List<Category>> getCategories();
/// Subscribes the user with the associated [userId] to
/// the subscription with the associated [subscriptionId].
Future<void> createSubscription({
required String userId,
required String subscriptionId,
});
/// Returns a list of all available news subscriptions.
Future<List<Subscription>> getSubscriptions();
/// Returns the user associated with the provided [userId].
/// Returns `null` if there is no user with the provided [userId].
Future<User?> getUser({required String userId});
}
| news_toolkit/flutter_news_example/api/lib/src/data/news_data_source.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/data/news_data_source.dart",
"repo_id": "news_toolkit",
"token_count": 885
} | 930 |
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:news_blocks/news_blocks.dart';
part 'related_articles_response.g.dart';
/// {@template related_articles_response}
/// A response object which contains related news article content.
/// {@endtemplate}
@JsonSerializable()
class RelatedArticlesResponse extends Equatable {
/// {@macro related_articles_response}
const RelatedArticlesResponse({
required this.relatedArticles,
required this.totalCount,
});
/// Converts a `Map<String, dynamic>` into
/// a [RelatedArticlesResponse] instance.
factory RelatedArticlesResponse.fromJson(Map<String, dynamic> json) =>
_$RelatedArticlesResponseFromJson(json);
/// The article content blocks.
@NewsBlocksConverter()
final List<NewsBlock> relatedArticles;
/// The total number of available content blocks.
final int totalCount;
/// Converts the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() => _$RelatedArticlesResponseToJson(this);
@override
List<Object> get props => [relatedArticles, totalCount];
}
| news_toolkit/flutter_news_example/api/lib/src/models/related_articles_response/related_articles_response.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/models/related_articles_response/related_articles_response.dart",
"repo_id": "news_toolkit",
"token_count": 336
} | 931 |
// 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 'block_action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
NavigateToArticleAction _$NavigateToArticleActionFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'NavigateToArticleAction',
json,
($checkedConvert) {
final val = NavigateToArticleAction(
articleId: $checkedConvert('article_id', (v) => v as String),
type: $checkedConvert('type',
(v) => v as String? ?? NavigateToArticleAction.identifier),
);
return val;
},
fieldKeyMap: const {'articleId': 'article_id'},
);
Map<String, dynamic> _$NavigateToArticleActionToJson(
NavigateToArticleAction instance) =>
<String, dynamic>{
'article_id': instance.articleId,
'type': instance.type,
};
NavigateToVideoArticleAction _$NavigateToVideoArticleActionFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'NavigateToVideoArticleAction',
json,
($checkedConvert) {
final val = NavigateToVideoArticleAction(
articleId: $checkedConvert('article_id', (v) => v as String),
type: $checkedConvert('type',
(v) => v as String? ?? NavigateToVideoArticleAction.identifier),
);
return val;
},
fieldKeyMap: const {'articleId': 'article_id'},
);
Map<String, dynamic> _$NavigateToVideoArticleActionToJson(
NavigateToVideoArticleAction instance) =>
<String, dynamic>{
'article_id': instance.articleId,
'type': instance.type,
};
NavigateToFeedCategoryAction _$NavigateToFeedCategoryActionFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'NavigateToFeedCategoryAction',
json,
($checkedConvert) {
final val = NavigateToFeedCategoryAction(
category: $checkedConvert(
'category', (v) => $enumDecode(_$CategoryEnumMap, v)),
type: $checkedConvert('type',
(v) => v as String? ?? NavigateToFeedCategoryAction.identifier),
);
return val;
},
);
Map<String, dynamic> _$NavigateToFeedCategoryActionToJson(
NavigateToFeedCategoryAction instance) =>
<String, dynamic>{
'category': _$CategoryEnumMap[instance.category],
'type': instance.type,
};
const _$CategoryEnumMap = {
Category.business: 'business',
Category.entertainment: 'entertainment',
Category.top: 'top',
Category.health: 'health',
Category.science: 'science',
Category.sports: 'sports',
Category.technology: 'technology',
};
NavigateToSlideshowAction _$NavigateToSlideshowActionFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'NavigateToSlideshowAction',
json,
($checkedConvert) {
final val = NavigateToSlideshowAction(
articleId: $checkedConvert('article_id', (v) => v as String),
slideshow: $checkedConvert('slideshow',
(v) => SlideshowBlock.fromJson(v as Map<String, dynamic>)),
type: $checkedConvert('type',
(v) => v as String? ?? NavigateToSlideshowAction.identifier),
);
return val;
},
fieldKeyMap: const {'articleId': 'article_id'},
);
Map<String, dynamic> _$NavigateToSlideshowActionToJson(
NavigateToSlideshowAction instance) =>
<String, dynamic>{
'article_id': instance.articleId,
'slideshow': instance.slideshow.toJson(),
'type': instance.type,
};
UnknownBlockAction _$UnknownBlockActionFromJson(Map<String, dynamic> json) =>
$checkedCreate(
'UnknownBlockAction',
json,
($checkedConvert) {
final val = UnknownBlockAction(
type: $checkedConvert(
'type', (v) => v as String? ?? UnknownBlockAction.identifier),
);
return val;
},
);
Map<String, dynamic> _$UnknownBlockActionToJson(UnknownBlockAction instance) =>
<String, dynamic>{
'type': instance.type,
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/block_action.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/block_action.g.dart",
"repo_id": "news_toolkit",
"token_count": 1719
} | 932 |
// 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_grid_group_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
PostGridGroupBlock _$PostGridGroupBlockFromJson(Map<String, dynamic> json) =>
$checkedCreate(
'PostGridGroupBlock',
json,
($checkedConvert) {
final val = PostGridGroupBlock(
category: $checkedConvert(
'category', (v) => $enumDecode(_$PostCategoryEnumMap, v)),
tiles: $checkedConvert(
'tiles',
(v) => (v as List<dynamic>)
.map((e) =>
PostGridTileBlock.fromJson(e as Map<String, dynamic>))
.toList()),
type: $checkedConvert(
'type', (v) => v as String? ?? PostGridGroupBlock.identifier),
);
return val;
},
);
Map<String, dynamic> _$PostGridGroupBlockToJson(PostGridGroupBlock instance) =>
<String, dynamic>{
'category': _$PostCategoryEnumMap[instance.category],
'tiles': instance.tiles.map((e) => e.toJson()).toList(),
'type': instance.type,
};
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_grid_group_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_grid_group_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 653
} | 933 |
// 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 'slideshow_introduction_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SlideshowIntroductionBlock _$SlideshowIntroductionBlockFromJson(
Map<String, dynamic> json) =>
$checkedCreate(
'SlideshowIntroductionBlock',
json,
($checkedConvert) {
final val = SlideshowIntroductionBlock(
title: $checkedConvert('title', (v) => v as String),
coverImageUrl: $checkedConvert('cover_image_url', (v) => v as String),
type: $checkedConvert('type',
(v) => v as String? ?? SlideshowIntroductionBlock.identifier),
action: $checkedConvert('action',
(v) => const BlockActionConverter().fromJson(v as Map?)),
);
return val;
},
fieldKeyMap: const {'coverImageUrl': 'cover_image_url'},
);
Map<String, dynamic> _$SlideshowIntroductionBlockToJson(
SlideshowIntroductionBlock instance) {
final val = <String, dynamic>{
'title': instance.title,
'cover_image_url': instance.coverImageUrl,
};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('action', const BlockActionConverter().toJson(instance.action));
val['type'] = instance.type;
return val;
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_introduction_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_introduction_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 574
} | 934 |
// 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 'video_block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
VideoBlock _$VideoBlockFromJson(Map<String, dynamic> json) => $checkedCreate(
'VideoBlock',
json,
($checkedConvert) {
final val = VideoBlock(
videoUrl: $checkedConvert('video_url', (v) => v as String),
type: $checkedConvert(
'type', (v) => v as String? ?? VideoBlock.identifier),
);
return val;
},
fieldKeyMap: const {'videoUrl': 'video_url'},
);
Map<String, dynamic> _$VideoBlockToJson(VideoBlock instance) =>
<String, dynamic>{
'video_url': instance.videoUrl,
'type': instance.type,
};
| news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/video_block.g.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/video_block.g.dart",
"repo_id": "news_toolkit",
"token_count": 370
} | 935 |
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('PostGridGroupBlock', () {
test('can be (de)serialized', () {
final block = PostGridGroupBlock(
category: PostCategory.science,
tiles: [
PostGridTileBlock(
id: 'id',
category: PostCategory.science,
author: 'author',
publishedAt: DateTime(2022, 3, 12),
imageUrl: 'imageUrl',
title: 'title',
)
],
);
expect(PostGridGroupBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_grid_group_block_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_grid_group_block_test.dart",
"repo_id": "news_toolkit",
"token_count": 295
} | 936 |
// ignore_for_file: prefer_const_constructors
import 'package:news_blocks/news_blocks.dart';
import 'package:test/test.dart';
void main() {
group('VideoBlock', () {
test('can be (de)serialized', () {
final block = VideoBlock(videoUrl: 'videoUrl');
expect(VideoBlock.fromJson(block.toJson()), equals(block));
});
});
}
| news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/video_block_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/video_block_test.dart",
"repo_id": "news_toolkit",
"token_count": 129
} | 937 |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../../../routes/api/v1/articles/[id]/index.dart' as route;
class _MockNewsDataSource extends Mock implements NewsDataSource {}
class _MockRequestContext extends Mock implements RequestContext {}
class _MockRequestUser extends Mock implements RequestUser {}
void main() {
const id = '__test_article_id__';
group('GET /api/v1/articles/<id>', () {
late NewsDataSource newsDataSource;
setUp(() {
newsDataSource = _MockNewsDataSource();
});
test('responds with a 404 when article not found (isPremium)', () async {
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => null);
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.notFound));
});
test('responds with a 404 when article not found (getArticle)', () async {
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => false);
when(
() => newsDataSource.getArticle(id: id),
).thenAnswer((_) async => null);
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.notFound));
});
test(
'responds with a 200 and full article '
'when article is not premium', () async {
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => false);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: false,
isPreview: false,
);
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
test(
'responds with a 200 and article preview '
'when article preview is requested', () async {
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id, preview: true),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => false);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: false,
isPreview: true,
);
final request = Request(
'GET',
Uri.parse('http://127.0.0.1/').replace(
queryParameters: {'preview': 'true'},
),
);
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
test(
'responds with a 200 and article preview '
'when article is premium and user is anonymous', () async {
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id, preview: true),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => true);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: true,
isPreview: true,
);
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
test(
'responds with a 200 and article preview '
'when article is premium and user is not found', () async {
const userId = '__test_user_id__';
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id, preview: true),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => true);
when(
() => newsDataSource.getUser(userId: userId),
).thenAnswer((_) async => null);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: true,
isPreview: true,
);
final requestUser = _MockRequestUser();
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => requestUser.id).thenReturn(userId);
when(() => requestUser.isAnonymous).thenReturn(false);
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(requestUser);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
test(
'responds with a 200 and article preview '
'when article is premium and user has no subscription plan', () async {
const userId = '__test_user_id__';
const user = User(id: userId, subscription: SubscriptionPlan.none);
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id, preview: true),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => true);
when(
() => newsDataSource.getUser(userId: userId),
).thenAnswer((_) async => user);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: true,
isPreview: true,
);
final requestUser = _MockRequestUser();
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => requestUser.id).thenReturn(userId);
when(() => requestUser.isAnonymous).thenReturn(false);
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(requestUser);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
test(
'responds with a 200 and full article '
'when article is premium and user has a subscription plan', () async {
const userId = '__test_user_id__';
const user = User(id: userId, subscription: SubscriptionPlan.basic);
final url = Uri.parse('https://dailyglobe.com');
final article = Article(
title: 'title',
blocks: const [],
totalBlocks: 0,
url: url,
);
when(
() => newsDataSource.getArticle(id: id),
).thenAnswer((_) async => article);
when(
() => newsDataSource.isPremiumArticle(id: id),
).thenAnswer((_) async => true);
when(
() => newsDataSource.getUser(userId: userId),
).thenAnswer((_) async => user);
final expected = ArticleResponse(
title: article.title,
content: article.blocks,
totalCount: article.totalBlocks,
url: url,
isPremium: true,
isPreview: false,
);
final requestUser = _MockRequestUser();
final request = Request('GET', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => requestUser.id).thenReturn(userId);
when(() => requestUser.isAnonymous).thenReturn(false);
when(() => context.request).thenReturn(request);
when(() => context.read<NewsDataSource>()).thenReturn(newsDataSource);
when(() => context.read<RequestUser>()).thenReturn(requestUser);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.ok));
expect(await response.json(), equals(expected.toJson()));
});
});
test('responds with 405 when method is not GET.', () async {
final request = Request('POST', Uri.parse('http://127.0.0.1/'));
final context = _MockRequestContext();
when(() => context.request).thenReturn(request);
final response = await route.onRequest(context, id);
expect(response.statusCode, equals(HttpStatus.methodNotAllowed));
});
}
| news_toolkit/flutter_news_example/api/test/routes/articles/[id]/index_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/test/routes/articles/[id]/index_test.dart",
"repo_id": "news_toolkit",
"token_count": 4331
} | 938 |
import 'package:dart_frog/dart_frog.dart';
import 'package:flutter_news_example_api/api.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class _MockRequestContext extends Mock implements RequestContext {}
class _MockRequestUser extends Mock implements RequestUser {}
void main() {
group('userProvider', () {
late RequestContext context;
setUp(() {
context = _MockRequestContext();
when(() => context.provide<NewsDataSource>(any())).thenReturn(context);
when(() => context.provide<RequestUser>(any())).thenReturn(context);
});
test(
'provides RequestUser.anonymous '
'when authorization header is missing.', () async {
RequestUser? value;
final handler = userProvider()(
(_) {
value = context.read<RequestUser>();
return Response(body: '');
},
);
final request = Request.get(Uri.parse('http://localhost/'));
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
await handler(context);
expect(value, equals(RequestUser.anonymous));
});
test(
'provides RequestUser.anonymous '
'when authorization header is malformed (no bearer).', () async {
RequestUser? value;
final handler = userProvider()(
(_) {
value = context.read<RequestUser>();
return Response(body: '');
},
);
final request = Request.get(
Uri.parse('http://localhost/'),
headers: {'Authorization': 'some token'},
);
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
await handler(context);
expect(value, equals(RequestUser.anonymous));
expect(value!.isAnonymous, isTrue);
});
test(
'provides RequestUser.anonymous '
'when authorization header is malformed (too many segments).',
() async {
RequestUser? value;
final handler = userProvider()(
(_) {
value = context.read<RequestUser>();
return Response(body: '');
},
);
final request = Request.get(
Uri.parse('http://localhost/'),
headers: {'Authorization': 'bearer some token'},
);
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(RequestUser.anonymous);
await handler(context);
expect(value, equals(RequestUser.anonymous));
expect(value!.isAnonymous, isTrue);
});
test(
'provides correct RequestUser '
'when authorization header is valid.', () async {
const userId = '__user_id__';
final requestUser = _MockRequestUser();
when(() => requestUser.id).thenReturn(userId);
RequestUser? value;
final handler = userProvider()(
(_) {
value = context.read<RequestUser>();
return Response(body: '');
},
);
final request = Request.get(
Uri.parse('http://localhost/'),
headers: {'Authorization': 'Bearer $userId'},
);
when(() => context.request).thenReturn(request);
when(() => context.read<RequestUser>()).thenReturn(requestUser);
await handler(context);
expect(value, isA<RequestUser>().having((r) => r.id, 'id', userId));
});
});
}
| news_toolkit/flutter_news_example/api/test/src/middleware/user_provider_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/test/src/middleware/user_provider_test.dart",
"repo_id": "news_toolkit",
"token_count": 1359
} | 939 |
<!-- Replace with GoogleService-Info.plist from the Firebase Console -->
| news_toolkit/flutter_news_example/ios/Runner/production/GoogleService-Info.plist/0 | {
"file_path": "news_toolkit/flutter_news_example/ios/Runner/production/GoogleService-Info.plist",
"repo_id": "news_toolkit",
"token_count": 18
} | 940 |
import 'package:flutter/widgets.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/home/home.dart';
import 'package:flutter_news_example/onboarding/onboarding.dart';
List<Page<dynamic>> onGenerateAppViewPages(
AppStatus state,
List<Page<dynamic>> pages,
) {
switch (state) {
case AppStatus.onboardingRequired:
return [OnboardingPage.page()];
case AppStatus.unauthenticated:
case AppStatus.authenticated:
return [HomePage.page()];
}
}
| news_toolkit/flutter_news_example/lib/app/routes/routes.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/app/routes/routes.dart",
"repo_id": "news_toolkit",
"token_count": 185
} | 941 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/l10n/l10n.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:sliver_tools/sliver_tools.dart';
class ArticleTrailingContent extends StatelessWidget {
const ArticleTrailingContent({super.key});
@override
Widget build(BuildContext context) {
final relatedArticles =
context.select((ArticleBloc bloc) => bloc.state.relatedArticles);
final isArticlePreview =
context.select((ArticleBloc bloc) => bloc.state.isPreview);
final hasReachedArticleViewsLimit = context
.select((ArticleBloc bloc) => bloc.state.hasReachedArticleViewsLimit);
final isUserSubscribed =
context.select((AppBloc bloc) => bloc.state.isUserSubscribed);
final isArticlePremium =
context.select((ArticleBloc bloc) => bloc.state.isPremium);
final showSubscribeWithArticleLimitModal =
hasReachedArticleViewsLimit && !isUserSubscribed;
final showSubscribeModal = isArticlePremium && !isUserSubscribed;
return MultiSliver(
children: [
if (relatedArticles.isNotEmpty && !isArticlePreview) ...[
SliverPadding(
padding: const EdgeInsets.only(
top: AppSpacing.xlg,
left: AppSpacing.lg,
right: AppSpacing.lg,
bottom: AppSpacing.lg,
),
sliver: SliverToBoxAdapter(
child: Text(
context.l10n.relatedStories,
style: Theme.of(context).textTheme.displaySmall,
),
),
),
...relatedArticles.map(
(articleBlock) => CategoryFeedItem(block: articleBlock),
),
],
if (!isArticlePreview) ...[
const SliverPadding(
padding: EdgeInsets.all(AppSpacing.lg),
sliver: SliverToBoxAdapter(child: ArticleComments()),
)
],
if (isArticlePreview) ...[
SliverList(
delegate: SliverChildListDelegate(
[
const SizedBox(height: AppSpacing.xlg),
if (showSubscribeModal)
const SubscribeModal()
else if (showSubscribeWithArticleLimitModal)
const SubscribeWithArticleLimitModal(),
],
),
),
]
],
);
}
}
@visibleForTesting
class ArticleTrailingShadow extends StatelessWidget {
const ArticleTrailingShadow({super.key});
static const _gradientHeight = 256.0;
@override
Widget build(BuildContext context) {
return Positioned(
top: -_gradientHeight,
left: 0,
right: 0,
child: Column(
children: [
Container(
height: _gradientHeight,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.white.withOpacity(0),
AppColors.white.withOpacity(1),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
],
),
);
}
}
| news_toolkit/flutter_news_example/lib/article/widgets/article_trailing_content.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/article/widgets/article_trailing_content.dart",
"repo_id": "news_toolkit",
"token_count": 1593
} | 942 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_news_example/network_error/network_error.dart';
import 'package:flutter_news_example_api/client.dart';
class CategoryFeed extends StatelessWidget {
const CategoryFeed({
required this.category,
this.scrollController,
super.key,
});
final Category category;
final ScrollController? scrollController;
@override
Widget build(BuildContext context) {
final categoryFeed =
context.select((FeedBloc bloc) => bloc.state.feed[category]) ?? [];
final hasMoreNews =
context.select((FeedBloc bloc) => bloc.state.hasMoreNews[category]) ??
true;
final isFailure = context
.select((FeedBloc bloc) => bloc.state.status == FeedStatus.failure);
return BlocListener<FeedBloc, FeedState>(
listener: (context, state) {
if (state.status == FeedStatus.failure && state.feed.isEmpty) {
Navigator.of(context).push<void>(
NetworkError.route(
onRetry: () {
context
.read<FeedBloc>()
.add(FeedRefreshRequested(category: category));
Navigator.of(context).pop();
},
),
);
}
},
child: RefreshIndicator(
onRefresh: () async => context
.read<FeedBloc>()
.add(FeedRefreshRequested(category: category)),
displacement: 0,
color: AppColors.mediumHighEmphasisSurface,
child: SelectionArea(
child: CustomScrollView(
controller: scrollController,
slivers: _buildSliverItems(
context,
categoryFeed,
hasMoreNews,
isFailure,
),
),
),
),
);
}
List<Widget> _buildSliverItems(
BuildContext context,
List<NewsBlock> categoryFeed,
bool hasMoreNews,
bool isFailure,
) {
final sliverList = <Widget>[];
for (var index = 0; index < categoryFeed.length + 1; index++) {
late Widget result;
if (index == categoryFeed.length) {
if (isFailure) {
result = NetworkError(
onRetry: () {
context
.read<FeedBloc>()
.add(FeedRefreshRequested(category: category));
},
);
} else {
result = hasMoreNews
? Padding(
padding: EdgeInsets.only(
top: categoryFeed.isEmpty ? AppSpacing.xxxlg : 0,
),
child: CategoryFeedLoaderItem(
key: ValueKey(index),
onPresented: () => context
.read<FeedBloc>()
.add(FeedRequested(category: category)),
),
)
: const SizedBox();
}
sliverList.add(SliverToBoxAdapter(child: result));
} else {
final block = categoryFeed[index];
sliverList.add(CategoryFeedItem(block: block));
}
}
return sliverList;
}
}
| news_toolkit/flutter_news_example/lib/feed/widgets/category_feed.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/feed/widgets/category_feed.dart",
"repo_id": "news_toolkit",
"token_count": 1569
} | 943 |
part of 'login_with_email_link_bloc.dart';
abstract class LoginWithEmailLinkEvent extends Equatable {
const LoginWithEmailLinkEvent();
}
class LoginWithEmailLinkSubmitted extends LoginWithEmailLinkEvent
with AnalyticsEventMixin {
const LoginWithEmailLinkSubmitted(this.emailLink);
final Uri emailLink;
@override
AnalyticsEvent get event =>
const AnalyticsEvent('LoginWithEmailLinkSubmitted');
@override
List<Object> get props => [emailLink, event];
}
| news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_event.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_event.dart",
"repo_id": "news_toolkit",
"token_count": 141
} | 944 |
import 'package:ads_consent_client/ads_consent_client.dart';
import 'package:article_repository/article_repository.dart';
import 'package:deep_link_client/deep_link_client.dart';
import 'package:firebase_authentication_client/firebase_authentication_client.dart';
import 'package:firebase_notifications_client/firebase_notifications_client.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/main/bootstrap/bootstrap.dart';
import 'package:flutter_news_example/src/version.dart';
import 'package:flutter_news_example_api/client.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:news_repository/news_repository.dart';
import 'package:notifications_repository/notifications_repository.dart';
import 'package:package_info_client/package_info_client.dart';
import 'package:permission_client/permission_client.dart';
import 'package:persistent_storage/persistent_storage.dart';
import 'package:purchase_client/purchase_client.dart';
import 'package:token_storage/token_storage.dart';
import 'package:user_repository/user_repository.dart';
void main() {
bootstrap(
(
firebaseDynamicLinks,
firebaseMessaging,
sharedPreferences,
analyticsRepository,
) async {
final tokenStorage = InMemoryTokenStorage();
final apiClient = FlutterNewsExampleApiClient.localhost(
tokenProvider: tokenStorage.readToken,
);
const permissionClient = PermissionClient();
final persistentStorage = PersistentStorage(
sharedPreferences: sharedPreferences,
);
final packageInfoClient = PackageInfoClient(
appName: 'Flutter News Example [DEV]',
packageName: 'com.flutter.news.example.dev',
packageVersion: packageVersion,
);
final deepLinkClient = DeepLinkClient(
firebaseDynamicLinks: firebaseDynamicLinks,
);
final userStorage = UserStorage(storage: persistentStorage);
final authenticationClient = FirebaseAuthenticationClient(
tokenStorage: tokenStorage,
);
final notificationsClient = FirebaseNotificationsClient(
firebaseMessaging: firebaseMessaging,
);
final userRepository = UserRepository(
apiClient: apiClient,
authenticationClient: authenticationClient,
packageInfoClient: packageInfoClient,
deepLinkClient: deepLinkClient,
storage: userStorage,
);
final newsRepository = NewsRepository(
apiClient: apiClient,
);
final notificationsRepository = NotificationsRepository(
permissionClient: permissionClient,
storage: NotificationsStorage(storage: persistentStorage),
notificationsClient: notificationsClient,
apiClient: apiClient,
);
final articleRepository = ArticleRepository(
storage: ArticleStorage(storage: persistentStorage),
apiClient: apiClient,
);
final inAppPurchaseRepository = InAppPurchaseRepository(
authenticationClient: authenticationClient,
apiClient: apiClient,
inAppPurchase: PurchaseClient(),
);
final adsConsentClient = AdsConsentClient();
return App(
userRepository: userRepository,
newsRepository: newsRepository,
notificationsRepository: notificationsRepository,
articleRepository: articleRepository,
analyticsRepository: analyticsRepository,
inAppPurchaseRepository: inAppPurchaseRepository,
adsConsentClient: adsConsentClient,
user: await userRepository.user.first,
);
},
);
}
| news_toolkit/flutter_news_example/lib/main/main_development.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/main/main_development.dart",
"repo_id": "news_toolkit",
"token_count": 1280
} | 945 |
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:news_repository/news_repository.dart';
import 'package:notifications_repository/notifications_repository.dart';
part 'notification_preferences_state.dart';
part 'notification_preferences_event.dart';
class NotificationPreferencesBloc
extends Bloc<NotificationPreferencesEvent, NotificationPreferencesState> {
NotificationPreferencesBloc({
required NewsRepository newsRepository,
required NotificationsRepository notificationsRepository,
}) : _notificationsRepository = notificationsRepository,
_newsRepository = newsRepository,
super(
NotificationPreferencesState.initial(),
) {
on<CategoriesPreferenceToggled>(
_onCategoriesPreferenceToggled,
);
on<InitialCategoriesPreferencesRequested>(
_onInitialCategoriesPreferencesRequested,
);
}
final NotificationsRepository _notificationsRepository;
final NewsRepository _newsRepository;
FutureOr<void> _onCategoriesPreferenceToggled(
CategoriesPreferenceToggled event,
Emitter<NotificationPreferencesState> emit,
) async {
emit(state.copyWith(status: NotificationPreferencesStatus.loading));
final updatedCategories = Set<Category>.from(state.selectedCategories);
updatedCategories.contains(event.category)
? updatedCategories.remove(event.category)
: updatedCategories.add(event.category);
try {
await _notificationsRepository
.setCategoriesPreferences(updatedCategories);
emit(
state.copyWith(
status: NotificationPreferencesStatus.success,
selectedCategories: updatedCategories,
),
);
} catch (error, stackTrace) {
emit(
state.copyWith(status: NotificationPreferencesStatus.failure),
);
addError(error, stackTrace);
}
}
FutureOr<void> _onInitialCategoriesPreferencesRequested(
InitialCategoriesPreferencesRequested event,
Emitter<NotificationPreferencesState> emit,
) async {
emit(state.copyWith(status: NotificationPreferencesStatus.loading));
try {
late Set<Category> selectedCategories;
late CategoriesResponse categoriesResponse;
await Future.wait(
[
(() async => selectedCategories =
await _notificationsRepository.fetchCategoriesPreferences() ??
{})(),
(() async =>
categoriesResponse = await _newsRepository.getCategories())(),
],
);
emit(
state.copyWith(
status: NotificationPreferencesStatus.success,
selectedCategories: selectedCategories,
categories: categoriesResponse.categories.toSet(),
),
);
} catch (error, stackTrace) {
emit(
state.copyWith(status: NotificationPreferencesStatus.failure),
);
addError(error, stackTrace);
}
}
}
| news_toolkit/flutter_news_example/lib/notification_preferences/bloc/notification_preferences_bloc.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/notification_preferences/bloc/notification_preferences_bloc.dart",
"repo_id": "news_toolkit",
"token_count": 1097
} | 946 |
export 'onboarding_view_item.dart';
| news_toolkit/flutter_news_example/lib/onboarding/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/onboarding/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 13
} | 947 |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:user_repository/user_repository.dart';
part 'subscriptions_event.dart';
part 'subscriptions_state.dart';
class SubscriptionsBloc extends Bloc<SubscriptionsEvent, SubscriptionsState> {
SubscriptionsBloc({
required InAppPurchaseRepository inAppPurchaseRepository,
required UserRepository userRepository,
}) : _inAppPurchaseRepository = inAppPurchaseRepository,
_userRepository = userRepository,
super(
SubscriptionsState.initial(),
) {
on<SubscriptionsRequested>(_onSubscriptionsRequested);
on<SubscriptionPurchaseRequested>(_onSubscriptionPurchaseRequested);
on<SubscriptionPurchaseUpdated>(_onSubscriptionPurchaseUpdated);
_subscriptionPurchaseUpdateSubscription =
_inAppPurchaseRepository.purchaseUpdate.listen(
(purchase) => add(SubscriptionPurchaseUpdated(purchase: purchase)),
onError: addError,
);
}
final InAppPurchaseRepository _inAppPurchaseRepository;
final UserRepository _userRepository;
late StreamSubscription<PurchaseUpdate>
_subscriptionPurchaseUpdateSubscription;
FutureOr<void> _onSubscriptionsRequested(
SubscriptionsRequested event,
Emitter<SubscriptionsState> emit,
) async {
try {
final subscriptions = await _inAppPurchaseRepository.fetchSubscriptions();
emit(state.copyWith(subscriptions: subscriptions));
} catch (error, stackTrace) {
addError(error, stackTrace);
}
}
FutureOr<void> _onSubscriptionPurchaseRequested(
SubscriptionPurchaseRequested event,
Emitter<SubscriptionsState> emit,
) async {
try {
emit(state.copyWith(purchaseStatus: PurchaseStatus.pending));
await _inAppPurchaseRepository.purchase(subscription: event.subscription);
} catch (error, stackTrace) {
addError(error, stackTrace);
}
}
FutureOr<void> _onSubscriptionPurchaseUpdated(
SubscriptionPurchaseUpdated event,
Emitter<SubscriptionsState> emit,
) async {
final purchase = event.purchase;
if (purchase is PurchasePurchased) {
emit(
state.copyWith(
purchaseStatus: PurchaseStatus.pending,
),
);
} else if (purchase is PurchaseDelivered) {
await _userRepository.updateSubscriptionPlan();
emit(
state.copyWith(
purchaseStatus: PurchaseStatus.completed,
),
);
} else if (purchase is PurchaseFailed || purchase is PurchaseCanceled) {
emit(
state.copyWith(
purchaseStatus: PurchaseStatus.failed,
),
);
}
}
@override
Future<void> close() {
_subscriptionPurchaseUpdateSubscription.cancel();
return super.close();
}
}
| news_toolkit/flutter_news_example/lib/subscriptions/dialog/bloc/subscriptions_bloc.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/subscriptions/dialog/bloc/subscriptions_bloc.dart",
"repo_id": "news_toolkit",
"token_count": 1039
} | 948 |
export 'terms_of_service_modal.dart';
export 'terms_of_service_page.dart';
| news_toolkit/flutter_news_example/lib/terms_of_service/view/view.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/lib/terms_of_service/view/view.dart",
"repo_id": "news_toolkit",
"token_count": 29
} | 949 |
import 'package:analytics_repository/analytics_repository.dart';
import 'package:flutter_test/flutter_test.dart';
// NTGEvent is exported and can be implemented.
class FakeNTGEvent extends Fake implements NTGEvent {}
void main() {
group('NTGEvent', () {
test('can be implemented', () {
expect(FakeNTGEvent.new, returnsNormally);
});
group('NewsletterEvent', () {
group('signUp', () {
test('has correct values', () {
final event = NewsletterEvent.signUp();
expect(event.name, equals('newsletter_signup'));
expect(event.properties!['eventCategory'], equals('NTG newsletter'));
expect(event.properties!['eventAction'], equals('newsletter signup'));
expect(event.properties!['eventLabel'], equals('success'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('impression', () {
test(
'has correct values '
'when articleTitle is empty', () {
final event = NewsletterEvent.impression();
expect(event.name, equals('newsletter_impression'));
expect(event.properties!['eventCategory'], equals('NTG newsletter'));
expect(
event.properties!['eventAction'],
equals('newsletter modal impression 3'),
);
expect(event.properties!['eventLabel'], equals(''));
expect(event.properties!['nonInteraction'], equals('false'));
});
test(
'has correct values '
'when articleTitle is not empty', () {
const articleTitle = 'articleTitle';
final event = NewsletterEvent.impression(articleTitle: articleTitle);
expect(event.name, equals('newsletter_impression'));
expect(event.properties!['eventCategory'], equals('NTG newsletter'));
expect(
event.properties!['eventAction'],
equals('newsletter modal impression 3'),
);
expect(event.properties!['eventLabel'], equals(articleTitle));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
});
group('LoginEvent', () {
test('has correct values', () {
final event = LoginEvent();
expect(event.name, equals('login'));
expect(event.properties!['eventCategory'], equals('NTG account'));
expect(event.properties!['eventAction'], equals('login'));
expect(event.properties!['eventLabel'], equals('success'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('RegistrationEvent', () {
test('has correct values', () {
final event = RegistrationEvent();
expect(event.name, equals('registration'));
expect(event.properties!['eventCategory'], equals('NTG account'));
expect(event.properties!['eventAction'], equals('registration'));
expect(event.properties!['eventLabel'], equals('success'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('ArticleMilestoneEvent', () {
test('has correct values', () {
const milestonePercentage = 25;
const articleTitle = 'articleTitle';
final event = ArticleMilestoneEvent(
milestonePercentage: milestonePercentage,
articleTitle: articleTitle,
);
expect(event.name, equals('article_milestone'));
expect(
event.properties!['eventCategory'],
equals('NTG article milestone'),
);
expect(
event.properties!['eventAction'],
equals('$milestonePercentage%'),
);
expect(event.properties!['eventLabel'], equals(articleTitle));
expect(event.properties!['eventValue'], equals(milestonePercentage));
expect(event.properties!['nonInteraction'], equals('true'));
expect(event.properties!['hitType'], equals('event'));
});
});
group('ArticleCommentEvent', () {
test('has correct values', () {
const articleTitle = 'articleTitle';
final event = ArticleCommentEvent(articleTitle: articleTitle);
expect(event.name, equals('comment'));
expect(event.properties!['eventCategory'], equals('NTG user'));
expect(event.properties!['eventAction'], equals('comment added'));
expect(event.properties!['eventLabel'], equals(articleTitle));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('SocialShareEvent', () {
test('has correct values', () {
final event = SocialShareEvent();
expect(event.name, equals('social_share'));
expect(event.properties!['eventCategory'], equals('NTG social'));
expect(event.properties!['eventAction'], equals('social share'));
expect(event.properties!['eventLabel'], equals('OS share menu'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('PushNotificationSubscriptionEvent', () {
test('has correct values', () {
final event = PushNotificationSubscriptionEvent();
expect(event.name, equals('push_notification_click'));
expect(
event.properties!['eventCategory'],
equals('NTG push notification'),
);
expect(event.properties!['eventAction'], equals('click'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
group('PaywallPromptEvent', () {
group('impression', () {
test('has correct values', () {
const impression = PaywallPromptImpression.subscription;
const articleTitle = 'articleTitle';
final event = PaywallPromptEvent.impression(
impression: impression,
articleTitle: articleTitle,
);
expect(event.name, equals('paywall_impression'));
expect(event.properties!['eventCategory'], equals('NTG paywall'));
expect(
event.properties!['eventAction'],
equals('paywall modal impression $impression'),
);
expect(event.properties!['eventLabel'], equals(articleTitle));
expect(event.properties!['nonInteraction'], equals('true'));
});
});
group('click', () {
test('has correct values', () {
const articleTitle = 'articleTitle';
final event = PaywallPromptEvent.click(
articleTitle: articleTitle,
);
expect(event.name, equals('paywall_click'));
expect(event.properties!['eventCategory'], equals('NTG paywall'));
expect(event.properties!['eventAction'], equals('click'));
expect(event.properties!['eventLabel'], equals(articleTitle));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
});
group('PaywallPromptImpression', () {
test('rewarded toString returns 1', () {
expect(PaywallPromptImpression.rewarded.toString(), equals('1'));
});
test('subscription toString returns 2', () {
expect(PaywallPromptImpression.subscription.toString(), equals('2'));
});
});
group('UserSubscriptionConversionEvent', () {
test('has correct values', () {
final event = UserSubscriptionConversionEvent();
expect(event.name, equals('subscription_submit'));
expect(event.properties!['eventCategory'], equals('NTG subscription'));
expect(event.properties!['eventAction'], equals('submit'));
expect(event.properties!['eventLabel'], equals('success'));
expect(event.properties!['nonInteraction'], equals('false'));
});
});
});
}
| news_toolkit/flutter_news_example/packages/analytics_repository/test/models/ntg_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/test/models/ntg_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 3030
} | 950 |
<svg width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 0H2C0.9 0 0.00999999 0.9 0.00999999 2L0 14C0 15.1 0.9 16 2 16H18C19.1 16 20 15.1 20 14V2C20 0.9 19.1 0 18 0ZM18 14H2V4L10 9L18 4V14ZM10 7L2 2H18L10 7Z" fill="#00677F"/>
</svg>
| news_toolkit/flutter_news_example/packages/app_ui/assets/icons/email_outline.svg/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/assets/icons/email_outline.svg",
"repo_id": "news_toolkit",
"token_count": 151
} | 951 |
export 'colors_page.dart';
| news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/colors/colors.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/lib/colors/colors.dart",
"repo_id": "news_toolkit",
"token_count": 11
} | 952 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// {@template app_theme}
/// The Default App [ThemeData].
/// {@endtemplate}
class AppTheme {
/// {@macro app_theme}
const AppTheme();
/// Default `ThemeData` for App UI.
ThemeData get themeData {
return ThemeData(
primaryColor: AppColors.blue,
canvasColor: _backgroundColor,
scaffoldBackgroundColor: _backgroundColor,
iconTheme: _iconTheme,
appBarTheme: _appBarTheme,
dividerTheme: _dividerTheme,
textTheme: _textTheme,
inputDecorationTheme: _inputDecorationTheme,
buttonTheme: _buttonTheme,
splashColor: AppColors.transparent,
snackBarTheme: _snackBarTheme,
elevatedButtonTheme: _elevatedButtonTheme,
textButtonTheme: _textButtonTheme,
colorScheme: _colorScheme,
bottomSheetTheme: _bottomSheetTheme,
listTileTheme: _listTileTheme,
switchTheme: _switchTheme,
progressIndicatorTheme: _progressIndicatorTheme,
tabBarTheme: _tabBarTheme,
bottomNavigationBarTheme: _bottomAppBarTheme,
chipTheme: _chipTheme,
);
}
ColorScheme get _colorScheme {
return ColorScheme.light(
secondary: AppColors.secondary,
background: _backgroundColor,
);
}
SnackBarThemeData get _snackBarTheme {
return SnackBarThemeData(
contentTextStyle: UITextStyle.bodyText1.copyWith(
color: AppColors.white,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppSpacing.sm),
),
actionTextColor: AppColors.lightBlue.shade300,
backgroundColor: AppColors.black,
elevation: 4,
behavior: SnackBarBehavior.floating,
);
}
Color get _backgroundColor => AppColors.white;
AppBarTheme get _appBarTheme {
return AppBarTheme(
iconTheme: _iconTheme,
titleTextStyle: _textTheme.titleLarge,
elevation: 0,
toolbarHeight: 64,
backgroundColor: AppColors.transparent,
systemOverlayStyle: const SystemUiOverlayStyle(
statusBarIconBrightness: Brightness.dark,
statusBarBrightness: Brightness.light,
),
);
}
IconThemeData get _iconTheme {
return const IconThemeData(
color: AppColors.onBackground,
);
}
DividerThemeData get _dividerTheme {
return const DividerThemeData(
color: AppColors.outlineLight,
space: AppSpacing.lg,
thickness: AppSpacing.xxxs,
indent: AppSpacing.lg,
endIndent: AppSpacing.lg,
);
}
TextTheme get _textTheme => uiTextTheme;
/// The Content text theme based on [ContentTextStyle].
static final contentTextTheme = TextTheme(
displayLarge: ContentTextStyle.headline1,
displayMedium: ContentTextStyle.headline2,
displaySmall: ContentTextStyle.headline3,
headlineMedium: ContentTextStyle.headline4,
headlineSmall: ContentTextStyle.headline5,
titleLarge: ContentTextStyle.headline6,
titleMedium: ContentTextStyle.subtitle1,
titleSmall: ContentTextStyle.subtitle2,
bodyLarge: ContentTextStyle.bodyText1,
bodyMedium: ContentTextStyle.bodyText2,
labelLarge: ContentTextStyle.button,
bodySmall: ContentTextStyle.caption,
labelSmall: ContentTextStyle.overline,
).apply(
bodyColor: AppColors.black,
displayColor: AppColors.black,
decorationColor: AppColors.black,
);
/// The UI text theme based on [UITextStyle].
static final uiTextTheme = TextTheme(
displayLarge: UITextStyle.headline1,
displayMedium: UITextStyle.headline2,
displaySmall: UITextStyle.headline3,
headlineMedium: UITextStyle.headline4,
headlineSmall: UITextStyle.headline5,
titleLarge: UITextStyle.headline6,
titleMedium: UITextStyle.subtitle1,
titleSmall: UITextStyle.subtitle2,
bodyLarge: UITextStyle.bodyText1,
bodyMedium: UITextStyle.bodyText2,
labelLarge: UITextStyle.button,
bodySmall: UITextStyle.caption,
labelSmall: UITextStyle.overline,
).apply(
bodyColor: AppColors.black,
displayColor: AppColors.black,
decorationColor: AppColors.black,
);
InputDecorationTheme get _inputDecorationTheme {
return InputDecorationTheme(
suffixIconColor: AppColors.mediumEmphasisSurface,
prefixIconColor: AppColors.mediumEmphasisSurface,
hoverColor: AppColors.inputHover,
focusColor: AppColors.inputFocused,
fillColor: AppColors.inputEnabled,
enabledBorder: _textFieldBorder,
focusedBorder: _textFieldBorder,
disabledBorder: _textFieldBorder,
hintStyle: UITextStyle.bodyText1.copyWith(
color: AppColors.mediumEmphasisSurface,
),
contentPadding: const EdgeInsets.all(AppSpacing.lg),
border: const UnderlineInputBorder(),
filled: true,
isDense: true,
errorStyle: UITextStyle.caption,
);
}
ButtonThemeData get _buttonTheme {
return ButtonThemeData(
textTheme: ButtonTextTheme.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppSpacing.sm),
),
);
}
ElevatedButtonThemeData get _elevatedButtonTheme {
return ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30)),
),
padding: const EdgeInsets.symmetric(vertical: AppSpacing.lg),
textStyle: _textTheme.labelLarge,
backgroundColor: AppColors.blue,
),
);
}
TextButtonThemeData get _textButtonTheme {
return TextButtonThemeData(
style: TextButton.styleFrom(
textStyle: _textTheme.labelLarge?.copyWith(
fontWeight: AppFontWeight.light,
),
foregroundColor: AppColors.black,
),
);
}
BottomSheetThemeData get _bottomSheetTheme {
return const BottomSheetThemeData(
backgroundColor: AppColors.modalBackground,
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(AppSpacing.lg),
topRight: Radius.circular(AppSpacing.lg),
),
),
);
}
ListTileThemeData get _listTileTheme {
return const ListTileThemeData(
iconColor: AppColors.onBackground,
contentPadding: EdgeInsets.all(AppSpacing.lg),
);
}
SwitchThemeData get _switchTheme {
return SwitchThemeData(
thumbColor:
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return AppColors.darkAqua;
}
return AppColors.eerieBlack;
}),
trackColor:
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return AppColors.primaryContainer;
}
return AppColors.paleSky;
}),
);
}
ProgressIndicatorThemeData get _progressIndicatorTheme {
return const ProgressIndicatorThemeData(
color: AppColors.darkAqua,
circularTrackColor: AppColors.borderOutline,
);
}
TabBarTheme get _tabBarTheme {
return TabBarTheme(
labelStyle: UITextStyle.button,
labelColor: AppColors.darkAqua,
labelPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.md + AppSpacing.xxs,
),
unselectedLabelStyle: UITextStyle.button,
unselectedLabelColor: AppColors.mediumEmphasisSurface,
indicator: const UnderlineTabIndicator(
borderSide: BorderSide(
width: 3,
color: AppColors.darkAqua,
),
),
indicatorSize: TabBarIndicatorSize.label,
);
}
}
InputBorder get _textFieldBorder => const UnderlineInputBorder(
borderSide: BorderSide(
width: 1.5,
color: AppColors.darkAqua,
),
);
BottomNavigationBarThemeData get _bottomAppBarTheme {
return BottomNavigationBarThemeData(
backgroundColor: AppColors.darkBackground,
selectedItemColor: AppColors.white,
unselectedItemColor: AppColors.white.withOpacity(0.74),
);
}
ChipThemeData get _chipTheme {
return const ChipThemeData(
backgroundColor: AppColors.transparent,
);
}
/// {@template app_dark_theme}
/// Dark Mode App [ThemeData].
/// {@endtemplate}
class AppDarkTheme extends AppTheme {
/// {@macro app_dark_theme}
const AppDarkTheme();
@override
ColorScheme get _colorScheme {
return const ColorScheme.dark().copyWith(
primary: AppColors.white,
secondary: AppColors.secondary,
background: AppColors.grey.shade900,
);
}
@override
TextTheme get _textTheme {
return AppTheme.contentTextTheme.apply(
bodyColor: AppColors.white,
displayColor: AppColors.white,
decorationColor: AppColors.white,
);
}
@override
SnackBarThemeData get _snackBarTheme {
return SnackBarThemeData(
contentTextStyle: UITextStyle.bodyText1.copyWith(
color: AppColors.black,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppSpacing.sm),
),
actionTextColor: AppColors.lightBlue.shade300,
backgroundColor: AppColors.grey.shade300,
elevation: 4,
behavior: SnackBarBehavior.floating,
);
}
@override
TextButtonThemeData get _textButtonTheme {
return TextButtonThemeData(
style: TextButton.styleFrom(
textStyle: _textTheme.labelLarge?.copyWith(
fontWeight: AppFontWeight.light,
),
foregroundColor: AppColors.white,
),
);
}
@override
Color get _backgroundColor => AppColors.grey.shade900;
@override
IconThemeData get _iconTheme {
return const IconThemeData(color: AppColors.white);
}
@override
DividerThemeData get _dividerTheme {
return const DividerThemeData(
color: AppColors.onBackground,
space: AppSpacing.lg,
thickness: AppSpacing.xxxs,
indent: AppSpacing.lg,
endIndent: AppSpacing.lg,
);
}
}
| news_toolkit/flutter_news_example/packages/app_ui/lib/src/theme/app_theme.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/theme/app_theme.dart",
"repo_id": "news_toolkit",
"token_count": 3946
} | 953 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockingjay/mockingjay.dart';
extension AppTester on WidgetTester {
Future<void> pumpApp(
Widget widgetUnderTest, {
ThemeData? theme,
MockNavigator? navigator,
}) async {
await pumpWidget(
MaterialApp(
theme: theme,
home: navigator == null
? Scaffold(
body: widgetUnderTest,
)
: MockNavigatorProvider(
navigator: navigator,
child: Scaffold(
body: widgetUnderTest,
),
),
),
);
await pump();
}
}
| news_toolkit/flutter_news_example/packages/app_ui/test/src/helpers/pump_app.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/helpers/pump_app.dart",
"repo_id": "news_toolkit",
"token_count": 344
} | 954 |
part of 'article_repository.dart';
/// Storage keys for the [ArticleStorage].
abstract class ArticleStorageKeys {
/// The number of article views.
static const articleViews = '__article_views_storage_key__';
/// The date when the number of article views was last reset.
static const articleViewsResetAt = '__article_views_reset_at_storage_key__';
/// Number of total articles views.
static const totalArticleViews = '__total_article_views_key__';
}
/// {@template article_storage}
/// Storage for the [ArticleRepository].
/// {@endtemplate}
class ArticleStorage {
/// {@macro article_storage}
const ArticleStorage({
required Storage storage,
}) : _storage = storage;
final Storage _storage;
/// Sets the number of article views in Storage.
Future<void> setArticleViews(int views) => _storage.write(
key: ArticleStorageKeys.articleViews,
value: views.toString(),
);
/// Fetches the number of article views from Storage.
Future<int> fetchArticleViews() async {
final articleViews =
await _storage.read(key: ArticleStorageKeys.articleViews);
return articleViews != null ? int.parse(articleViews) : 0;
}
/// Sets the reset date of the number of article views in Storage.
Future<void> setArticleViewsResetDate(DateTime date) => _storage.write(
key: ArticleStorageKeys.articleViewsResetAt,
value: date.toIso8601String(),
);
/// Fetches the reset date of the number of article views from Storage.
Future<DateTime?> fetchArticleViewsResetDate() async {
final resetDate =
await _storage.read(key: ArticleStorageKeys.articleViewsResetAt);
return resetDate != null ? DateTime.parse(resetDate) : null;
}
/// Sets the number of total article views.
Future<void> setTotalArticleViews(int count) => _storage.write(
key: ArticleStorageKeys.totalArticleViews,
value: count.toString(),
);
/// Fetches the number of total article views value from storage.
Future<int> fetchTotalArticleViews() async {
final count =
await _storage.read(key: ArticleStorageKeys.totalArticleViews);
return int.tryParse(count ?? '') ?? 0;
}
}
| news_toolkit/flutter_news_example/packages/article_repository/lib/src/article_storage.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/article_repository/lib/src/article_storage.dart",
"repo_id": "news_toolkit",
"token_count": 699
} | 955 |
include: package:very_good_analysis/analysis_options.5.1.0.yaml
| news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/analysis_options.yaml/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/analysis_options.yaml",
"repo_id": "news_toolkit",
"token_count": 23
} | 956 |
import 'dart:async';
import 'package:deep_link_client/deep_link_client.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
typedef OnAppLinkFunction = void Function(Uri uri, String stringUri);
class MockAppLinks extends Mock implements FirebaseDynamicLinks {}
class MockFirebaseCore extends Mock
with MockPlatformInterfaceMixin
implements FirebasePlatform {}
void main() {
late MockAppLinks appLinksMock;
late StreamController<PendingDynamicLinkData> onLinkStreamController;
setUp(() {
appLinksMock = MockAppLinks();
onLinkStreamController = StreamController<PendingDynamicLinkData>();
when(() => appLinksMock.onLink)
.thenAnswer((_) => onLinkStreamController.stream);
});
tearDown(() {
onLinkStreamController.close();
});
group('DeepLinkClient', () {
test('retrieves and publishes latest link if present', () {
final expectedUri = Uri.https('ham.app.test', '/test/path');
when(appLinksMock.getInitialLink).thenAnswer(
(_) => Future.value(PendingDynamicLinkData(link: expectedUri)),
);
final client = DeepLinkClient(firebaseDynamicLinks: appLinksMock);
expect(client.deepLinkStream, emits(expectedUri));
// Testing also the replay of the latest value.
expect(client.deepLinkStream, emits(expectedUri));
});
test('publishes DeepLinkClientFailure to stream if upstream throws', () {
final expectedError = Error();
final expectedStackTrace = StackTrace.current;
when(appLinksMock.getInitialLink).thenAnswer((_) {
return Future.error(expectedError, expectedStackTrace);
});
final client = DeepLinkClient(firebaseDynamicLinks: appLinksMock);
expect(
client.deepLinkStream,
emitsError(
isA<DeepLinkClientFailure>()
.having((failure) => failure.error, 'error', expectedError),
),
);
});
test('publishes values received through onAppLink callback', () {
final expectedUri1 = Uri.https('ham.app.test', '/test/1');
final expectedUri2 = Uri.https('ham.app.test', '/test/2');
when(appLinksMock.getInitialLink).thenAnswer((_) async => null);
final client = DeepLinkClient(firebaseDynamicLinks: appLinksMock);
expect(
client.deepLinkStream,
emitsInOrder(
<Uri>[expectedUri1, expectedUri1, expectedUri2, expectedUri1],
),
);
onLinkStreamController
..add(PendingDynamicLinkData(link: expectedUri1))
..add(PendingDynamicLinkData(link: expectedUri1))
..add(PendingDynamicLinkData(link: expectedUri2))
..add(PendingDynamicLinkData(link: expectedUri1));
});
group('with default FirebaseDynamicLinks', () {
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
final mock = MockFirebaseCore();
Firebase.delegatePackingProperty = mock;
final platformApp = FirebaseAppPlatform(
'testAppName',
const FirebaseOptions(
apiKey: 'apiKey',
appId: 'appId',
messagingSenderId: 'messagingSenderId',
projectId: 'projectId',
),
);
when(() => mock.apps).thenReturn([platformApp]);
when(() => mock.app(any())).thenReturn(platformApp);
when(
() => mock.initializeApp(
name: any(named: 'name'),
options: any(named: 'options'),
),
).thenAnswer((_) => Future.value(platformApp));
});
tearDown(() {
Firebase.delegatePackingProperty = null;
});
test('can be instantiated', () async {
await Firebase.initializeApp();
expect(DeepLinkClient.new, returnsNormally);
});
});
});
group('DeepLinkClientFailure', () {
final error = Exception('errorMessage');
test('has correct props', () {
expect(
DeepLinkClientFailure(error).props,
[error],
);
});
});
}
| news_toolkit/flutter_news_example/packages/deep_link_client/test/deep_link_client_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/deep_link_client/test/deep_link_client_test.dart",
"repo_id": "news_toolkit",
"token_count": 1667
} | 957 |
// ignore_for_file: prefer_const_constructors
import 'package:form_inputs/form_inputs.dart';
import 'package:test/test.dart';
void main() {
const emailString = 'test@gmail.com';
group('Email', () {
group('constructors', () {
test('pure creates correct instance', () {
final email = Email.pure();
expect(email.value, '');
expect(email.isPure, true);
});
test('dirty creates correct instance', () {
final email = Email.dirty(emailString);
expect(email.value, emailString);
expect(email.isPure, false);
});
});
group('validator', () {
test('returns invalid error when email is empty', () {
expect(
Email.dirty().error,
EmailValidationError.invalid,
);
});
test('returns invalid error when email is malformed', () {
expect(
Email.dirty('test').error,
EmailValidationError.invalid,
);
});
test('is valid when email is valid', () {
expect(
Email.dirty(emailString).error,
isNull,
);
});
});
});
}
| news_toolkit/flutter_news_example/packages/form_inputs/test/email_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/form_inputs/test/email_test.dart",
"repo_id": "news_toolkit",
"token_count": 488
} | 958 |
export 'src/article_introduction.dart';
export 'src/banner_ad.dart' show BannerAd;
export 'src/block_action_callback.dart';
export 'src/divider_horizontal.dart';
export 'src/html.dart' show Html;
export 'src/image.dart';
export 'src/newsletter/index.dart' hide NewsletterContainer;
export 'src/post_grid.dart';
export 'src/post_large/index.dart';
export 'src/post_medium/index.dart';
export 'src/post_small.dart';
export 'src/section_header.dart';
export 'src/slideshow.dart';
export 'src/slideshow_introduction.dart' show SlideshowIntroduction;
export 'src/spacer.dart';
export 'src/text_caption.dart';
export 'src/text_headline.dart';
export 'src/text_lead_paragraph.dart';
export 'src/text_paragraph.dart';
export 'src/trending_story.dart';
export 'src/video.dart';
export 'src/video_introduction.dart';
export 'src/widgets/widgets.dart'
show AdsRetryPolicy, BannerAdContent, ShareButton;
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/news_blocks_ui.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/news_blocks_ui.dart",
"repo_id": "news_toolkit",
"token_count": 324
} | 959 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template post_large_image}
/// Block post large image widget.
/// {@endtemplate}
class PostLargeImage extends StatelessWidget {
/// {@macro post_large_image}
const PostLargeImage({
required this.imageUrl,
required this.isContentOverlaid,
required this.isLocked,
super.key,
});
/// The url of image displayed in this post.
final String imageUrl;
/// Whether this image is displayed in overlay.
final bool isContentOverlaid;
/// Whether this image displays lock icon.
final bool isLocked;
@override
Widget build(BuildContext context) {
return Stack(
children: [
if (isContentOverlaid)
OverlaidImage(
imageUrl: imageUrl,
gradientColor: AppColors.black.withOpacity(0.7),
)
else
InlineImage(imageUrl: imageUrl),
if (isLocked) const LockIcon(),
],
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_large/post_large_image.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_large/post_large_image.dart",
"repo_id": "news_toolkit",
"token_count": 396
} | 960 |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart' hide ProgressIndicator;
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
/// {@template video}
/// A reusable video news block widget.
/// {@endtemplate}
class Video extends StatelessWidget {
/// {@macro video}
const Video({required this.block, super.key});
/// The associated [VideoBlock] instance.
final VideoBlock block;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: InlineVideo(
videoUrl: block.videoUrl,
progressIndicator: const ProgressIndicator(),
),
);
}
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/video.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/video.dart",
"repo_id": "news_toolkit",
"token_count": 258
} | 961 |
export 'ads_retry_policy.dart';
export 'banner_ad_container.dart';
export 'banner_ad_content.dart';
export 'inline_image.dart';
export 'inline_video.dart';
export 'lock_icon.dart';
export 'overlaid_image.dart';
export 'post_content.dart';
export 'post_content_category.dart';
export 'post_content_premium_category.dart';
export 'post_footer.dart';
export 'progress_indicator.dart';
export 'share_button.dart';
export 'slideshow_category.dart';
| news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/widgets.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/widgets.dart",
"repo_id": "news_toolkit",
"token_count": 161
} | 962 |
// ignore_for_file: prefer_const_constructors
import 'dart:async';
import 'package:app_ui/app_ui.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks_ui/src/newsletter/index.dart';
import '../../helpers/helpers.dart';
void main() {
group('NewsletterSignUp', () {
testWidgets('renders correctly', (tester) async {
final widget = NewsletterSignUp(
headerText: 'header',
bodyText: 'body',
email: Text('email'),
buttonText: 'buttonText',
onPressed: null,
);
await tester.pumpApp(widget);
expect(find.byType(NewsletterSignUp), findsOneWidget);
});
testWidgets('onPressed is called on tap', (tester) async {
final completer = Completer<void>();
final widget = NewsletterSignUp(
headerText: 'header',
bodyText: 'body',
email: Text('email'),
buttonText: 'buttonText',
onPressed: completer.complete,
);
await tester.pumpApp(widget);
await tester.tap(find.byType(AppButton));
expect(completer.isCompleted, isTrue);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_sign_up_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_sign_up_test.dart",
"repo_id": "news_toolkit",
"token_count": 475
} | 963 |
// ignore_for_file: prefer_const_constructors
import 'dart:async';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/material.dart' hide ProgressIndicator;
import 'package:flutter_test/flutter_test.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import 'package:platform/platform.dart';
import '../../helpers/helpers.dart';
class MockBannerAd extends Mock implements BannerAd {}
class MockPlatform extends Mock implements Platform {}
class MockLoadAdError extends Mock implements LoadAdError {}
void main() {
group('BannerAdContent', () {
late AdSize capturedSize;
late String capturedAdUnitId;
late BannerAdListener capturedListener;
late Platform platform;
late BannerAd ad;
late BannerAdBuilder adBuilder;
setUp(() {
platform = MockPlatform();
when(() => platform.isAndroid).thenReturn(true);
when(() => platform.isIOS).thenReturn(false);
ad = MockBannerAd();
when(ad.load).thenAnswer((_) async {});
when(() => ad.size).thenReturn(AdSize.banner);
when(ad.dispose).thenAnswer((_) async {});
adBuilder = ({
required AdSize size,
required String adUnitId,
required BannerAdListener listener,
required AdRequest request,
}) {
capturedSize = size;
capturedAdUnitId = adUnitId;
capturedListener = listener;
return ad;
};
});
testWidgets(
'loads ad object correctly '
'on Android', (tester) async {
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
expect(capturedAdUnitId, equals(BannerAdContent.androidTestUnitId));
verify(ad.load).called(1);
});
testWidgets(
'loads ad object correctly '
'on iOS', (tester) async {
when(() => platform.isIOS).thenReturn(true);
when(() => platform.isAndroid).thenReturn(false);
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.anchoredAdaptive,
adBuilder: adBuilder,
currentPlatform: platform,
anchoredAdaptiveAdSizeProvider: (orientation, width) async =>
AnchoredAdaptiveBannerAdSize(
Orientation.portrait,
width: 100,
height: 100,
),
),
);
expect(capturedAdUnitId, equals(BannerAdContent.iosTestUnitAd));
verify(ad.load).called(1);
});
testWidgets(
'loads ad object correctly '
'with provided adUnitId', (tester) async {
const adUnitId = 'adUnitId';
await tester.pumpApp(
BannerAdContent(
adUnitId: adUnitId,
size: BannerAdSize.anchoredAdaptive,
adBuilder: adBuilder,
currentPlatform: platform,
anchoredAdaptiveAdSizeProvider: (orientation, width) async =>
AnchoredAdaptiveBannerAdSize(
Orientation.portrait,
width: 100,
height: 100,
),
),
);
expect(capturedAdUnitId, equals(adUnitId));
verify(ad.load).called(1);
});
testWidgets(
'renders ProgressIndicator '
'when ad is loading '
'and showProgressIndicator is true', (tester) async {
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
expect(find.byType(ProgressIndicator), findsOneWidget);
expect(find.byType(AdWidget), findsNothing);
});
testWidgets(
'does not render ProgressIndicator '
'when ad is loading '
'and showProgressIndicator is false', (tester) async {
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
showProgressIndicator: false,
),
);
expect(find.byType(ProgressIndicator), findsNothing);
expect(find.byType(AdWidget), findsNothing);
});
testWidgets('renders AdWidget when ad is loaded', (tester) async {
await tester.runAsync(() async {
ad = BannerAd(
size: AdSize.banner,
adUnitId: BannerAdContent.androidTestUnitId,
listener: BannerAdListener(),
request: AdRequest(),
);
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
capturedListener.onAdLoaded!(ad);
await tester.pumpAndSettle();
expect(find.byType(AdWidget), findsOneWidget);
expect(find.byType(ProgressIndicator), findsNothing);
});
});
testWidgets('uses AdSize.banner for BannerAdSize.normal', (tester) async {
const expectedSize = AdSize.banner;
when(() => ad.size).thenReturn(expectedSize);
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
expect(capturedSize, equals(expectedSize));
expect(
find.byWidgetPredicate(
(widget) =>
widget.key == Key('bannerAdContent_sizedBox') &&
widget is SizedBox &&
widget.width == expectedSize.width &&
widget.height == expectedSize.height,
),
findsOneWidget,
);
});
testWidgets('uses AdSize.mediumRectangle for BannerAdSize.large',
(tester) async {
const expectedSize = AdSize.mediumRectangle;
when(() => ad.size).thenReturn(expectedSize);
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.large,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
expect(capturedSize, equals(expectedSize));
expect(
find.byWidgetPredicate(
(widget) =>
widget.key == Key('bannerAdContent_sizedBox') &&
widget is SizedBox &&
widget.width == expectedSize.width &&
widget.height == expectedSize.height,
),
findsOneWidget,
);
});
testWidgets('uses AdSize(300, 600) for BannerAdSize.extraLarge',
(tester) async {
const expectedSize = AdSize(width: 300, height: 600);
when(() => ad.size).thenReturn(expectedSize);
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.extraLarge,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
expect(capturedSize, equals(expectedSize));
expect(
find.byWidgetPredicate(
(widget) =>
widget.key == Key('bannerAdContent_sizedBox') &&
widget is SizedBox &&
widget.width == expectedSize.width &&
widget.height == expectedSize.height,
),
findsOneWidget,
);
});
testWidgets('disposes ad object on widget dispose', (tester) async {
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
),
);
// Pump another widget so the tested widget is disposed.
await tester.pumpApp(SizedBox());
verify(ad.dispose).called(1);
});
testWidgets(
'retries loading ad based on AdsRetryPolicy '
'and renders placeholder '
'when ad fails to load', (tester) async {
final fakeAsync = FakeAsync();
const adFailedToLoadTitle = 'adFailedToLoadTitle';
final adsRetryPolicy = AdsRetryPolicy();
adBuilder = ({
required AdSize size,
required String adUnitId,
required BannerAdListener listener,
required AdRequest request,
}) {
Future.microtask(
() => listener.onAdFailedToLoad!(
ad,
LoadAdError(0, 'domain', 'message', null),
),
);
return ad;
};
final errors = <Object>[];
FlutterError.onError = (error) => errors.add(error.exception);
unawaited(
fakeAsync.run((async) async {
await tester.pumpApp(
BannerAdContent(
adFailedToLoadTitle: adFailedToLoadTitle,
size: BannerAdSize.normal,
adBuilder: adBuilder,
currentPlatform: platform,
adsRetryPolicy: adsRetryPolicy,
),
);
await tester.pump();
expect(find.text(adFailedToLoadTitle), findsNothing);
for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++) {
await tester.pump();
expect(find.text(adFailedToLoadTitle), findsNothing);
async.elapse(adsRetryPolicy.getIntervalForRetry(i));
}
await tester.pump();
expect(find.text(adFailedToLoadTitle), findsOneWidget);
}),
);
fakeAsync.flushMicrotasks();
expect(
errors,
equals([
// Initial load attempt failure.
isA<BannerAdFailedToLoadException>(),
// Retry load attempt failures.
for (var i = 1; i <= adsRetryPolicy.maxRetryCount; i++)
isA<BannerAdFailedToLoadException>(),
]),
);
});
testWidgets(
'throws BannerAdFailedToGetSizeException '
'for BannerAdSize.anchoredAdaptive '
'when ad size fails to load', (tester) async {
await tester.pumpApp(
BannerAdContent(
size: BannerAdSize.anchoredAdaptive,
adBuilder: adBuilder,
currentPlatform: platform,
anchoredAdaptiveAdSizeProvider: (orientation, width) async => null,
),
);
expect(
tester.takeException(),
isA<BannerAdFailedToGetSizeException>(),
);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/banner_ad_content_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/banner_ad_content_test.dart",
"repo_id": "news_toolkit",
"token_count": 4545
} | 964 |
// ignore_for_file: unnecessary_const, prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:news_blocks_ui/src/widgets/widgets.dart';
import '../../helpers/helpers.dart';
void main() {
group('SlideshowCategory', () {
testWidgets('renders slideshow text in uppercase', (tester) async {
final slideshowCategory = SlideshowCategory(
slideshowText: 'slideshowText',
);
await tester.pumpContentThemedApp(slideshowCategory);
expect(
find.text(slideshowCategory.slideshowText.toUpperCase()),
findsOneWidget,
);
});
});
}
| news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/slideshow_category_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/slideshow_category_test.dart",
"repo_id": "news_toolkit",
"token_count": 235
} | 965 |
# notifications_client
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
A Generic Notifications Client Interface.
| news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/README.md/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_client/notifications_client/README.md",
"repo_id": "news_toolkit",
"token_count": 61
} | 966 |
export 'src/notifications_repository.dart';
| news_toolkit/flutter_news_example/packages/notifications_repository/lib/notifications_repository.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/lib/notifications_repository.dart",
"repo_id": "news_toolkit",
"token_count": 15
} | 967 |
export 'src/permission_client.dart';
| news_toolkit/flutter_news_example/packages/permission_client/lib/permission_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/permission_client/lib/permission_client.dart",
"repo_id": "news_toolkit",
"token_count": 13
} | 968 |
import 'package:equatable/equatable.dart';
import 'package:share_plus/share_plus.dart';
/// {@template share_failure}
/// A failure for the share launcher failures.
/// {@endtemplate}
class ShareFailure with EquatableMixin implements Exception {
/// {@macro share_failure}
const ShareFailure(this.error);
/// The error which was caught.
final Object error;
@override
List<Object?> get props => [error];
}
/// ShareProvider is a function type that provides the ability to share content.
typedef ShareProvider = Future<void> Function(String);
/// {@template share_launcher}
/// A class allowing opening native share bottom sheet.
/// {@endtemplate}
class ShareLauncher {
/// {@macro share_launcher}
const ShareLauncher({ShareProvider? shareProvider})
: _shareProvider = shareProvider ?? Share.share;
final ShareProvider _shareProvider;
/// Method for opening native share bottom sheet.
Future<void> share({required String text}) async {
try {
return _shareProvider(text);
} catch (error, stackTrace) {
Error.throwWithStackTrace(ShareFailure(error), stackTrace);
}
}
}
| news_toolkit/flutter_news_example/packages/share_launcher/lib/src/share_launcher.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/share_launcher/lib/src/share_launcher.dart",
"repo_id": "news_toolkit",
"token_count": 337
} | 969 |
import 'package:mocktail/mocktail.dart';
import 'package:storage/storage.dart';
import 'package:test/test.dart';
import 'package:user_repository/user_repository.dart';
class MockStorage extends Mock implements Storage {}
void main() {
group('UserStorage', () {
late Storage storage;
setUp(() {
storage = MockStorage();
when(
() => storage.write(
key: any(named: 'key'),
value: any(named: 'value'),
),
).thenAnswer((_) async {});
});
group('setNumberOfTimesAppOpened', () {
test('saves the value in Storage', () async {
const value = 1;
await UserStorage(storage: storage).setAppOpenedCount(count: value);
verify(
() => storage.write(
key: UserStorageKeys.appOpenedCount,
value: value.toString(),
),
).called(1);
});
});
group('fetchNumberOfTimesAppOpened', () {
test('returns the value from Storage', () async {
const value = 1;
when(
() => storage.read(key: UserStorageKeys.appOpenedCount),
).thenAnswer((_) async => 1.toString());
final result =
await UserStorage(storage: storage).fetchAppOpenedCount();
verify(
() => storage.read(
key: UserStorageKeys.appOpenedCount,
),
).called(1);
expect(result, value);
});
test('returns 0 when no value exists in UserStorage', () async {
when(
() => storage.read(key: UserStorageKeys.appOpenedCount),
).thenAnswer((_) async => null);
final result =
await UserStorage(storage: storage).fetchAppOpenedCount();
verify(
() => storage.read(
key: UserStorageKeys.appOpenedCount,
),
).called(1);
expect(result, 0);
});
});
});
}
| news_toolkit/flutter_news_example/packages/user_repository/test/src/user_storage_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/packages/user_repository/test/src/user_storage_test.dart",
"repo_id": "news_toolkit",
"token_count": 836
} | 970 |
// ignore_for_file: prefer_const_constructors
import 'package:analytics_repository/analytics_repository.dart';
import 'package:flutter_news_example/article/article.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('ArticleEvent', () {
group('ArticleRequested', () {
test('supports value comparisons', () {
final event1 = ArticleRequested();
final event2 = ArticleRequested();
expect(event1, equals(event2));
});
});
group('ArticleContentSeen', () {
test('supports value comparisons', () {
final event1 = ArticleContentSeen(contentIndex: 10);
final event2 = ArticleContentSeen(contentIndex: 10);
expect(event1, equals(event2));
});
});
group('ArticleRewardedAdWatched', () {
test('supports value comparisons', () {
final event1 = ArticleRewardedAdWatched();
final event2 = ArticleRewardedAdWatched();
expect(event1, equals(event2));
});
});
group('ArticleCommented', () {
test('supports value comparisons', () {
final event1 = ArticleCommented(articleTitle: 'title');
final event2 = ArticleCommented(articleTitle: 'title');
expect(event1, equals(event2));
});
test('has ArticleCommentEvent', () {
expect(
ArticleCommented(articleTitle: 'title'),
isA<AnalyticsEventMixin>().having(
(event) => event.event,
'event',
equals(ArticleCommentEvent(articleTitle: 'title')),
),
);
});
});
group('ShareRequested', () {
test('supports value comparisons', () {
final event1 = ShareRequested(uri: Uri(path: 'text'));
final event2 = ShareRequested(uri: Uri(path: 'text'));
expect(event1, equals(event2));
});
test('has SocialShareEvent', () {
expect(
ShareRequested(uri: Uri(path: 'text')),
isA<AnalyticsEventMixin>().having(
(event) => event.event,
'event',
equals(SocialShareEvent()),
),
);
});
});
});
}
| news_toolkit/flutter_news_example/test/article/bloc/article_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/article/bloc/article_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 899
} | 971 |
// ignore_for_file: prefer_const_constructors
// ignore_for_file: prefer_const_literals_to_create_immutables
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_news_example/feed/feed.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_blocks/news_blocks.dart';
import 'package:news_repository/news_repository.dart';
import '../../helpers/helpers.dart';
class MockNewsRepository extends Mock implements NewsRepository {}
void main() {
initMockHydratedStorage();
group('FeedBloc', () {
late NewsRepository newsRepository;
late FeedBloc feedBloc;
final feedResponse = FeedResponse(
feed: [
SectionHeaderBlock(title: 'title'),
DividerHorizontalBlock(),
],
totalCount: 4,
);
final feedStatePopulated = FeedState(
status: FeedStatus.populated,
feed: {
Category.entertainment: [
SpacerBlock(spacing: Spacing.medium),
DividerHorizontalBlock(),
],
Category.health: [
DividerHorizontalBlock(),
],
},
hasMoreNews: {
Category.entertainment: true,
Category.health: false,
},
);
setUp(() async {
newsRepository = MockNewsRepository();
feedBloc = FeedBloc(newsRepository: newsRepository);
});
test('can be (de)serialized', () {
final serialized = feedBloc.toJson(feedStatePopulated);
final deserialized = feedBloc.fromJson(serialized!);
expect(deserialized, feedStatePopulated);
});
group('FeedRequested', () {
blocTest<FeedBloc, FeedState>(
'emits [loading, populated] '
'when getFeed succeeds '
'and there are more news to fetch',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
limit: any(named: 'limit'),
),
).thenAnswer((_) async => feedResponse),
build: () => feedBloc,
act: (bloc) => bloc.add(
FeedRequested(category: Category.entertainment),
),
expect: () => <FeedState>[
FeedState(status: FeedStatus.loading),
FeedState(
status: FeedStatus.populated,
feed: {
Category.entertainment: feedResponse.feed,
},
hasMoreNews: {
Category.entertainment: true,
},
),
],
);
blocTest<FeedBloc, FeedState>(
'emits [loading, populated] '
'with appended feed for the given category '
'when getFeed succeeds '
'and there are no more news to fetch',
seed: () => feedStatePopulated,
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
limit: any(named: 'limit'),
),
).thenAnswer((_) async => feedResponse),
build: () => feedBloc,
act: (bloc) => bloc.add(
FeedRequested(category: Category.entertainment),
),
expect: () => <FeedState>[
feedStatePopulated.copyWith(status: FeedStatus.loading),
feedStatePopulated.copyWith(
status: FeedStatus.populated,
feed: feedStatePopulated.feed
..addAll({
Category.entertainment: [
...feedStatePopulated.feed[Category.entertainment]!,
...feedResponse.feed,
],
}),
hasMoreNews: feedStatePopulated.hasMoreNews
..addAll({
Category.entertainment: false,
}),
)
],
);
blocTest<FeedBloc, FeedState>(
'emits [loading, error] '
'when getFeed fails',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
limit: any(named: 'limit'),
),
).thenThrow(Exception()),
build: () => feedBloc,
act: (bloc) => bloc.add(
FeedRequested(category: Category.entertainment),
),
expect: () => <FeedState>[
FeedState(status: FeedStatus.loading),
FeedState(status: FeedStatus.failure),
],
);
});
group('FeedRefreshRequested', () {
blocTest<FeedBloc, FeedState>(
'emits [loading, populated] '
'when getFeed succeeds '
'and there is more news to fetch',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
),
).thenAnswer((_) async => feedResponse),
build: () => feedBloc,
act: (bloc) => bloc.add(
FeedRefreshRequested(category: Category.entertainment),
),
expect: () => <FeedState>[
FeedState(status: FeedStatus.loading),
FeedState(
status: FeedStatus.populated,
feed: {
Category.entertainment: feedResponse.feed,
},
hasMoreNews: {
Category.entertainment: true,
},
),
],
);
blocTest<FeedBloc, FeedState>(
'emits [loading, error] '
'when getFeed fails',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
),
).thenThrow(Exception()),
build: () => feedBloc,
act: (bloc) => bloc.add(
FeedRefreshRequested(category: Category.entertainment),
),
expect: () => <FeedState>[
FeedState(status: FeedStatus.loading),
FeedState(status: FeedStatus.failure),
],
);
});
group('FeedResumed', () {
blocTest<FeedBloc, FeedState>(
'emits [populated] '
'when getFeed succeeds '
'and there are more news to fetch for a single category',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
limit: any(named: 'limit'),
),
).thenAnswer((_) async => feedResponse),
build: () => feedBloc,
seed: () => FeedState(
status: FeedStatus.populated,
feed: {Category.top: []},
),
act: (bloc) => bloc.add(FeedResumed()),
expect: () => <FeedState>[
FeedState(
status: FeedStatus.populated,
feed: {
Category.top: feedResponse.feed,
},
hasMoreNews: {
Category.top: true,
},
),
],
verify: (_) {
verify(
() => newsRepository.getFeed(
category: Category.top,
offset: 0,
),
).called(1);
},
);
blocTest<FeedBloc, FeedState>(
'emits [populated] '
'when getFeed succeeds '
'and there are more news to fetch for multiple category',
setUp: () => when(
() => newsRepository.getFeed(
category: any(named: 'category'),
offset: any(named: 'offset'),
limit: any(named: 'limit'),
),
).thenAnswer((_) async => feedResponse),
build: () => feedBloc,
seed: () => FeedState(
status: FeedStatus.populated,
feed: {Category.top: [], Category.technology: []},
),
act: (bloc) => bloc.add(FeedResumed()),
expect: () => <FeedState>[
FeedState(
status: FeedStatus.populated,
feed: {
Category.top: feedResponse.feed,
Category.technology: [],
},
hasMoreNews: {
Category.top: true,
},
),
FeedState(
status: FeedStatus.populated,
feed: {
Category.top: feedResponse.feed,
Category.technology: feedResponse.feed,
},
hasMoreNews: {
Category.top: true,
Category.technology: true,
},
),
],
verify: (_) {
verify(
() => newsRepository.getFeed(category: Category.top, offset: 0),
).called(1);
verify(
() => newsRepository.getFeed(
category: Category.technology,
offset: 0,
),
).called(1);
},
);
});
});
}
| news_toolkit/flutter_news_example/test/feed/bloc/feed_bloc_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/feed/bloc/feed_bloc_test.dart",
"repo_id": "news_toolkit",
"token_count": 4271
} | 972 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LoginEvent', () {
group('LoginEmailChanged', () {
test('supports value comparisons', () {
expect(
LoginEmailChanged('test@gmail.com'),
LoginEmailChanged('test@gmail.com'),
);
expect(
LoginEmailChanged(''),
isNot(LoginEmailChanged('test@gmail.com')),
);
});
});
group('SendEmailLinkSubmitted', () {
test('supports value comparisons', () {
expect(SendEmailLinkSubmitted(), SendEmailLinkSubmitted());
});
});
group('LoginGoogleSubmitted', () {
test('supports value comparisons', () {
expect(LoginGoogleSubmitted(), LoginGoogleSubmitted());
});
});
group('LoginTwitterSubmitted', () {
test('supports value comparisons', () {
expect(LoginTwitterSubmitted(), LoginTwitterSubmitted());
});
});
group('LoginFacebookSubmitted', () {
test('supports value comparisons', () {
expect(LoginFacebookSubmitted(), LoginFacebookSubmitted());
});
});
group('LoginAppleSubmitted', () {
test('supports value comparisons', () {
expect(LoginAppleSubmitted(), LoginAppleSubmitted());
});
});
});
}
| news_toolkit/flutter_news_example/test/login/bloc/login_event_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/login/bloc/login_event_test.dart",
"repo_id": "news_toolkit",
"token_count": 531
} | 973 |
// ignore_for_file: prefer_const_constructors
import 'package:app_ui/app_ui.dart';
import 'package:flutter_news_example/navigation/navigation.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
void main() {
group('NavDrawerSubscribe', () {
testWidgets('renders NavDrawerSubscribeTitle', (tester) async {
await tester.pumpApp(NavDrawerSubscribe());
expect(find.byType(NavDrawerSubscribeTitle), findsOneWidget);
});
testWidgets('renders NavDrawerSubscribeSubtitle', (tester) async {
await tester.pumpApp(NavDrawerSubscribe());
expect(find.byType(NavDrawerSubscribeSubtitle), findsOneWidget);
});
testWidgets('renders NavDrawerSubscribeButton', (tester) async {
await tester.pumpApp(NavDrawerSubscribe());
expect(find.byType(NavDrawerSubscribeButton), findsOneWidget);
});
group('NavDrawerSubscribeButton', () {
testWidgets('renders AppButton', (tester) async {
await tester.pumpApp(NavDrawerSubscribeButton());
expect(find.byType(AppButton), findsOneWidget);
});
testWidgets('opens PurchaseSubscriptionDialog when tapped',
(tester) async {
final inAppPurchaseRepository = MockInAppPurchaseRepository();
when(
() => inAppPurchaseRepository.purchaseUpdate,
).thenAnswer((_) => Stream.empty());
when(
inAppPurchaseRepository.fetchSubscriptions,
).thenAnswer((_) async => []);
await tester.pumpApp(
NavDrawerSubscribeButton(),
inAppPurchaseRepository: inAppPurchaseRepository,
);
await tester.tap(find.byType(NavDrawerSubscribeButton));
await tester.pump();
expect(find.byType(PurchaseSubscriptionDialog), findsOneWidget);
});
});
});
}
| news_toolkit/flutter_news_example/test/navigation/widgets/nav_drawer_subscribe_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/navigation/widgets/nav_drawer_subscribe_test.dart",
"repo_id": "news_toolkit",
"token_count": 742
} | 974 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_news_example/search/search.dart';
import 'package:flutter_news_example_api/client.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:news_repository/news_repository.dart';
class MockNewsRepository extends Mock implements NewsRepository {}
void main() {
group('SearchBloc', () {
late NewsRepository newsRepository;
const popularResponseSuccess = PopularSearchResponse(
articles: [DividerHorizontalBlock()],
topics: ['test'],
);
const relevantResponseSuccess = RelevantSearchResponse(
articles: [DividerHorizontalBlock()],
topics: ['test'],
);
setUpAll(() {
newsRepository = MockNewsRepository();
});
group('on SearchTermChanged with empty search term', () {
blocTest<SearchBloc, SearchState>(
'emits [loading, populated] '
'with articles and topics '
'when popularSearch succeeds.',
setUp: () => when(() => newsRepository.popularSearch()).thenAnswer(
(_) async => popularResponseSuccess,
),
build: () => SearchBloc(newsRepository: newsRepository),
act: (bloc) => bloc.add(SearchTermChanged()),
expect: () => <SearchState>[
const SearchState.initial().copyWith(status: SearchStatus.loading),
const SearchState.initial().copyWith(
status: SearchStatus.populated,
articles: popularResponseSuccess.articles,
topics: popularResponseSuccess.topics,
),
],
);
blocTest<SearchBloc, SearchState>(
'emits [loading, failure] '
'when popularSearch throws.',
setUp: () => when(() => newsRepository.popularSearch())
.thenThrow(PopularSearchFailure),
build: () => SearchBloc(newsRepository: newsRepository),
act: (bloc) => bloc.add(SearchTermChanged()),
expect: () => <SearchState>[
const SearchState.initial().copyWith(
status: SearchStatus.loading,
searchType: SearchType.popular,
),
const SearchState.initial().copyWith(
status: SearchStatus.failure,
searchType: SearchType.popular,
),
],
);
});
group('on SearchTermChanged', () {
blocTest<SearchBloc, SearchState>(
'emits [loading, populated] '
'with articles and topics '
'and awaited debounce time '
'when relevantSearch succeeds',
setUp: () => when(
() => newsRepository.relevantSearch(
term: any(named: 'term'),
),
).thenAnswer(
(_) async => relevantResponseSuccess,
),
build: () => SearchBloc(newsRepository: newsRepository),
act: (bloc) {
bloc.add(SearchTermChanged(searchTerm: 'term'));
},
wait: const Duration(milliseconds: 300),
expect: () => <SearchState>[
SearchState(
status: SearchStatus.loading,
articles: const [],
topics: const [],
searchType: SearchType.relevant,
),
SearchState(
status: SearchStatus.populated,
articles: popularResponseSuccess.articles,
topics: popularResponseSuccess.topics,
searchType: SearchType.relevant,
),
],
);
blocTest<SearchBloc, SearchState>(
'emits [loading, failure] '
'when relevantSearch throws.',
setUp: () => when(
() => newsRepository.relevantSearch(
term: any(named: 'term'),
),
).thenThrow(RelevantSearchFailure),
build: () => SearchBloc(newsRepository: newsRepository),
act: (bloc) => bloc.add(SearchTermChanged(searchTerm: 'term')),
wait: const Duration(milliseconds: 300),
expect: () => <SearchState>[
SearchState(
status: SearchStatus.loading,
articles: const [],
topics: const [],
searchType: SearchType.relevant,
),
SearchState(
status: SearchStatus.failure,
articles: const [],
topics: const [],
searchType: SearchType.relevant,
),
],
);
});
});
}
| news_toolkit/flutter_news_example/test/search/bloc/search_bloc_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/search/bloc/search_bloc_test.dart",
"repo_id": "news_toolkit",
"token_count": 1899
} | 975 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/login/login.dart';
import 'package:flutter_news_example/subscriptions/subscriptions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_repository/in_app_purchase_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:user_repository/user_repository.dart';
import '../../helpers/pump_app.dart';
class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {}
class MockSubscriptionsBloc
extends MockBloc<SubscriptionsEvent, SubscriptionsState>
implements SubscriptionsBloc {}
class MockUser extends Mock implements User {}
void main() {
group('SubscriptionCard', () {
const subscription = Subscription(
id: 'dd339fda-33e9-49d0-9eb5-0ccb77eb760f',
name: SubscriptionPlan.premium,
cost: SubscriptionCost(
annual: 16200,
monthly: 1499,
),
benefits: [
'first',
'second',
'third',
],
);
group('when isExpanded is true', () {
testWidgets('renders correctly', (tester) async {
await tester.pumpApp(
const SubscriptionCard(
isExpanded: true,
subscription: subscription,
),
);
for (final benefit in subscription.benefits) {
expect(find.byKey(ValueKey(benefit)), findsOneWidget);
}
expect(
find.byKey(const Key('subscriptionCard_subscribe_appButton')),
findsOneWidget,
);
expect(
find.byKey(const Key('subscriptionCard_viewDetails_appButton')),
findsNothing,
);
});
testWidgets(
'adds SubscriptionPurchaseRequested to SubscriptionsBloc '
'on subscribeButton tap '
'when user is logged in', (tester) async {
final inAppPurchaseRepository = MockInAppPurchaseRepository();
final appBloc = MockAppBloc();
final SubscriptionsBloc subscriptionsBloc = MockSubscriptionsBloc();
final user = MockUser();
when(() => user.subscriptionPlan).thenReturn(SubscriptionPlan.premium);
when(() => appBloc.state).thenAnswer(
(_) => AppState.authenticated(user),
);
when(() => subscriptionsBloc.state).thenAnswer(
(_) => SubscriptionsState.initial(),
);
await tester.pumpApp(
BlocProvider.value(
value: subscriptionsBloc,
child: Builder(
builder: (context) {
return const SubscriptionCard(
isExpanded: true,
subscription: subscription,
);
},
),
),
appBloc: appBloc,
inAppPurchaseRepository: inAppPurchaseRepository,
);
await tester
.tap(find.byKey(const Key('subscriptionCard_subscribe_appButton')));
await tester.pumpAndSettle();
verify(
() => subscriptionsBloc.add(
SubscriptionPurchaseRequested(
subscription: subscription,
),
),
).called(1);
});
testWidgets(
'shows LoginModal '
'on subscribeButton tap '
'when user is not logged in', (tester) async {
final inAppPurchaseRepository = MockInAppPurchaseRepository();
final appBloc = MockAppBloc();
final SubscriptionsBloc subscriptionsBloc = MockSubscriptionsBloc();
when(() => appBloc.state).thenAnswer(
(_) => AppState.unauthenticated(),
);
when(() => subscriptionsBloc.state).thenAnswer(
(_) => SubscriptionsState.initial(),
);
await tester.pumpApp(
BlocProvider.value(
value: subscriptionsBloc,
child: Builder(
builder: (context) {
return const SubscriptionCard(
isExpanded: true,
subscription: subscription,
);
},
),
),
appBloc: appBloc,
inAppPurchaseRepository: inAppPurchaseRepository,
);
await tester
.tap(find.byKey(const Key('subscriptionCard_subscribe_appButton')));
await tester.pumpAndSettle();
expect(find.byType(LoginModal), findsOneWidget);
});
});
group('when isExpanded is false', () {
testWidgets('renders correctly', (tester) async {
await tester.pumpApp(
const SubscriptionCard(
subscription: subscription,
),
);
for (final benefit in subscription.benefits) {
expect(find.byKey(ValueKey(benefit)), findsOneWidget);
}
expect(
find.byKey(const Key('subscriptionCard_subscribe_appButton')),
findsNothing,
);
expect(
find.byKey(const Key('subscriptionCard_viewDetails_appButton')),
findsOneWidget,
);
});
testWidgets('shows SnackBar on viewDetails tap', (tester) async {
await tester.pumpApp(
const SubscriptionCard(
subscription: subscription,
),
);
final snackBarFinder = find.byKey(
const Key(
'subscriptionCard_unimplemented_snackBar',
),
);
expect(snackBarFinder, findsNothing);
await tester.tap(
find.byKey(const Key('subscriptionCard_viewDetails_appButton')),
);
await tester.pump();
expect(snackBarFinder, findsOneWidget);
});
});
testWidgets('renders bestValue Icon when isBestValue is true',
(tester) async {
await tester.pumpApp(
const SubscriptionCard(
isBestValue: true,
subscription: subscription,
),
);
expect(
find.byKey(const Key('subscriptionCard_bestValueSvg')),
findsOneWidget,
);
});
});
}
| news_toolkit/flutter_news_example/test/subscriptions/widgets/subscription_card_test.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/test/subscriptions/widgets/subscription_card_test.dart",
"repo_id": "news_toolkit",
"token_count": 2830
} | 976 |
#!/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
# Allow analyzing packages that use a dev dependency with a higher minimum
# Flutter/Dart version than the package itself. Non-client code doesn't need to
# work in legacy versions.
#
# This requires the --lib-only flag below.
.ci/scripts/tool_runner.sh remove-dev-dependencies
# This uses --run-on-dirty-packages rather than --packages-for-branch
# since only the packages changed by 'make-deps-path-based' need to be
# re-checked.
.ci/scripts/tool_runner.sh analyze --lib-only \
--skip-if-not-supporting-flutter-version="$CHANNEL" \
--custom-analysis=script/configs/custom_analysis.yaml
# Restore the tree to a clean state, to avoid accidental issues if
# other script steps are added to the enclosing task.
git checkout .
| packages/.ci/scripts/analyze_legacy.sh/0 | {
"file_path": "packages/.ci/scripts/analyze_legacy.sh",
"repo_id": "packages",
"token_count": 269
} | 977 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: Dart unit tests
script: .ci/scripts/tool_runner.sh
args: ["dart-test", "--exclude=script/configs/dart_unit_tests_exceptions.yaml", "--platform=vm"]
# Re-run tests with path-based dependencies to ensure that publishing
# the changes won't break tests of other packages in the respository
# that depend on it.
- name: Dart unit tests - pathified
script: .ci/scripts/dart_unit_tests_pathified.sh
args: ["--platform=vm"]
| packages/.ci/targets/dart_unit_tests.yaml/0 | {
"file_path": "packages/.ci/targets/dart_unit_tests.yaml",
"repo_id": "packages",
"token_count": 207
} | 978 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
infra_step: true # Note infra steps failing prevents "always" from running.
- name: download Dart deps
script: .ci/scripts/tool_runner.sh
args: ["fetch-deps", "--windows", "--supporting-target-platforms-only"]
infra_step: true
- name: build examples (Win32)
script: .ci/scripts/build_examples_win32.sh
- name: native unit tests (Win32)
script: .ci/scripts/native_test_win32.sh
- name: drive examples (Win32)
script: .ci/scripts/drive_examples_win32.sh
| packages/.ci/targets/windows_build_and_platform_tests.yaml/0 | {
"file_path": "packages/.ci/targets/windows_build_and_platform_tests.yaml",
"repo_id": "packages",
"token_count": 208
} | 979 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Updates support matrix in README to indicate that iOS 11 is no longer supported.
* Clients on versions of Flutter that still support iOS 11 can continue to use this
package with iOS 11, but will not receive any further updates to the iOS implementation.
## 0.10.5+9
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 0.10.5+8
* Fixes new lint warnings.
## 0.10.5+7
* Updates example app to use non-deprecated video_player method.
## 0.10.5+6
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Drop unused dependency on `package:quiver`.
## 0.10.5+5
* Fixes bug where old camera resources were not disposed when switching between camera descriptions.
* Fixes bug where _deviceOrientationSubscription was recreated every time the camera description was
changed.
## 0.10.5+4
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.10.5+3
* Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters.
## 0.10.5+2
* Fixes unawaited_futures violations.
## 0.10.5+1
* Removes obsolete null checks on non-nullable values.
## 0.10.5
* Adds NV21 as an image streaming option for Android.
## 0.10.4
* Allows camera to be switched while video recording.
* Updates minimum Flutter version to 3.3.
* Aligns Dart and Flutter SDK constraints.
## 0.10.3+2
* Updates iOS minimum version in README.
## 0.10.3+1
* Updates links for the merge of flutter/plugins into flutter/packages.
## 0.10.3
* Adds back use of Optional type.
## 0.10.2+1
* Updates code for stricter lint checks.
## 0.10.2
* Implements option to also stream when recording a video.
## 0.10.1
* Remove usage of deprecated quiver Optional type.
## 0.10.0+5
* Updates code for stricter lint checks.
## 0.10.0+4
* Removes usage of `_ambiguate` method in example.
* Updates minimum Flutter version to 3.0.
## 0.10.0+3
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
## 0.10.0+2
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 0.10.0+1
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 0.10.0
* **Breaking Change** Bumps default camera_web package version, which updates permission exception code from `cameraPermission` to `CameraAccessDenied`.
* **Breaking Change** Bumps default camera_android package version, which updates permission exception code from `cameraPermission` to
`CameraAccessDenied` and `AudioAccessDenied`.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 0.9.8+1
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.9.8
* Moves Android and iOS implementations to federated packages.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231).
## 0.9.7+1
* Moves streaming implementation to the platform interface package.
## 0.9.7
* Returns all the available cameras on iOS.
## 0.9.6
* Adds audio access permission handling logic on iOS to fix an issue with `prepareForVideoRecording` not awaiting for the audio permission request result.
## 0.9.5+1
* Suppresses warnings for pre-iOS-11 codepaths.
## 0.9.5
* Adds camera access permission handling logic on iOS to fix a related crash when using the camera for the first time.
## 0.9.4+24
* Fixes preview orientation when pausing preview with locked orientation.
## 0.9.4+23
* Minor fixes for new analysis options.
## 0.9.4+22
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.9.4+21
* Fixes README code samples.
## 0.9.4+20
* Fixes an issue with the orientation of videos recorded in landscape on Android.
## 0.9.4+19
* Migrate deprecated Scaffold SnackBar methods to ScaffoldMessenger.
## 0.9.4+18
* Fixes a crash in iOS when streaming on low-performance devices.
## 0.9.4+17
* Removes obsolete information from README, and adds OS support table.
## 0.9.4+16
* Fixes a bug resulting in a `CameraAccessException` that prevents image
capture on some Android devices.
## 0.9.4+15
* Uses dispatch queue for pixel buffer synchronization on iOS.
* Minor iOS internal code cleanup related to queue helper functions.
## 0.9.4+14
* Restores compatibility with Flutter 2.5 and 2.8.
## 0.9.4+13
* Updates iOS camera's photo capture delegate reference on a background queue to prevent potential race conditions, and some related internal code cleanup.
## 0.9.4+12
* Skips unnecessary AppDelegate setup for unit tests on iOS.
* Internal code cleanup for stricter analysis options.
## 0.9.4+11
* Manages iOS camera's orientation-related states on a background queue to prevent potential race conditions.
## 0.9.4+10
* iOS performance improvement by moving file writing from the main queue to a background IO queue.
## 0.9.4+9
* iOS performance improvement by moving sample buffer handling from the main queue to a background session queue.
* Minor iOS internal code cleanup related to camera class and its delegate.
* Minor iOS internal code cleanup related to resolution preset, video format, focus mode, exposure mode and device orientation.
* Minor iOS internal code cleanup related to flash mode.
## 0.9.4+8
* Fixes a bug where ImageFormatGroup was ignored in `startImageStream` on iOS.
## 0.9.4+7
* Fixes a crash in iOS when passing null queue pointer into AVFoundation API due to race condition.
* Minor iOS internal code cleanup related to dispatch queue.
## 0.9.4+6
* Fixes a crash in iOS when using image stream due to calling Flutter engine API on non-main thread.
## 0.9.4+5
* Fixes bug where calling a method after the camera was closed resulted in a Java `IllegalStateException` exception.
* Fixes integration tests.
## 0.9.4+4
* Change Android compileSdkVersion to 31.
* Remove usages of deprecated Android API `CamcorderProfile`.
* Update gradle version to 7.0.2 on Android.
## 0.9.4+3
* Fix registerTexture and result being called on background thread on iOS.
## 0.9.4+2
* Updated package description;
* Refactor unit test on iOS to make it compatible with new restrictions in Xcode 13 which only supports the use of the `XCUIDevice` in Xcode UI tests.
## 0.9.4+1
* Fixed Android implementation throwing IllegalStateException when switching to a different activity.
## 0.9.4
* Add web support by endorsing `package:camera_web`.
## 0.9.3+1
* Remove iOS 9 availability check around ultra high capture sessions.
## 0.9.3
* Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0.
## 0.9.2+2
* Ensure that setting the exposure offset returns the new offset value on Android.
## 0.9.2+1
* Fixed camera controller throwing an exception when being replaced in the preview widget.
## 0.9.2
* Added functions to pause and resume the camera preview.
## 0.9.1+1
* Replace `device_info` reference with `device_info_plus` in the [README.md](README.md)
## 0.9.1
* Added `lensAperture`, `sensorExposureTime` and `sensorSensitivity` properties to the `CameraImage` dto.
## 0.9.0
* Complete rewrite of Android plugin to fix many capture, focus, flash, orientation and exposure issues.
* Fixed crash when opening front-facing cameras on some legacy android devices like Sony XZ.
* Android Flash mode works with full precapture sequence.
* Updated Android lint settings.
## 0.8.1+7
* Fix device orientation sometimes not affecting the camera preview orientation.
## 0.8.1+6
* Remove references to the Android V1 embedding.
## 0.8.1+5
* Make sure the `setFocusPoint` and `setExposurePoint` coordinates work correctly in all orientations on iOS (instead of only in portrait mode).
## 0.8.1+4
* Silenced warnings that may occur during build when using a very
recent version of Flutter relating to null safety.
## 0.8.1+3
* Do not change camera orientation when iOS device is flat.
## 0.8.1+2
* Fix iOS crash when selecting an unsupported FocusMode.
## 0.8.1+1
* Migrate maven repository from jcenter to mavenCentral.
## 0.8.1
* Solved a rotation issue on iOS which caused the default preview to be displayed as landscape right instead of portrait.
## 0.8.0
* Stable null safety release.
* Solved delay when using the zoom feature on iOS.
* Added a timeout to the pre-capture sequence on Android to prevent crashes when the camera cannot get a focus.
* Updates the example code listed in the [README.md](README.md), so it runs without errors when you simply copy/ paste it into a Flutter App.
## 0.7.0+4
* Fix crash when taking picture with orientation lock
## 0.7.0+3
* Clockwise rotation of focus point in android
## 0.7.0+2
* Fix example reference in README.
* Revert compileSdkVersion back to 29 (from 30) as this is causing problems with add-to-app configurations.
## 0.7.0+1
* Ensure communication from JAVA to Dart is done on the main UI thread.
## 0.7.0
* BREAKING CHANGE: `CameraValue.aspectRatio` now returns `width / height` rather than `height / width`. [(commit)](https://github.com/flutter/plugins/commit/100c7470d4066b1d0f8f7e4ec6d7c943e736f970)
* Added support for capture orientation locking on Android and iOS.
* Fixed camera preview not rotating correctly on Android and iOS.
* Fixed camera preview sometimes appearing stretched on Android and iOS.
* Fixed videos & photos saving with the incorrect rotation on iOS.
* New Features:
* Adds auto focus support for Android and iOS implementations. [(commmit)](https://github.com/flutter/plugins/commit/71a831790220f898bf8120c8a23840ac6e742db5)
* Adds ImageFormat selection for ImageStream and Video(iOS only). [(commit)](https://github.com/flutter/plugins/commit/da1b4638b750a5ff832d7be86a42831c42c6d6c0)
* Bug Fixes:
* Fixes crash when taking a picture on iOS devices without flash. [(commit)](https://github.com/flutter/plugins/commit/831344490984b1feec007afc9c8595d80b6c13f4)
* Make sure the configured zoom scale is copied over to the final capture builder on Android. Fixes the issue where the preview is zoomed but the final picture is not. [(commit)](https://github.com/flutter/plugins/commit/5916f55664e1772a4c3f0c02c5c71fc11e491b76)
* Fixes crash with using inner camera on some Android devices. [(commit)](https://github.com/flutter/plugins/commit/980b674cb4020c1927917426211a87e275346d5e)
* Improved error feedback by differentiating between uninitialized and disposed camera controllers. [(commit)](https://github.com/flutter/plugins/commit/d0b7109f6b00a0eda03506fed2c74cc123ffc6f3)
* Fixes picture captures causing a crash on some Huawei devices. [(commit)](https://github.com/flutter/plugins/commit/6d18db83f00f4861ffe485aba2d1f8aa08845ce6)
## 0.6.4+5
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
## 0.6.4+4
* Set camera auto focus enabled by default.
## 0.6.4+3
* Detect if selected camera supports auto focus and act accordingly on Android. This solves a problem where front facing cameras are not capturing the picture because auto focus is not supported.
## 0.6.4+2
* Set ImageStreamReader listener to null to prevent stale images when streaming images.
## 0.6.4+1
* Added closeCaptureSession() to stopVideoRecording in Camera.java to fix an Android 6 crash.
## 0.6.4
* Adds auto exposure support for Android and iOS implementations.
## 0.6.3+4
* Revert previous dependency update: Changed dependency on camera_platform_interface to >=1.04 <1.1.0.
## 0.6.3+3
* Updated dependency on camera_platform_interface to ^1.2.0.
## 0.6.3+2
* Fixes crash on Android which occurs after video recording has stopped just before taking a picture.
## 0.6.3+1
* Fixes flash & torch modes not working on some Android devices.
## 0.6.3
* Adds torch mode as a flash mode for Android and iOS implementations.
## 0.6.2+1
* Fix the API documentation for the `CameraController.takePicture` method.
## 0.6.2
* Add zoom support for Android and iOS implementations.
## 0.6.1+1
* Added implementation of the `didFinishProcessingPhoto` on iOS which allows saving image metadata (EXIF) on iOS 11 and up.
## 0.6.1
* Add flash support for Android and iOS implementations.
## 0.6.0+2
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
## 0.6.0+1
Updated README to inform users that iOS 10.0+ is needed for use
## 0.6.0
As part of implementing federated architecture and making the interface compatible with the web this version contains the following **breaking changes**:
Method changes in `CameraController`:
- The `takePicture` method no longer accepts the `path` parameter, but instead returns the captured image as an instance of the `XFile` class;
- The `startVideoRecording` method no longer accepts the `filePath`. Instead the recorded video is now returned as a `XFile` instance when the `stopVideoRecording` method completes;
- The `stopVideoRecording` method now returns the captured video when it completes;
- Added the `buildPreview` method which is now used to implement the CameraPreview widget.
## 0.5.8+19
* Update Flutter SDK constraint.
## 0.5.8+18
* Suppress unchecked warning in Android tests which prevented the tests to compile.
## 0.5.8+17
* Added Android 30 support.
## 0.5.8+16
* Moved package to camera/camera subdir, to allow for federated implementations.
## 0.5.8+15
* Added the `debugCheckIsDisposed` method which can be used in debug mode to validate if the `CameraController` class has been disposed.
## 0.5.8+14
* Changed the order of the setters for `mediaRecorder` in `MediaRecorderBuilder.java` to make it more readable.
## 0.5.8+13
* Added Dartdocs for all public APIs.
## 0.5.8+12
* Added information of video not working correctly on Android emulators to `README.md`.
## 0.5.8+11
* Fix rare nullptr exception on Android.
* Updated README.md with information about handling App lifecycle changes.
## 0.5.8+10
* Suppress the `deprecated_member_use` warning in the example app for `ScaffoldMessenger.showSnackBar`.
## 0.5.8+9
* Update android compileSdkVersion to 29.
## 0.5.8+8
* Fixed garbled audio (in video) by setting audio encoding bitrate.
## 0.5.8+7
* Keep handling deprecated Android v1 classes for backward compatibility.
## 0.5.8+6
* Avoiding uses or overrides a deprecated API in CameraPlugin.java.
## 0.5.8+5
* Fix compilation/availability issues on iOS.
## 0.5.8+4
* Fixed bug caused by casting a `CameraAccessException` on Android.
## 0.5.8+3
* Fix bug in usage example in README.md
## 0.5.8+2
* Post-v2 embedding cleanups.
## 0.5.8+1
* Update lower bound of dart dependency to 2.1.0.
## 0.5.8
* Remove Android dependencies fallback.
* Require Flutter SDK 1.12.13+hotfix.5 or greater.
## 0.5.7+5
* Replace deprecated `getFlutterEngine` call on Android.
## 0.5.7+4
* Add `pedantic` to dev_dependency.
## 0.5.7+3
* Fix an Android crash when permissions are requested multiple times.
## 0.5.7+2
* Remove the deprecated `author:` field from pubspec.yaml
* Migrate the plugin to the pubspec platforms manifest.
* Require Flutter SDK 1.10.0 or greater.
## 0.5.7+1
* Fix example null exception.
## 0.5.7
* Fix unawaited futures.
## 0.5.6+4
* Android: Use CameraDevice.TEMPLATE_RECORD to improve image streaming.
## 0.5.6+3
* Remove AndroidX warning.
## 0.5.6+2
* Include lifecycle dependency as a compileOnly one on Android to resolve
potential version conflicts with other transitive libraries.
## 0.5.6+1
* Android: Use android.arch.lifecycle instead of androidx.lifecycle:lifecycle in `build.gradle` to support apps that has not been migrated to AndroidX.
## 0.5.6
* Add support for the v2 Android embedding. This shouldn't affect existing
functionality.
## 0.5.5+1
* Fix event type check
## 0.5.5
* Define clang modules for iOS.
## 0.5.4+3
* Update and migrate iOS example project.
## 0.5.4+2
* Fix Android NullPointerException on devices with only front-facing camera.
## 0.5.4+1
* Fix Android pause and resume video crash when executing in APIs below 24.
## 0.5.4
* Add feature to pause and resume video recording.
## 0.5.3+1
* Fix too large request code for FragmentActivity users.
## 0.5.3
* Added new quality presets.
* Now all quality presets can be used to control image capture quality.
## 0.5.2+2
* Fix memory leak related to not unregistering stream handler in FlutterEventChannel when disposing camera.
## 0.5.2+1
* Fix bug that prevented video recording with audio.
## 0.5.2
* Added capability to disable audio for the `CameraController`. (e.g. `CameraController(_, _,
enableAudio: false);`)
## 0.5.1
* Can now be compiled with earlier Android sdks below 21 when
`<uses-sdk tools:overrideLibrary="io.flutter.plugins.camera"/>` has been added to the project
`AndroidManifest.xml`. For sdks below 21, the plugin won't be registered and calls to it will throw
a `MissingPluginException.`
## 0.5.0
* **Breaking Change** This plugin no longer handles closing and opening the camera on Android
lifecycle changes. Please use `WidgetsBindingObserver` to control camera resources on lifecycle
changes. See example project for example using `WidgetsBindingObserver`.
## 0.4.3+2
* Bump the minimum Flutter version to 1.2.0.
* Add template type parameter to `invokeMethod` calls.
## 0.4.3+1
* Catch additional `Exception`s from Android and throw as `CameraException`s.
## 0.4.3
* Add capability to prepare the capture session for video recording on iOS.
## 0.4.2
* Add sensor orientation value to `CameraDescription`.
## 0.4.1
* Camera methods are ran in a background thread on iOS.
## 0.4.0+3
* Fixed a crash when the plugin is registered by a background FlutterView.
## 0.4.0+2
* Fix orientation of captured photos when camera is used for the first time on Android.
## 0.4.0+1
* Remove categories.
## 0.4.0
* **Breaking Change** Change iOS image stream format to `ImageFormatGroup.bgra8888` from
`ImageFormatGroup.yuv420`.
## 0.3.0+4
* Fixed bug causing black screen on some Android devices.
## 0.3.0+3
* Log a more detailed warning at build time about the previous AndroidX
migration.
## 0.3.0+2
* Fix issue with calculating iOS image orientation in certain edge cases.
## 0.3.0+1
* Remove initial method call invocation from static camera method.
## 0.3.0
* **Breaking change**. Migrate from the deprecated original Android Support
Library to AndroidX. This shouldn't result in any functional changes, but it
requires any Android apps using this plugin to [also
migrate](https://developer.android.com/jetpack/androidx/migrate) if they're
using the original support library.
## 0.2.9+1
* Fix a crash when failing to start preview.
## 0.2.9
* Save photo orientation data on iOS.
## 0.2.8
* Add access to the image stream from Dart.
* Use `cameraController.startImageStream(listener)` to process the images.
## 0.2.7
* Fix issue with crash when the physical device's orientation is unknown.
## 0.2.6
* Update the camera to use the physical device's orientation instead of the UI
orientation on Android.
## 0.2.5
* Fix preview and video size with satisfying conditions of multiple outputs.
## 0.2.4
* Unregister the activity lifecycle callbacks when disposing the camera.
## 0.2.3
* Added path_provider and video_player as dev dependencies because the example uses them.
* Updated example path_provider version to get Dart 2 support.
## 0.2.2
* iOS image capture is done in high quality (full camera size)
## 0.2.1
* Updated Gradle tooling to match Android Studio 3.1.2.
## 0.2.0
* Added support for video recording.
* Changed the example app to add video recording.
A lot of **breaking changes** in this version:
Getter changes:
- Removed `isStarted`
- Renamed `initialized` to `isInitialized`
- Added `isRecordingVideo`
Method changes:
- Renamed `capture` to `takePicture`
- Removed `start` (the preview starts automatically when `initialize` is called)
- Added `startVideoRecording(String filePath)`
- Removed `stop` (the preview stops automatically when `dispose` is called)
- Added `stopVideoRecording`
## 0.1.2
* Fix Dart 2 runtime errors.
## 0.1.1
* Fix Dart 2 runtime error.
## 0.1.0
* **Breaking change**. Set SDK constraints to match the Flutter beta release.
## 0.0.4
* Revert regression of `CameraController.capture()` introduced in v. 0.0.3.
## 0.0.3
* Improved resource cleanup on Android. Avoids crash on Activity restart.
* Made the Future returned by `CameraController.dispose()` and `CameraController.capture()` actually complete on
Android.
## 0.0.2
* Simplified and upgraded Android project template to Android SDK 27.
* Moved Android package to io.flutter.plugins.
* Fixed warnings from the Dart 2.0 analyzer.
## 0.0.1
* Initial release
| packages/packages/camera/camera/CHANGELOG.md/0 | {
"file_path": "packages/packages/camera/camera/CHANGELOG.md",
"repo_id": "packages",
"token_count": 6356
} | 980 |
group 'io.flutter.plugins.camera'
version '1.0-SNAPSHOT'
def args = ["-Xlint:deprecation","-Xlint:unchecked"]
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
project.getTasks().withType(JavaCompile){
options.compilerArgs.addAll(args)
}
apply plugin: 'com.android.library'
android {
buildFeatures {
buildConfig true
}
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.camera'
}
compileSdk 34
defaultConfig {
minSdkVersion 21
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
jvmArgs "-Xmx1g"
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
dependencies {
implementation 'androidx.annotation:annotation:1.7.0'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-inline:5.0.0'
testImplementation 'androidx.test:core:1.4.0'
testImplementation 'org.robolectric:robolectric:4.10.3'
}
| packages/packages/camera/camera_android/android/build.gradle/0 | {
"file_path": "packages/packages/camera/camera_android/android/build.gradle",
"repo_id": "packages",
"token_count": 792
} | 981 |
// 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.app.Activity;
import android.hardware.camera2.CameraAccessException;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.camera.CameraPermissions.PermissionsRegistry;
import io.flutter.plugins.camera.features.CameraFeatureFactoryImpl;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.autofocus.FocusMode;
import io.flutter.plugins.camera.features.exposurelock.ExposureMode;
import io.flutter.plugins.camera.features.flash.FlashMode;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.view.TextureRegistry;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
final class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {
private final Activity activity;
private final BinaryMessenger messenger;
private final CameraPermissions cameraPermissions;
private final PermissionsRegistry permissionsRegistry;
private final TextureRegistry textureRegistry;
private final MethodChannel methodChannel;
private final EventChannel imageStreamChannel;
private @Nullable Camera camera;
MethodCallHandlerImpl(
Activity activity,
BinaryMessenger messenger,
CameraPermissions cameraPermissions,
PermissionsRegistry permissionsAdder,
TextureRegistry textureRegistry) {
this.activity = activity;
this.messenger = messenger;
this.cameraPermissions = cameraPermissions;
this.permissionsRegistry = permissionsAdder;
this.textureRegistry = textureRegistry;
methodChannel = new MethodChannel(messenger, "plugins.flutter.io/camera_android");
imageStreamChannel =
new EventChannel(messenger, "plugins.flutter.io/camera_android/imageStream");
methodChannel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
switch (call.method) {
case "availableCameras":
try {
result.success(CameraUtils.getAvailableCameras(activity));
} catch (Exception e) {
handleException(e, result);
}
break;
case "create":
{
if (camera != null) {
camera.close();
}
cameraPermissions.requestPermissions(
activity,
permissionsRegistry,
call.argument("enableAudio"),
(String errCode, String errDesc) -> {
if (errCode == null) {
try {
instantiateCamera(call, result);
} catch (Exception e) {
handleException(e, result);
}
} else {
result.error(errCode, errDesc, null);
}
});
break;
}
case "initialize":
{
if (camera != null) {
try {
camera.open(call.argument("imageFormatGroup"));
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
} else {
result.error(
"cameraNotFound",
"Camera not found. Please call the 'create' method before calling 'initialize'.",
null);
}
break;
}
case "takePicture":
{
camera.takePicture(result);
break;
}
case "prepareForVideoRecording":
{
// This optimization is not required for Android.
result.success(null);
break;
}
case "startVideoRecording":
{
camera.startVideoRecording(
result,
Objects.equals(call.argument("enableStream"), true) ? imageStreamChannel : null);
break;
}
case "stopVideoRecording":
{
camera.stopVideoRecording(result);
break;
}
case "pauseVideoRecording":
{
camera.pauseVideoRecording(result);
break;
}
case "resumeVideoRecording":
{
camera.resumeVideoRecording(result);
break;
}
case "setFlashMode":
{
String modeStr = call.argument("mode");
FlashMode mode = FlashMode.getValueForString(modeStr);
if (mode == null) {
result.error("setFlashModeFailed", "Unknown flash mode " + modeStr, null);
return;
}
try {
camera.setFlashMode(result, mode);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setExposureMode":
{
String modeStr = call.argument("mode");
ExposureMode mode = ExposureMode.getValueForString(modeStr);
if (mode == null) {
result.error("setExposureModeFailed", "Unknown exposure mode " + modeStr, null);
return;
}
try {
camera.setExposureMode(result, mode);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setExposurePoint":
{
Boolean reset = call.argument("reset");
Double x = null;
Double y = null;
if (reset == null || !reset) {
x = call.argument("x");
y = call.argument("y");
}
try {
camera.setExposurePoint(result, new Point(x, y));
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "getMinExposureOffset":
{
try {
result.success(camera.getMinExposureOffset());
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "getMaxExposureOffset":
{
try {
result.success(camera.getMaxExposureOffset());
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "getExposureOffsetStepSize":
{
try {
result.success(camera.getExposureOffsetStepSize());
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setExposureOffset":
{
try {
camera.setExposureOffset(result, call.argument("offset"));
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setFocusMode":
{
String modeStr = call.argument("mode");
FocusMode mode = FocusMode.getValueForString(modeStr);
if (mode == null) {
result.error("setFocusModeFailed", "Unknown focus mode " + modeStr, null);
return;
}
try {
camera.setFocusMode(result, mode);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setFocusPoint":
{
Boolean reset = call.argument("reset");
Double x = null;
Double y = null;
if (reset == null || !reset) {
x = call.argument("x");
y = call.argument("y");
}
try {
camera.setFocusPoint(result, new Point(x, y));
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "startImageStream":
{
try {
camera.startPreviewWithImageStream(imageStreamChannel);
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "stopImageStream":
{
try {
camera.startPreview();
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "getMaxZoomLevel":
{
assert camera != null;
try {
float maxZoomLevel = camera.getMaxZoomLevel();
result.success(maxZoomLevel);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "getMinZoomLevel":
{
assert camera != null;
try {
float minZoomLevel = camera.getMinZoomLevel();
result.success(minZoomLevel);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "setZoomLevel":
{
assert camera != null;
Double zoom = call.argument("zoom");
if (zoom == null) {
result.error(
"ZOOM_ERROR", "setZoomLevel is called without specifying a zoom level.", null);
return;
}
try {
camera.setZoomLevel(result, zoom.floatValue());
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "lockCaptureOrientation":
{
PlatformChannel.DeviceOrientation orientation =
CameraUtils.deserializeDeviceOrientation(call.argument("orientation"));
try {
camera.lockCaptureOrientation(orientation);
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "unlockCaptureOrientation":
{
try {
camera.unlockCaptureOrientation();
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "pausePreview":
{
try {
camera.pausePreview();
result.success(null);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "resumePreview":
{
camera.resumePreview();
result.success(null);
break;
}
case "setDescriptionWhileRecording":
{
try {
String cameraName = call.argument("cameraName");
CameraProperties cameraProperties =
new CameraPropertiesImpl(cameraName, CameraUtils.getCameraManager(activity));
camera.setDescriptionWhileRecording(result, cameraProperties);
} catch (Exception e) {
handleException(e, result);
}
break;
}
case "dispose":
{
if (camera != null) {
camera.dispose();
}
result.success(null);
break;
}
default:
result.notImplemented();
break;
}
}
void stopListening() {
methodChannel.setMethodCallHandler(null);
}
private void instantiateCamera(MethodCall call, Result result) throws CameraAccessException {
String cameraName = call.argument("cameraName");
String preset = call.argument("resolutionPreset");
boolean enableAudio = call.argument("enableAudio");
TextureRegistry.SurfaceTextureEntry flutterSurfaceTexture =
textureRegistry.createSurfaceTexture();
DartMessenger dartMessenger =
new DartMessenger(
messenger, flutterSurfaceTexture.id(), new Handler(Looper.getMainLooper()));
CameraProperties cameraProperties =
new CameraPropertiesImpl(cameraName, CameraUtils.getCameraManager(activity));
ResolutionPreset resolutionPreset = ResolutionPreset.valueOf(preset);
camera =
new Camera(
activity,
flutterSurfaceTexture,
new CameraFeatureFactoryImpl(),
dartMessenger,
cameraProperties,
resolutionPreset,
enableAudio);
Map<String, Object> reply = new HashMap<>();
reply.put("cameraId", flutterSurfaceTexture.id());
result.success(reply);
}
// We move catching CameraAccessException out of onMethodCall because it causes a crash
// on plugin registration for sdks incompatible with Camera2 (< 21). We want this plugin to
// to be able to compile with <21 sdks for apps that want the camera and support earlier version.
@SuppressWarnings("ConstantConditions")
private void handleException(Exception exception, Result result) {
if (exception instanceof CameraAccessException) {
result.error("CameraAccess", exception.getMessage(), null);
return;
}
// CameraAccessException can not be cast to a RuntimeException.
throw (RuntimeException) exception;
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/MethodCallHandlerImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/MethodCallHandlerImpl.java",
"repo_id": "packages",
"token_count": 6058
} | 982 |
// 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.types;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
// Mirrors flash_mode.dart
public enum FlashMode {
off("off"),
auto("auto"),
always("always"),
torch("torch");
private final String strValue;
FlashMode(String strValue) {
this.strValue = strValue;
}
@Nullable
public static FlashMode getValueForString(@NonNull String modeStr) {
for (FlashMode value : values()) {
if (value.strValue.equals(modeStr)) return value;
}
return null;
}
@Override
public String toString() {
return strValue;
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/FlashMode.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/FlashMode.java",
"repo_id": "packages",
"token_count": 252
} | 983 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.autofocus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import io.flutter.plugins.camera.CameraProperties;
import org.junit.Test;
public class AutoFocusFeatureTest {
private static final int[] FOCUS_MODES_ONLY_OFF =
new int[] {CameraCharacteristics.CONTROL_AF_MODE_OFF};
private static final int[] FOCUS_MODES =
new int[] {
CameraCharacteristics.CONTROL_AF_MODE_OFF, CameraCharacteristics.CONTROL_AF_MODE_AUTO
};
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
assertEquals("AutoFocusFeature", autoFocusFeature.getDebugName());
}
@Test
public void getValue_shouldReturnAutoIfNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
assertEquals(FocusMode.auto, autoFocusFeature.getValue());
}
@Test
public void getValue_shouldEchoTheSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
FocusMode expectedValue = FocusMode.locked;
autoFocusFeature.setValue(expectedValue);
FocusMode actualValue = autoFocusFeature.getValue();
assertEquals(expectedValue, actualValue);
}
@Test
public void checkIsSupported_shouldReturnFalseWhenMinimumFocusDistanceIsZero() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(0.0F);
assertFalse(autoFocusFeature.checkIsSupported());
}
@Test
public void checkIsSupported_shouldReturnFalseWhenMinimumFocusDistanceIsNull() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(null);
assertFalse(autoFocusFeature.checkIsSupported());
}
@Test
public void checkIsSupport_shouldReturnFalseWhenNoFocusModesAreAvailable() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(new int[] {});
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
assertFalse(autoFocusFeature.checkIsSupported());
}
@Test
public void checkIsSupport_shouldReturnFalseWhenOnlyFocusOffIsAvailable() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES_ONLY_OFF);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
assertFalse(autoFocusFeature.checkIsSupported());
}
@Test
public void checkIsSupport_shouldReturnTrueWhenOnlyMultipleFocusModesAreAvailable() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
assertTrue(autoFocusFeature.checkIsSupported());
}
@Test
public void updateBuilderShouldReturnWhenCheckIsSupportedIsFalse() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(0.0F);
autoFocusFeature.updateBuilder(mockBuilder);
verify(mockBuilder, never()).set(any(), any());
}
@Test
public void updateBuilder_shouldSetControlModeToAutoWhenFocusIsLocked() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
autoFocusFeature.setValue(FocusMode.locked);
autoFocusFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
}
@Test
public void
updateBuilder_shouldSetControlModeToContinuousVideoWhenFocusIsAutoAndRecordingVideo() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, true);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
autoFocusFeature.setValue(FocusMode.auto);
autoFocusFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO);
}
@Test
public void
updateBuilder_shouldSetControlModeToContinuousVideoWhenFocusIsAutoAndNotRecordingVideo() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
AutoFocusFeature autoFocusFeature = new AutoFocusFeature(mockCameraProperties, false);
when(mockCameraProperties.getControlAutoFocusAvailableModes()).thenReturn(FOCUS_MODES);
when(mockCameraProperties.getLensInfoMinimumFocusDistance()).thenReturn(1.0F);
autoFocusFeature.setValue(FocusMode.auto);
autoFocusFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
}
}
| packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeatureTest.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeatureTest.java",
"repo_id": "packages",
"token_count": 2296
} | 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.
package io.flutter.plugins.camera.media;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.graphics.ImageFormat;
import android.media.Image;
import android.media.ImageReader;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import java.nio.ByteBuffer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class ImageStreamReaderTest {
/** If we request YUV42 we should stream in YUV420. */
@Test
public void computeStreamImageFormat_computesCorrectStreamFormatYuv() {
int requestedStreamFormat = ImageFormat.YUV_420_888;
int result = ImageStreamReader.computeStreamImageFormat(requestedStreamFormat);
assertEquals(result, ImageFormat.YUV_420_888);
}
/**
* When we want to stream in NV21, we should still request YUV420 from the camera because we will
* convert it to NV21 before sending it to dart.
*/
@Test
public void computeStreamImageFormat_computesCorrectStreamFormatNv21() {
int requestedStreamFormat = ImageFormat.NV21;
int result = ImageStreamReader.computeStreamImageFormat(requestedStreamFormat);
assertEquals(result, ImageFormat.YUV_420_888);
}
/**
* If we are requesting NV21, then the planes should be processed and converted to NV21 before
* being sent to dart. We make sure yuv420ThreePlanesToNV21 is called when we are requesting
*/
@Test
public void onImageAvailable_parsesPlanesForNv21() {
// Dart wants NV21 frames
int dartImageFormat = ImageFormat.NV21;
ImageReader mockImageReader = mock(ImageReader.class);
ImageStreamReaderUtils mockImageStreamReaderUtils = mock(ImageStreamReaderUtils.class);
ImageStreamReader imageStreamReader =
new ImageStreamReader(mockImageReader, dartImageFormat, mockImageStreamReaderUtils);
ByteBuffer mockBytes = ByteBuffer.allocate(0);
when(mockImageStreamReaderUtils.yuv420ThreePlanesToNV21(any(), anyInt(), anyInt()))
.thenReturn(mockBytes);
// The image format as streamed from the camera
int imageFormat = ImageFormat.YUV_420_888;
// Mock YUV image
Image mockImage = mock(Image.class);
when(mockImage.getWidth()).thenReturn(1280);
when(mockImage.getHeight()).thenReturn(720);
when(mockImage.getFormat()).thenReturn(imageFormat);
// Mock planes. YUV images have 3 planes (Y, U, V).
Image.Plane planeY = mock(Image.Plane.class);
Image.Plane planeU = mock(Image.Plane.class);
Image.Plane planeV = mock(Image.Plane.class);
// Y plane is width*height
// Row stride is generally == width but when there is padding it will
// be larger. The numbers in this example are from a Vivo V2135 on 'high'
// setting (1280x720).
when(planeY.getBuffer()).thenReturn(ByteBuffer.allocate(1105664));
when(planeY.getRowStride()).thenReturn(1536);
when(planeY.getPixelStride()).thenReturn(1);
// U and V planes are always the same sizes/values.
// https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888
when(planeU.getBuffer()).thenReturn(ByteBuffer.allocate(552703));
when(planeV.getBuffer()).thenReturn(ByteBuffer.allocate(552703));
when(planeU.getRowStride()).thenReturn(1536);
when(planeV.getRowStride()).thenReturn(1536);
when(planeU.getPixelStride()).thenReturn(2);
when(planeV.getPixelStride()).thenReturn(2);
// Add planes to image
Image.Plane[] planes = {planeY, planeU, planeV};
when(mockImage.getPlanes()).thenReturn(planes);
CameraCaptureProperties mockCaptureProps = mock(CameraCaptureProperties.class);
EventChannel.EventSink mockEventSink = mock(EventChannel.EventSink.class);
imageStreamReader.onImageAvailable(mockImage, mockCaptureProps, mockEventSink);
// Make sure we processed the frame with parsePlanesForNv21
verify(mockImageStreamReaderUtils)
.yuv420ThreePlanesToNV21(planes, mockImage.getWidth(), mockImage.getHeight());
}
/** If we are requesting YUV420, then we should send the 3-plane image as it is. */
@Test
public void onImageAvailable_parsesPlanesForYuv420() {
// Dart wants NV21 frames
int dartImageFormat = ImageFormat.YUV_420_888;
ImageReader mockImageReader = mock(ImageReader.class);
ImageStreamReaderUtils mockImageStreamReaderUtils = mock(ImageStreamReaderUtils.class);
ImageStreamReader imageStreamReader =
new ImageStreamReader(mockImageReader, dartImageFormat, mockImageStreamReaderUtils);
ByteBuffer mockBytes = ByteBuffer.allocate(0);
when(mockImageStreamReaderUtils.yuv420ThreePlanesToNV21(any(), anyInt(), anyInt()))
.thenReturn(mockBytes);
// The image format as streamed from the camera
int imageFormat = ImageFormat.YUV_420_888;
// Mock YUV image
Image mockImage = mock(Image.class);
when(mockImage.getWidth()).thenReturn(1280);
when(mockImage.getHeight()).thenReturn(720);
when(mockImage.getFormat()).thenReturn(imageFormat);
// Mock planes. YUV images have 3 planes (Y, U, V).
Image.Plane planeY = mock(Image.Plane.class);
Image.Plane planeU = mock(Image.Plane.class);
Image.Plane planeV = mock(Image.Plane.class);
// Y plane is width*height
// Row stride is generally == width but when there is padding it will
// be larger. The numbers in this example are from a Vivo V2135 on 'high'
// setting (1280x720).
when(planeY.getBuffer()).thenReturn(ByteBuffer.allocate(1105664));
when(planeY.getRowStride()).thenReturn(1536);
when(planeY.getPixelStride()).thenReturn(1);
// U and V planes are always the same sizes/values.
// https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888
when(planeU.getBuffer()).thenReturn(ByteBuffer.allocate(552703));
when(planeV.getBuffer()).thenReturn(ByteBuffer.allocate(552703));
when(planeU.getRowStride()).thenReturn(1536);
when(planeV.getRowStride()).thenReturn(1536);
when(planeU.getPixelStride()).thenReturn(2);
when(planeV.getPixelStride()).thenReturn(2);
// Add planes to image
Image.Plane[] planes = {planeY, planeU, planeV};
when(mockImage.getPlanes()).thenReturn(planes);
CameraCaptureProperties mockCaptureProps = mock(CameraCaptureProperties.class);
EventChannel.EventSink mockEventSink = mock(EventChannel.EventSink.class);
imageStreamReader.onImageAvailable(mockImage, mockCaptureProps, mockEventSink);
// Make sure we processed the frame with parsePlanesForYuvOrJpeg
verify(mockImageStreamReaderUtils, never()).yuv420ThreePlanesToNV21(any(), anyInt(), anyInt());
}
}
| packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/media/ImageStreamReaderTest.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/media/ImageStreamReaderTest.java",
"repo_id": "packages",
"token_count": 2405
} | 985 |
// 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:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:stream_transform/stream_transform.dart';
import 'type_conversion.dart';
import 'utils.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/camera_android');
/// The Android implementation of [CameraPlatform] that uses method channels.
class AndroidCamera extends CameraPlatform {
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith() {
CameraPlatform.instance = AndroidCamera();
}
final Map<int, MethodChannel> _channels = <int, MethodChannel>{};
/// The name of the channel that device events from the platform side are
/// sent on.
@visibleForTesting
static const String deviceEventChannelName =
'plugins.flutter.io/camera_android/fromPlatform';
/// The controller we need to broadcast the different events coming
/// from handleMethodCall, specific to camera events.
///
/// It is a `broadcast` because multiple controllers will connect to
/// different stream views of this Controller.
/// This is only exposed for test purposes. It shouldn't be used by clients of
/// the plugin as it may break or change at any time.
@visibleForTesting
final StreamController<CameraEvent> cameraEventStreamController =
StreamController<CameraEvent>.broadcast();
/// The controller we need to broadcast the different events coming
/// from handleMethodCall, specific to general device events.
///
/// It is a `broadcast` because multiple controllers will connect to
/// different stream views of this Controller.
late final StreamController<DeviceEvent> _deviceEventStreamController =
_createDeviceEventStreamController();
StreamController<DeviceEvent> _createDeviceEventStreamController() {
// Set up the method handler lazily.
const MethodChannel channel = MethodChannel(deviceEventChannelName);
channel.setMethodCallHandler(_handleDeviceMethodCall);
return StreamController<DeviceEvent>.broadcast();
}
// The stream to receive frames from the native code.
StreamSubscription<dynamic>? _platformImageStreamSubscription;
// The stream for vending frames to platform interface clients.
StreamController<CameraImageData>? _frameStreamController;
Stream<CameraEvent> _cameraEvents(int cameraId) =>
cameraEventStreamController.stream
.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
try {
final List<Map<dynamic, dynamic>>? cameras = await _channel
.invokeListMethod<Map<dynamic, dynamic>>('availableCameras');
if (cameras == null) {
return <CameraDescription>[];
}
return cameras.map((Map<dynamic, dynamic> camera) {
return CameraDescription(
name: camera['name']! as String,
lensDirection:
parseCameraLensDirection(camera['lensFacing']! as String),
sensorOrientation: camera['sensorOrientation']! as int,
);
}).toList();
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<int> createCamera(
CameraDescription cameraDescription,
ResolutionPreset? resolutionPreset, {
bool enableAudio = false,
}) async {
try {
final Map<String, dynamic>? reply = await _channel
.invokeMapMethod<String, dynamic>('create', <String, dynamic>{
'cameraName': cameraDescription.name,
'resolutionPreset': resolutionPreset != null
? _serializeResolutionPreset(resolutionPreset)
: null,
'enableAudio': enableAudio,
});
return reply!['cameraId']! as int;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<void> initializeCamera(
int cameraId, {
ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown,
}) {
_channels.putIfAbsent(cameraId, () {
final MethodChannel channel =
MethodChannel('plugins.flutter.io/camera_android/camera$cameraId');
channel.setMethodCallHandler(
(MethodCall call) => handleCameraMethodCall(call, cameraId));
return channel;
});
final Completer<void> completer = Completer<void>();
onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) {
completer.complete();
});
_channel.invokeMapMethod<String, dynamic>(
'initialize',
<String, dynamic>{
'cameraId': cameraId,
'imageFormatGroup': imageFormatGroup.name(),
},
).catchError(
// TODO(srawlins): This should return a value of the future's type. This
// will fail upcoming analysis checks with
// https://github.com/flutter/flutter/issues/105750.
// ignore: body_might_complete_normally_catch_error
(Object error, StackTrace stackTrace) {
if (error is! PlatformException) {
// ignore: only_throw_errors
throw error;
}
completer.completeError(
CameraException(error.code, error.message),
stackTrace,
);
},
);
return completer.future;
}
@override
Future<void> dispose(int cameraId) async {
if (_channels.containsKey(cameraId)) {
final MethodChannel? cameraChannel = _channels[cameraId];
cameraChannel?.setMethodCallHandler(null);
_channels.remove(cameraId);
}
await _channel.invokeMethod<void>(
'dispose',
<String, dynamic>{'cameraId': cameraId},
);
}
@override
Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraInitializedEvent>();
}
@override
Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraResolutionChangedEvent>();
}
@override
Stream<CameraClosingEvent> onCameraClosing(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraClosingEvent>();
}
@override
Stream<CameraErrorEvent> onCameraError(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraErrorEvent>();
}
@override
Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) {
return _cameraEvents(cameraId).whereType<VideoRecordedEvent>();
}
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
return _deviceEventStreamController.stream
.whereType<DeviceOrientationChangedEvent>();
}
@override
Future<void> lockCaptureOrientation(
int cameraId,
DeviceOrientation orientation,
) async {
await _channel.invokeMethod<String>(
'lockCaptureOrientation',
<String, dynamic>{
'cameraId': cameraId,
'orientation': serializeDeviceOrientation(orientation)
},
);
}
@override
Future<void> unlockCaptureOrientation(int cameraId) async {
await _channel.invokeMethod<String>(
'unlockCaptureOrientation',
<String, dynamic>{'cameraId': cameraId},
);
}
@override
Future<XFile> takePicture(int cameraId) async {
final String? path = await _channel.invokeMethod<String>(
'takePicture',
<String, dynamic>{'cameraId': cameraId},
);
if (path == null) {
throw CameraException(
'INVALID_PATH',
'The platform "$defaultTargetPlatform" did not return a path while reporting success. The platform should always return a valid path or report an error.',
);
}
return XFile(path);
}
@override
Future<void> prepareForVideoRecording() =>
_channel.invokeMethod<void>('prepareForVideoRecording');
@override
Future<void> startVideoRecording(int cameraId,
{Duration? maxVideoDuration}) async {
return startVideoCapturing(
VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration));
}
@override
Future<void> startVideoCapturing(VideoCaptureOptions options) async {
await _channel.invokeMethod<void>(
'startVideoRecording',
<String, dynamic>{
'cameraId': options.cameraId,
'maxVideoDuration': options.maxDuration?.inMilliseconds,
'enableStream': options.streamCallback != null,
},
);
if (options.streamCallback != null) {
_installStreamController().stream.listen(options.streamCallback);
_startStreamListener();
}
}
@override
Future<XFile> stopVideoRecording(int cameraId) async {
final String? path = await _channel.invokeMethod<String>(
'stopVideoRecording',
<String, dynamic>{'cameraId': cameraId},
);
if (path == null) {
throw CameraException(
'INVALID_PATH',
'The platform "$defaultTargetPlatform" did not return a path while reporting success. The platform should always return a valid path or report an error.',
);
}
return XFile(path);
}
@override
Future<void> pauseVideoRecording(int cameraId) => _channel.invokeMethod<void>(
'pauseVideoRecording',
<String, dynamic>{'cameraId': cameraId},
);
@override
Future<void> resumeVideoRecording(int cameraId) =>
_channel.invokeMethod<void>(
'resumeVideoRecording',
<String, dynamic>{'cameraId': cameraId},
);
@override
Stream<CameraImageData> onStreamedFrameAvailable(int cameraId,
{CameraImageStreamOptions? options}) {
_installStreamController(onListen: _onFrameStreamListen);
return _frameStreamController!.stream;
}
StreamController<CameraImageData> _installStreamController(
{void Function()? onListen}) {
_frameStreamController = StreamController<CameraImageData>(
onListen: onListen ?? () {},
onPause: _onFrameStreamPauseResume,
onResume: _onFrameStreamPauseResume,
onCancel: _onFrameStreamCancel,
);
return _frameStreamController!;
}
void _onFrameStreamListen() {
_startPlatformStream();
}
Future<void> _startPlatformStream() async {
await _channel.invokeMethod<void>('startImageStream');
_startStreamListener();
}
void _startStreamListener() {
const EventChannel cameraEventChannel =
EventChannel('plugins.flutter.io/camera_android/imageStream');
_platformImageStreamSubscription =
cameraEventChannel.receiveBroadcastStream().listen((dynamic imageData) {
_frameStreamController!
.add(cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>));
});
}
FutureOr<void> _onFrameStreamCancel() async {
await _channel.invokeMethod<void>('stopImageStream');
await _platformImageStreamSubscription?.cancel();
_platformImageStreamSubscription = null;
_frameStreamController = null;
}
void _onFrameStreamPauseResume() {
throw CameraException('InvalidCall',
'Pause and resume are not supported for onStreamedFrameAvailable');
}
@override
Future<void> setFlashMode(int cameraId, FlashMode mode) =>
_channel.invokeMethod<void>(
'setFlashMode',
<String, dynamic>{
'cameraId': cameraId,
'mode': _serializeFlashMode(mode),
},
);
@override
Future<void> setExposureMode(int cameraId, ExposureMode mode) =>
_channel.invokeMethod<void>(
'setExposureMode',
<String, dynamic>{
'cameraId': cameraId,
'mode': serializeExposureMode(mode),
},
);
@override
Future<void> setExposurePoint(int cameraId, Point<double>? point) {
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
return _channel.invokeMethod<void>(
'setExposurePoint',
<String, dynamic>{
'cameraId': cameraId,
'reset': point == null,
'x': point?.x,
'y': point?.y,
},
);
}
@override
Future<double> getMinExposureOffset(int cameraId) async {
final double? minExposureOffset = await _channel.invokeMethod<double>(
'getMinExposureOffset',
<String, dynamic>{'cameraId': cameraId},
);
return minExposureOffset!;
}
@override
Future<double> getMaxExposureOffset(int cameraId) async {
final double? maxExposureOffset = await _channel.invokeMethod<double>(
'getMaxExposureOffset',
<String, dynamic>{'cameraId': cameraId},
);
return maxExposureOffset!;
}
@override
Future<double> getExposureOffsetStepSize(int cameraId) async {
final double? stepSize = await _channel.invokeMethod<double>(
'getExposureOffsetStepSize',
<String, dynamic>{'cameraId': cameraId},
);
return stepSize!;
}
@override
Future<double> setExposureOffset(int cameraId, double offset) async {
final double? appliedOffset = await _channel.invokeMethod<double>(
'setExposureOffset',
<String, dynamic>{
'cameraId': cameraId,
'offset': offset,
},
);
return appliedOffset!;
}
@override
Future<void> setFocusMode(int cameraId, FocusMode mode) =>
_channel.invokeMethod<void>(
'setFocusMode',
<String, dynamic>{
'cameraId': cameraId,
'mode': serializeFocusMode(mode),
},
);
@override
Future<void> setFocusPoint(int cameraId, Point<double>? point) {
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
return _channel.invokeMethod<void>(
'setFocusPoint',
<String, dynamic>{
'cameraId': cameraId,
'reset': point == null,
'x': point?.x,
'y': point?.y,
},
);
}
@override
Future<double> getMaxZoomLevel(int cameraId) async {
final double? maxZoomLevel = await _channel.invokeMethod<double>(
'getMaxZoomLevel',
<String, dynamic>{'cameraId': cameraId},
);
return maxZoomLevel!;
}
@override
Future<double> getMinZoomLevel(int cameraId) async {
final double? minZoomLevel = await _channel.invokeMethod<double>(
'getMinZoomLevel',
<String, dynamic>{'cameraId': cameraId},
);
return minZoomLevel!;
}
@override
Future<void> setZoomLevel(int cameraId, double zoom) async {
try {
await _channel.invokeMethod<double>(
'setZoomLevel',
<String, dynamic>{
'cameraId': cameraId,
'zoom': zoom,
},
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<void> pausePreview(int cameraId) async {
await _channel.invokeMethod<double>(
'pausePreview',
<String, dynamic>{'cameraId': cameraId},
);
}
@override
Future<void> resumePreview(int cameraId) async {
await _channel.invokeMethod<double>(
'resumePreview',
<String, dynamic>{'cameraId': cameraId},
);
}
@override
Future<void> setDescriptionWhileRecording(
CameraDescription description) async {
await _channel.invokeMethod<double>(
'setDescriptionWhileRecording',
<String, dynamic>{
'cameraName': description.name,
},
);
}
@override
Widget buildPreview(int cameraId) {
return Texture(textureId: cameraId);
}
/// Returns the flash mode as a String.
String _serializeFlashMode(FlashMode flashMode) {
switch (flashMode) {
case FlashMode.off:
return 'off';
case FlashMode.auto:
return 'auto';
case FlashMode.always:
return 'always';
case FlashMode.torch:
return 'torch';
}
// The enum comes from a different package, which could get a new value at
// any time, so provide a fallback that ensures this won't break when used
// with a version that contains new values. This is deliberately outside
// the switch rather than a `default` so that the linter will flag the
// switch as needing an update.
// ignore: dead_code
return 'off';
}
/// Returns the resolution preset as a String.
String _serializeResolutionPreset(ResolutionPreset resolutionPreset) {
switch (resolutionPreset) {
case ResolutionPreset.max:
return 'max';
case ResolutionPreset.ultraHigh:
return 'ultraHigh';
case ResolutionPreset.veryHigh:
return 'veryHigh';
case ResolutionPreset.high:
return 'high';
case ResolutionPreset.medium:
return 'medium';
case ResolutionPreset.low:
return 'low';
}
// The enum comes from a different package, which could get a new value at
// any time, so provide a fallback that ensures this won't break when used
// with a version that contains new values. This is deliberately outside
// the switch rather than a `default` so that the linter will flag the
// switch as needing an update.
// ignore: dead_code
return 'max';
}
/// Converts messages received from the native platform into device events.
Future<dynamic> _handleDeviceMethodCall(MethodCall call) async {
switch (call.method) {
case 'orientation_changed':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_deviceEventStreamController.add(DeviceOrientationChangedEvent(
deserializeDeviceOrientation(arguments['orientation']! as String)));
default:
throw MissingPluginException();
}
}
/// Converts messages received from the native platform into camera events.
///
/// This is only exposed for test purposes. It shouldn't be used by clients of
/// the plugin as it may break or change at any time.
@visibleForTesting
Future<dynamic> handleCameraMethodCall(MethodCall call, int cameraId) async {
switch (call.method) {
case 'initialized':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
cameraEventStreamController.add(CameraInitializedEvent(
cameraId,
arguments['previewWidth']! as double,
arguments['previewHeight']! as double,
deserializeExposureMode(arguments['exposureMode']! as String),
arguments['exposurePointSupported']! as bool,
deserializeFocusMode(arguments['focusMode']! as String),
arguments['focusPointSupported']! as bool,
));
case 'resolution_changed':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
cameraEventStreamController.add(CameraResolutionChangedEvent(
cameraId,
arguments['captureWidth']! as double,
arguments['captureHeight']! as double,
));
case 'camera_closing':
cameraEventStreamController.add(CameraClosingEvent(
cameraId,
));
case 'video_recorded':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
cameraEventStreamController.add(VideoRecordedEvent(
cameraId,
XFile(arguments['path']! as String),
arguments['maxVideoDuration'] != null
? Duration(milliseconds: arguments['maxVideoDuration']! as int)
: null,
));
case 'error':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
cameraEventStreamController.add(CameraErrorEvent(
cameraId,
arguments['description']! as String,
));
default:
throw MissingPluginException();
}
}
/// Returns the arguments of [call] as typed string-keyed Map.
///
/// This does not do any type validation, so is only safe to call if the
/// arguments are known to be a map.
Map<String, Object?> _getArgumentDictionary(MethodCall call) {
return (call.arguments as Map<Object?, Object?>).cast<String, Object?>();
}
}
| packages/packages/camera/camera_android/lib/src/android_camera.dart/0 | {
"file_path": "packages/packages/camera/camera_android/lib/src/android_camera.dart",
"repo_id": "packages",
"token_count": 7154
} | 986 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="io.flutter.plugins.camerax">
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
tools:node="remove" />
</manifest>
| packages/packages/camera/camera_android_camerax/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 207
} | 987 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.CameraState;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateFlutterApi;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateTypeData;
/**
* Flutter API implementation for {@link CameraState}.
*
* <p>This class may handle adding native instances that are attached to a Dart instance or passing
* arguments of callbacks methods to a Dart instance.
*/
public class CameraStateFlutterApiWrapper {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
private CameraStateFlutterApi cameraStateFlutterApi;
/**
* Constructs a {@link CameraStateFlutterApiWrapper}.
*
* @param binaryMessenger used to communicate with Dart over asynchronous messages
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public CameraStateFlutterApiWrapper(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
cameraStateFlutterApi = new CameraStateFlutterApi(binaryMessenger);
}
/**
* Stores the {@link CameraState} instance and notifies Dart to create and store a new {@link
* CameraState} instance that is attached to this one. If {@code instance} has already been added,
* this method does nothing.
*/
public void create(
@NonNull CameraState instance,
@NonNull CameraStateType type,
@Nullable CameraState.StateError error,
@NonNull CameraStateFlutterApi.Reply<Void> callback) {
if (instanceManager.containsInstance(instance)) {
return;
}
if (error != null) {
// if there is a problem with the current camera state, we need to create a CameraStateError
// to send to the Dart side.
new CameraStateErrorFlutterApiWrapper(binaryMessenger, instanceManager)
.create(error, Long.valueOf(error.getCode()), reply -> {});
}
cameraStateFlutterApi.create(
instanceManager.addHostCreatedInstance(instance),
new CameraStateTypeData.Builder().setValue(type).build(),
instanceManager.getIdentifierForStrongReference(error),
callback);
}
/** Converts CameraX CameraState.Type to CameraStateType that the Dart side understands. */
@NonNull
public static CameraStateType getCameraStateType(@NonNull CameraState.Type type) {
CameraStateType cameraStateType = null;
switch (type) {
case CLOSED:
cameraStateType = CameraStateType.CLOSED;
break;
case CLOSING:
cameraStateType = CameraStateType.CLOSING;
break;
case OPEN:
cameraStateType = CameraStateType.OPEN;
break;
case OPENING:
cameraStateType = CameraStateType.OPENING;
break;
case PENDING_OPEN:
cameraStateType = CameraStateType.PENDING_OPEN;
break;
}
if (cameraStateType == null) {
throw new IllegalArgumentException(
"The CameraState.Type passed to this method was not recognized.");
}
return cameraStateType;
}
/** Sets the Flutter API used to send messages to Dart. */
@VisibleForTesting
void setApi(@NonNull CameraStateFlutterApi api) {
this.cameraStateFlutterApi = api;
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java",
"repo_id": "packages",
"token_count": 1226
} | 988 |
// 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.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.WeakHashMap;
/**
* Maintains instances used to communicate with the corresponding objects in Dart.
*
* <p>Objects stored in this container are represented by an object in Dart that is also stored in
* an InstanceManager with the same identifier.
*
* <p>When an instance is added with an identifier, either can be used to retrieve the other.
*
* <p>Added instances are added as a weak reference and a strong reference. When the strong
* reference is removed with `{@link #remove(long)}` and the weak reference is deallocated, the
* `finalizationListener` is made with the instance's identifier. However, if the strong reference
* is removed and then the identifier is retrieved with the intention to pass the identifier to Dart
* (e.g. calling {@link #getIdentifierForStrongReference(Object)}), the strong reference to the
* instance is recreated. The strong reference will then need to be removed manually again.
*/
@SuppressWarnings("unchecked")
public class InstanceManager {
// Identifiers are locked to a specific range to avoid collisions with objects
// created simultaneously from Dart.
// Host uses identifiers >= 2^16 and Dart is expected to use values n where,
// 0 <= n < 2^16.
private static final long MIN_HOST_CREATED_IDENTIFIER = 65536;
private static final long CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL = 30000;
private static final String TAG = "InstanceManager";
/** Interface for listening when a weak reference of an instance is removed from the manager. */
public interface FinalizationListener {
void onFinalize(long identifier);
}
private final WeakHashMap<Object, Long> identifiers = new WeakHashMap<>();
private final HashMap<Long, WeakReference<Object>> weakInstances = new HashMap<>();
private final HashMap<Long, Object> strongInstances = new HashMap<>();
private final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
private final HashMap<WeakReference<Object>, Long> weakReferencesToIdentifiers = new HashMap<>();
private final Handler handler = new Handler(Looper.getMainLooper());
private final FinalizationListener finalizationListener;
private long nextIdentifier = MIN_HOST_CREATED_IDENTIFIER;
private boolean hasFinalizationListenerStopped = false;
/**
* Instantiate a new manager.
*
* <p>When the manager is no longer needed, {@link #stopFinalizationListener()} must be called.
*
* @param finalizationListener the listener for garbage collected weak references.
* @return a new `InstanceManager`.
*/
@NonNull
public static InstanceManager create(@NonNull FinalizationListener finalizationListener) {
return new InstanceManager(finalizationListener);
}
private InstanceManager(FinalizationListener finalizationListener) {
this.finalizationListener = finalizationListener;
handler.postDelayed(
this::releaseAllFinalizedInstances, CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL);
}
/**
* Removes `identifier` and its associated strongly referenced instance, if present, from the
* manager.
*
* @param identifier the identifier paired to an instance.
* @param <T> the expected return type.
* @return the removed instance if the manager contains the given identifier, otherwise `null` if
* the manager doesn't contain the value.
*/
@Nullable
public <T> T remove(long identifier) {
logWarningIfFinalizationListenerHasStopped();
return (T) strongInstances.remove(identifier);
}
/**
* Retrieves the identifier paired with an instance.
*
* <p>If the manager contains a strong reference to `instance`, it will return the identifier
* associated with `instance`. If the manager contains only a weak reference to `instance`, a new
* strong reference to `instance` will be added and will need to be removed again with {@link
* #remove(long)}.
*
* <p>If this method returns a nonnull identifier, this method also expects the Dart
* `InstanceManager` to have, or recreate, a weak reference to the Dart instance the identifier is
* associated with.
*
* @param instance an instance that may be stored in the manager.
* @return the identifier associated with `instance` if the manager contains the value, otherwise
* `null` if the manager doesn't contain the value.
*/
@Nullable
public Long getIdentifierForStrongReference(@Nullable Object instance) {
logWarningIfFinalizationListenerHasStopped();
final Long identifier = identifiers.get(instance);
if (identifier != null) {
strongInstances.put(identifier, instance);
}
return identifier;
}
/**
* Adds a new instance that was instantiated from Dart.
*
* <p>The same instance can be added multiple times, but each identifier must be unique. This
* allows two objects that are equivalent (e.g. the `equals` method returns true and their
* hashcodes are equal) to both be added.
*
* @param instance the instance to be stored.
* @param identifier the identifier to be paired with instance. This value must be >= 0 and
* unique.
*/
public void addDartCreatedInstance(@NonNull Object instance, long identifier) {
logWarningIfFinalizationListenerHasStopped();
addInstance(instance, identifier);
}
/**
* Adds a new instance that was instantiated from the host platform.
*
* @param instance the instance to be stored. This must be unique to all other added instances.
* @return the unique identifier (>= 0) stored with instance.
*/
public long addHostCreatedInstance(@NonNull Object instance) {
logWarningIfFinalizationListenerHasStopped();
if (containsInstance(instance)) {
throw new IllegalArgumentException(
"Instance of " + instance.getClass() + " has already been added.");
}
final long identifier = nextIdentifier++;
addInstance(instance, identifier);
return identifier;
}
/**
* Retrieves the instance associated with identifier.
*
* @param identifier the identifier associated with an instance.
* @param <T> the expected return type.
* @return the instance associated with `identifier` if the manager contains the value, otherwise
* `null` if the manager doesn't contain the value.
*/
@Nullable
public <T> T getInstance(long identifier) {
logWarningIfFinalizationListenerHasStopped();
final WeakReference<T> instance = (WeakReference<T>) weakInstances.get(identifier);
if (instance != null) {
return instance.get();
}
return null;
}
/**
* Returns whether this manager contains the given `instance`.
*
* @param instance the instance whose presence in this manager is to be tested.
* @return whether this manager contains the given `instance`.
*/
public boolean containsInstance(@Nullable Object instance) {
logWarningIfFinalizationListenerHasStopped();
return identifiers.containsKey(instance);
}
/**
* Stop the periodic run of the {@link FinalizationListener} for instances that have been garbage
* collected.
*
* <p>The InstanceManager can continue to be used, but the {@link FinalizationListener} will no
* longer be called and methods will log a warning.
*/
public void stopFinalizationListener() {
handler.removeCallbacks(this::releaseAllFinalizedInstances);
hasFinalizationListenerStopped = true;
}
/**
* Removes all of the instances from this manager.
*
* <p>The manager will be empty after this call returns.
*/
public void clear() {
identifiers.clear();
weakInstances.clear();
strongInstances.clear();
weakReferencesToIdentifiers.clear();
}
/**
* Whether the {@link FinalizationListener} is still being called for instances that are garbage
* collected.
*
* <p>See {@link #stopFinalizationListener()}.
*/
public boolean hasFinalizationListenerStopped() {
return hasFinalizationListenerStopped;
}
private void releaseAllFinalizedInstances() {
if (hasFinalizationListenerStopped()) {
return;
}
WeakReference<Object> reference;
while ((reference = (WeakReference<Object>) referenceQueue.poll()) != null) {
final Long identifier = weakReferencesToIdentifiers.remove(reference);
if (identifier != null) {
weakInstances.remove(identifier);
strongInstances.remove(identifier);
finalizationListener.onFinalize(identifier);
}
}
handler.postDelayed(
this::releaseAllFinalizedInstances, CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL);
}
private void addInstance(Object instance, long identifier) {
if (identifier < 0) {
throw new IllegalArgumentException(String.format("Identifier must be >= 0: %d", identifier));
}
if (weakInstances.containsKey(identifier)) {
throw new IllegalArgumentException(
String.format("Identifier has already been added: %d", identifier));
}
final WeakReference<Object> weakReference = new WeakReference<>(instance, referenceQueue);
identifiers.put(instance, identifier);
weakInstances.put(identifier, weakReference);
weakReferencesToIdentifiers.put(weakReference, identifier);
strongInstances.put(identifier, instance);
}
private void logWarningIfFinalizationListenerHasStopped() {
if (hasFinalizationListenerStopped()) {
Log.w(TAG, "The manager was used after calls to the FinalizationListener have been stopped.");
}
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java",
"repo_id": "packages",
"token_count": 2859
} | 989 |
// 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.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.PendingRecording;
import androidx.camera.video.Recorder;
import androidx.core.content.ContextCompat;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecorderHostApi;
import java.io.File;
import java.util.Objects;
import java.util.concurrent.Executor;
public class RecorderHostApiImpl implements RecorderHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
@Nullable private Context context;
@NonNull @VisibleForTesting public CameraXProxy cameraXProxy = new CameraXProxy();
@NonNull @VisibleForTesting public PendingRecordingFlutterApiImpl pendingRecordingFlutterApi;
public RecorderHostApiImpl(
@Nullable BinaryMessenger binaryMessenger,
@NonNull InstanceManager instanceManager,
@Nullable Context context) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
this.context = context;
this.pendingRecordingFlutterApi =
new PendingRecordingFlutterApiImpl(binaryMessenger, instanceManager);
}
@Override
public void create(
@NonNull Long instanceId,
@Nullable Long aspectRatio,
@Nullable Long bitRate,
@Nullable Long qualitySelector) {
if (context == null) {
throw new IllegalStateException("Context must be set to create Recorder instance.");
}
Recorder.Builder recorderBuilder = cameraXProxy.createRecorderBuilder();
if (aspectRatio != null) {
recorderBuilder.setAspectRatio(aspectRatio.intValue());
}
if (bitRate != null) {
recorderBuilder.setTargetVideoEncodingBitRate(bitRate.intValue());
}
if (qualitySelector != null) {
recorderBuilder.setQualitySelector(
Objects.requireNonNull(instanceManager.getInstance(qualitySelector)));
}
Recorder recorder = recorderBuilder.setExecutor(ContextCompat.getMainExecutor(context)).build();
instanceManager.addDartCreatedInstance(recorder, instanceId);
}
/** Sets the context, which is used to get the {@link Executor} passed to the Recorder builder. */
public void setContext(@Nullable Context context) {
this.context = context;
}
/** Gets the aspect ratio of the given {@link Recorder}. */
@NonNull
@Override
public Long getAspectRatio(@NonNull Long identifier) {
Recorder recorder = getRecorderFromInstanceId(identifier);
return Long.valueOf(recorder.getAspectRatio());
}
/** Gets the target video encoding bitrate of the given {@link Recorder}. */
@NonNull
@Override
public Long getTargetVideoEncodingBitRate(@NonNull Long identifier) {
Recorder recorder = getRecorderFromInstanceId(identifier);
return Long.valueOf(recorder.getTargetVideoEncodingBitRate());
}
/**
* Uses the provided {@link Recorder} to prepare a recording that will be saved to a file at the
* provided path.
*/
@NonNull
@Override
public Long prepareRecording(@NonNull Long identifier, @NonNull String path) {
if (context == null) {
throw new IllegalStateException("Context must be set to prepare recording.");
}
Recorder recorder = getRecorderFromInstanceId(identifier);
File temporaryCaptureFile = openTempFile(path);
FileOutputOptions fileOutputOptions =
new FileOutputOptions.Builder(temporaryCaptureFile).build();
PendingRecording pendingRecording = recorder.prepareRecording(context, fileOutputOptions);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED) {
pendingRecording.withAudioEnabled();
}
pendingRecordingFlutterApi.create(pendingRecording, reply -> {});
return Objects.requireNonNull(
instanceManager.getIdentifierForStrongReference(pendingRecording));
}
@Nullable
@VisibleForTesting
public File openTempFile(@NonNull String path) {
File file = null;
try {
file = new File(path);
} catch (NullPointerException | SecurityException e) {
throw new RuntimeException(e);
}
return file;
}
private Recorder getRecorderFromInstanceId(Long instanceId) {
return (Recorder) Objects.requireNonNull(instanceManager.getInstance(instanceId));
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java",
"repo_id": "packages",
"token_count": 1482
} | 990 |
// 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 junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.pm.PackageManager;
import io.flutter.plugins.camerax.CameraPermissionsManager.CameraRequestPermissionsListener;
import io.flutter.plugins.camerax.CameraPermissionsManager.ResultCallback;
import org.junit.Test;
public class CameraPermissionsManagerTest {
@Test
public void listener_respondsOnce() {
final int[] calledCounter = {0};
CameraRequestPermissionsListener permissionsListener =
new CameraRequestPermissionsListener((String code, String desc) -> calledCounter[0]++);
permissionsListener.onRequestPermissionsResult(
9796, null, new int[] {PackageManager.PERMISSION_DENIED});
permissionsListener.onRequestPermissionsResult(
9796, null, new int[] {PackageManager.PERMISSION_GRANTED});
assertEquals(1, calledCounter[0]);
}
@Test
public void callback_respondsWithCameraAccessDenied() {
ResultCallback fakeResultCallback = mock(ResultCallback.class);
CameraRequestPermissionsListener permissionsListener =
new CameraRequestPermissionsListener(fakeResultCallback);
permissionsListener.onRequestPermissionsResult(
9796, null, new int[] {PackageManager.PERMISSION_DENIED});
verify(fakeResultCallback)
.onResult("CameraAccessDenied", "Camera access permission was denied.");
}
@Test
public void callback_respondsWithAudioAccessDenied() {
ResultCallback fakeResultCallback = mock(ResultCallback.class);
CameraRequestPermissionsListener permissionsListener =
new CameraRequestPermissionsListener(fakeResultCallback);
permissionsListener.onRequestPermissionsResult(
9796,
null,
new int[] {PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED});
verify(fakeResultCallback).onResult("AudioAccessDenied", "Audio access permission was denied.");
}
@Test
public void callback_doesNotRespond() {
ResultCallback fakeResultCallback = mock(ResultCallback.class);
CameraRequestPermissionsListener permissionsListener =
new CameraRequestPermissionsListener(fakeResultCallback);
permissionsListener.onRequestPermissionsResult(
9796,
null,
new int[] {PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED});
verify(fakeResultCallback, never())
.onResult("CameraAccessDenied", "Camera access permission was denied.");
verify(fakeResultCallback, never())
.onResult("AudioAccessDenied", "Audio access permission was denied.");
}
@Test
public void callback_respondsWithCameraAccessDeniedWhenEmptyResult() {
// Handles the case where the grantResults array is empty
ResultCallback fakeResultCallback = mock(ResultCallback.class);
CameraRequestPermissionsListener permissionsListener =
new CameraRequestPermissionsListener(fakeResultCallback);
permissionsListener.onRequestPermissionsResult(9796, null, new int[] {});
verify(fakeResultCallback)
.onResult("CameraAccessDenied", "Camera access permission was denied.");
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java",
"repo_id": "packages",
"token_count": 1028
} | 991 |
// 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.assertNull;
import org.junit.Test;
public class JavaObjectHostApiTest {
@Test
public void dispose() {
final InstanceManager instanceManager = InstanceManager.create(identifier -> {});
final JavaObjectHostApiImpl hostApi = new JavaObjectHostApiImpl(instanceManager);
Object object = new Object();
instanceManager.addDartCreatedInstance(object, 0);
// To free object for garbage collection.
//noinspection UnusedAssignment
object = null;
hostApi.dispose(0L);
Runtime.getRuntime().gc();
assertNull(instanceManager.getInstance(0));
instanceManager.stopFinalizationListener();
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java",
"repo_id": "packages",
"token_count": 266
} | 992 |
// 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' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Represents exposure related information of a camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/ExposureState.
@immutable
class ExposureState extends JavaObject {
/// Constructs a [ExposureState] that is not automatically attached to a native object.
ExposureState.detached(
{super.binaryMessenger,
super.instanceManager,
required this.exposureCompensationRange,
required this.exposureCompensationStep})
: super.detached() {
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
/// Gets the maximum and minimum exposure compensation values for the camera
/// represented by this instance.
final ExposureCompensationRange exposureCompensationRange;
/// Gets the smallest step by which the exposure compensation can be changed for
/// the camera represented by this instance.
final double exposureCompensationStep;
}
/// Flutter API implementation of [ExposureState].
class ExposureStateFlutterApiImpl implements ExposureStateFlutterApi {
/// Constructs a [ExposureStateFlutterApiImpl].
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created.
ExposureStateFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(
int identifier,
ExposureCompensationRange exposureCompensationRange,
double exposureCompensationStep) {
instanceManager.addHostCreatedInstance(
ExposureState.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
exposureCompensationRange: exposureCompensationRange,
exposureCompensationStep: exposureCompensationStep),
identifier,
onCopy: (ExposureState original) {
return ExposureState.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
exposureCompensationRange: original.exposureCompensationRange,
exposureCompensationStep: original.exposureCompensationStep);
},
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/exposure_state.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/exposure_state.dart",
"repo_id": "packages",
"token_count": 868
} | 993 |
// 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 'camera_info.dart';
import 'camerax_library.g.dart';
import 'fallback_strategy.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Quality setting used to configure components with quality setting
/// requirements such as creating a Recorder.
///
/// See https://developer.android.com/reference/androidx/camera/video/QualitySelector.
@immutable
class QualitySelector extends JavaObject {
/// Creates a [QualitySelector] with the desired quality and fallback
/// strategy, if specified.
QualitySelector.from(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required VideoQualityData quality,
this.fallbackStrategy})
: qualityList = <VideoQualityData>[quality],
super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _QualitySelectorHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstance(this, qualityList, fallbackStrategy);
}
/// Creates a [QualitySelector] with ordered desired qualities and fallback
/// strategy, if specified.
///
/// The final quality will be selected according to the order in which they are
/// specified.
QualitySelector.fromOrderedList(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required this.qualityList,
this.fallbackStrategy})
: assert(qualityList.isNotEmpty,
'Quality list specified must be non-empty.'),
super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _QualitySelectorHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstance(this, qualityList, fallbackStrategy);
}
/// Creates a [QualitySelector] that is not automatically attached to a
/// native object.
QualitySelector.detached({
super.binaryMessenger,
super.instanceManager,
required this.qualityList,
this.fallbackStrategy,
}) : super.detached();
late final _QualitySelectorHostApiImpl _api;
/// Desired qualities for this selector instance.
final List<VideoQualityData> qualityList;
/// Desired fallback strategy for this selector instance.
final FallbackStrategy? fallbackStrategy;
/// Retrieves the corresponding resolution from the input [quality] for the
/// camera represented by [cameraInfo].
static Future<ResolutionInfo> getResolution(
CameraInfo cameraInfo, VideoQuality quality,
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) {
final _QualitySelectorHostApiImpl api = _QualitySelectorHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
return api.getResolutionFromInstance(cameraInfo, quality);
}
}
/// Host API implementation of [QualitySelector].
class _QualitySelectorHostApiImpl extends QualitySelectorHostApi {
/// Constructs a [QualitySelectorHostApiImpl].
///
/// 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].
_QualitySelectorHostApiImpl(
{this.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default [BinaryMessenger] will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Creates a [QualitySelector] instance with the desired qualities and
/// fallback strategy specified.
void createFromInstance(QualitySelector instance,
List<VideoQualityData> qualityList, FallbackStrategy? fallbackStrategy) {
final int identifier = instanceManager.addDartCreatedInstance(instance,
onCopy: (QualitySelector original) {
return QualitySelector.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
qualityList: original.qualityList,
fallbackStrategy: original.fallbackStrategy,
);
});
create(
identifier,
qualityList,
fallbackStrategy == null
? null
: instanceManager.getIdentifier(fallbackStrategy));
}
/// Retrieves the corresponding resolution from the input [quality] for the
/// camera represented by [cameraInfo].
Future<ResolutionInfo> getResolutionFromInstance(
CameraInfo cameraInfo, VideoQuality quality) async {
final int? cameraInfoIdentifier = instanceManager.getIdentifier(cameraInfo);
if (cameraInfoIdentifier == null) {
throw ArgumentError(
'The CameraInfo instance specified needs to be added to the InstanceManager instance in use.');
}
final ResolutionInfo resolution =
await getResolution(cameraInfoIdentifier, quality);
return resolution;
}
}
| packages/packages/camera/camera_android_camerax/lib/src/quality_selector.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/quality_selector.dart",
"repo_id": "packages",
"token_count": 1698
} | 994 |
// 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/aspect_ratio_strategy.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'aspect_ratio_strategy_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
TestAspectRatioStrategyHostApi,
TestInstanceManagerHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('AspectRatioStrategy', () {
tearDown(() {
TestAspectRatioStrategyHostApi.setup(null);
TestInstanceManagerHostApi.setup(null);
});
test(
'detached create does not make call to create expected AspectRatioStrategy instance',
() async {
final MockTestAspectRatioStrategyHostApi mockApi =
MockTestAspectRatioStrategyHostApi();
TestAspectRatioStrategyHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int preferredAspectRatio = 1;
const int fallbackRule = 1;
AspectRatioStrategy.detached(
preferredAspectRatio: preferredAspectRatio,
fallbackRule: fallbackRule,
instanceManager: instanceManager,
);
verifyNever(mockApi.create(
argThat(isA<int>()),
preferredAspectRatio,
fallbackRule,
));
});
test(
'HostApi create makes call to create expected AspectRatioStrategy instance',
() {
final MockTestAspectRatioStrategyHostApi mockApi =
MockTestAspectRatioStrategyHostApi();
TestAspectRatioStrategyHostApi.setup(mockApi);
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int preferredAspectRatio = 0;
const int fallbackRule = 0;
final AspectRatioStrategy instance = AspectRatioStrategy(
preferredAspectRatio: preferredAspectRatio,
fallbackRule: fallbackRule,
instanceManager: instanceManager,
);
verify(mockApi.create(
instanceManager.getIdentifier(instance),
preferredAspectRatio,
fallbackRule,
));
});
});
}
| packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart",
"repo_id": "packages",
"token_count": 984
} | 995 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/capture_request_options.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'capture_request_options_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(
<Type>[TestCaptureRequestOptionsHostApi, TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('CaptureRequestOptions', () {
tearDown(() {
TestCaptureRequestOptionsHostApi.setup(null);
TestInstanceManagerHostApi.setup(null);
});
test('detached create does not make call on the Java side', () {
final MockTestCaptureRequestOptionsHostApi mockApi =
MockTestCaptureRequestOptionsHostApi();
TestCaptureRequestOptionsHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final List<(CaptureRequestKeySupportedType, Object?)> options =
<(CaptureRequestKeySupportedType, Object?)>[
(CaptureRequestKeySupportedType.controlAeLock, true),
];
CaptureRequestOptions.detached(
requestedOptions: options,
instanceManager: instanceManager,
);
verifyNever(mockApi.create(
argThat(isA<int>()),
argThat(isA<Map<int, Object?>>()),
));
});
test(
'create makes call on the Java side as expected for suppported null capture request options',
() {
final MockTestCaptureRequestOptionsHostApi mockApi =
MockTestCaptureRequestOptionsHostApi();
TestCaptureRequestOptionsHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final List<(CaptureRequestKeySupportedType key, Object? value)>
supportedOptionsForTesting = <(
CaptureRequestKeySupportedType key,
Object? value
)>[(CaptureRequestKeySupportedType.controlAeLock, null)];
final CaptureRequestOptions instance = CaptureRequestOptions(
requestedOptions: supportedOptionsForTesting,
instanceManager: instanceManager,
);
final VerificationResult verificationResult = verify(mockApi.create(
instanceManager.getIdentifier(instance),
captureAny,
));
final Map<int?, Object?> captureRequestOptions =
verificationResult.captured.single as Map<int?, Object?>;
expect(captureRequestOptions.length,
equals(supportedOptionsForTesting.length));
for (final (CaptureRequestKeySupportedType key, Object? value) option
in supportedOptionsForTesting) {
final CaptureRequestKeySupportedType optionKey = option.$1;
expect(captureRequestOptions[optionKey.index], isNull);
}
});
test(
'create makes call on the Java side as expected for suppported non-null capture request options',
() {
final MockTestCaptureRequestOptionsHostApi mockApi =
MockTestCaptureRequestOptionsHostApi();
TestCaptureRequestOptionsHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final List<(CaptureRequestKeySupportedType key, Object? value)>
supportedOptionsForTesting = <(
CaptureRequestKeySupportedType key,
Object? value
)>[(CaptureRequestKeySupportedType.controlAeLock, false)];
final CaptureRequestOptions instance = CaptureRequestOptions(
requestedOptions: supportedOptionsForTesting,
instanceManager: instanceManager,
);
final VerificationResult verificationResult = verify(mockApi.create(
instanceManager.getIdentifier(instance),
captureAny,
));
final Map<int?, Object?>? captureRequestOptions =
verificationResult.captured.single as Map<int?, Object?>?;
expect(captureRequestOptions!.length,
equals(supportedOptionsForTesting.length));
for (final (CaptureRequestKeySupportedType key, Object? value) option
in supportedOptionsForTesting) {
final CaptureRequestKeySupportedType optionKey = option.$1;
final Object? optionValue = option.$2;
switch (optionKey) {
case CaptureRequestKeySupportedType.controlAeLock:
expect(captureRequestOptions[optionKey.index],
equals(optionValue! as bool));
// This ignore statement is safe beause this will test when
// a new CaptureRequestKeySupportedType is being added, but the logic in
// in the CaptureRequestOptions class has not yet been updated.
// ignore: no_default_cases
default:
fail(
'Option $option contains unrecognized CaptureRequestKeySupportedType key ${option.$1}');
}
}
});
});
}
| packages/packages/camera/camera_android_camerax/test/capture_request_options_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/capture_request_options_test.dart",
"repo_id": "packages",
"token_count": 1923
} | 996 |
// 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:camera_android_camerax/src/image_proxy.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/plane_proxy.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'image_proxy_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestImageProxyHostApi, TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('ImageProxy', () {
tearDown(() {
TestImageProxyHostApi.setup(null);
});
test('getPlanes', () async {
final MockTestImageProxyHostApi mockApi = MockTestImageProxyHostApi();
TestImageProxyHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ImageProxy instance = ImageProxy.detached(
instanceManager: instanceManager, format: 2, height: 7, width: 10);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier,
onCopy: (ImageProxy original) => ImageProxy.detached(
instanceManager: instanceManager,
format: original.format,
height: original.height,
width: original.width));
final PlaneProxy planeProxy = PlaneProxy.detached(
instanceManager: instanceManager,
buffer: Uint8List(3),
pixelStride: 3,
rowStride: 20);
const int planeProxyIdentifier = 48;
instanceManager.addHostCreatedInstance(planeProxy, planeProxyIdentifier,
onCopy: (PlaneProxy original) => PlaneProxy.detached(
instanceManager: instanceManager,
buffer: original.buffer,
pixelStride: original.pixelStride,
rowStride: original.rowStride));
final List<int> result = <int>[planeProxyIdentifier];
when(mockApi.getPlanes(
instanceIdentifier,
)).thenAnswer((_) {
return result;
});
final List<PlaneProxy> planes = await instance.getPlanes();
expect(planes[0], equals(planeProxy));
verify(mockApi.getPlanes(
instanceIdentifier,
));
});
test('close', () async {
final MockTestImageProxyHostApi mockApi = MockTestImageProxyHostApi();
TestImageProxyHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ImageProxy instance = ImageProxy.detached(
instanceManager: instanceManager, format: 2, height: 7, width: 10);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier,
onCopy: (ImageProxy original) => ImageProxy.detached(
instanceManager: instanceManager,
format: original.format,
height: original.height,
width: original.width));
await instance.close();
verify(mockApi.close(
instanceIdentifier,
));
});
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ImageProxyFlutterApiImpl api = ImageProxyFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
const int format = 9;
const int height = 55;
const int width = 11;
api.create(
instanceIdentifier,
format,
height,
width,
);
final ImageProxy imageProxy =
instanceManager.getInstanceWithWeakReference(instanceIdentifier)!;
expect(imageProxy.format, equals(format));
expect(imageProxy.height, equals(height));
expect(imageProxy.width, equals(width));
});
});
}
| packages/packages/camera/camera_android_camerax/test/image_proxy_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/image_proxy_test.dart",
"repo_id": "packages",
"token_count": 1640
} | 997 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/process_camera_provider_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' 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 [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,
);
}
/// A class which mocks [TestProcessCameraProviderHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestProcessCameraProviderHostApi extends _i1.Mock
implements _i2.TestProcessCameraProviderHostApi {
MockTestProcessCameraProviderHostApi() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<int> getInstance() => (super.noSuchMethod(
Invocation.method(
#getInstance,
[],
),
returnValue: _i3.Future<int>.value(0),
) as _i3.Future<int>);
@override
List<int?> getAvailableCameraInfos(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getAvailableCameraInfos,
[identifier],
),
returnValue: <int?>[],
) as List<int?>);
@override
int bindToLifecycle(
int? identifier,
int? cameraSelectorIdentifier,
List<int?>? useCaseIds,
) =>
(super.noSuchMethod(
Invocation.method(
#bindToLifecycle,
[
identifier,
cameraSelectorIdentifier,
useCaseIds,
],
),
returnValue: 0,
) as int);
@override
bool isBound(
int? identifier,
int? useCaseIdentifier,
) =>
(super.noSuchMethod(
Invocation.method(
#isBound,
[
identifier,
useCaseIdentifier,
],
),
returnValue: false,
) as bool);
@override
void unbind(
int? identifier,
List<int?>? useCaseIds,
) =>
super.noSuchMethod(
Invocation.method(
#unbind,
[
identifier,
useCaseIds,
],
),
returnValueForMissingStub: null,
);
@override
void unbindAll(int? identifier) => super.noSuchMethod(
Invocation.method(
#unbindAll,
[identifier],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart",
"repo_id": "packages",
"token_count": 1442
} | 998 |
// 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/instance_manager.dart';
import 'package:camera_android_camerax/src/zoom_state.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'test_camerax_library.g.dart';
import 'zoom_state_test.mocks.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('ZoomState', () {
test('flutterApi create makes call to create expected ZoomState', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ZoomStateFlutterApiImpl flutterApi = ZoomStateFlutterApiImpl(
instanceManager: instanceManager,
);
const int zoomStateIdentifier = 68;
const double minZoomRatio = 0;
const double maxZoomRatio = 1;
flutterApi.create(zoomStateIdentifier, minZoomRatio, maxZoomRatio);
final ZoomState instance = instanceManager
.getInstanceWithWeakReference(zoomStateIdentifier)! as ZoomState;
expect(instance.minZoomRatio, equals(minZoomRatio));
expect(instance.maxZoomRatio, equals(maxZoomRatio));
});
});
}
| packages/packages/camera/camera_android_camerax/test/zoom_state_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/zoom_state_test.dart",
"repo_id": "packages",
"token_count": 522
} | 999 |
// 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 "CameraProperties.h"
#pragma mark - flash mode
FLTFlashMode FLTGetFLTFlashModeForString(NSString *mode) {
if ([mode isEqualToString:@"off"]) {
return FLTFlashModeOff;
} else if ([mode isEqualToString:@"auto"]) {
return FLTFlashModeAuto;
} else if ([mode isEqualToString:@"always"]) {
return FLTFlashModeAlways;
} else if ([mode isEqualToString:@"torch"]) {
return FLTFlashModeTorch;
} else {
return FLTFlashModeInvalid;
}
}
AVCaptureFlashMode FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashMode mode) {
switch (mode) {
case FLTFlashModeOff:
return AVCaptureFlashModeOff;
case FLTFlashModeAuto:
return AVCaptureFlashModeAuto;
case FLTFlashModeAlways:
return AVCaptureFlashModeOn;
case FLTFlashModeTorch:
default:
return -1;
}
}
#pragma mark - exposure mode
NSString *FLTGetStringForFLTExposureMode(FLTExposureMode mode) {
switch (mode) {
case FLTExposureModeAuto:
return @"auto";
case FLTExposureModeLocked:
return @"locked";
case FLTExposureModeInvalid:
// This value should never actually be used.
return nil;
}
return nil;
}
FLTExposureMode FLTGetFLTExposureModeForString(NSString *mode) {
if ([mode isEqualToString:@"auto"]) {
return FLTExposureModeAuto;
} else if ([mode isEqualToString:@"locked"]) {
return FLTExposureModeLocked;
} else {
return FLTExposureModeInvalid;
}
}
#pragma mark - focus mode
NSString *FLTGetStringForFLTFocusMode(FLTFocusMode mode) {
switch (mode) {
case FLTFocusModeAuto:
return @"auto";
case FLTFocusModeLocked:
return @"locked";
case FLTFocusModeInvalid:
// This value should never actually be used.
return nil;
}
return nil;
}
FLTFocusMode FLTGetFLTFocusModeForString(NSString *mode) {
if ([mode isEqualToString:@"auto"]) {
return FLTFocusModeAuto;
} else if ([mode isEqualToString:@"locked"]) {
return FLTFocusModeLocked;
} else {
return FLTFocusModeInvalid;
}
}
#pragma mark - device orientation
UIDeviceOrientation FLTGetUIDeviceOrientationForString(NSString *orientation) {
if ([orientation isEqualToString:@"portraitDown"]) {
return UIDeviceOrientationPortraitUpsideDown;
} else if ([orientation isEqualToString:@"landscapeLeft"]) {
return UIDeviceOrientationLandscapeLeft;
} else if ([orientation isEqualToString:@"landscapeRight"]) {
return UIDeviceOrientationLandscapeRight;
} else if ([orientation isEqualToString:@"portraitUp"]) {
return UIDeviceOrientationPortrait;
} else {
return UIDeviceOrientationUnknown;
}
}
NSString *FLTGetStringForUIDeviceOrientation(UIDeviceOrientation orientation) {
switch (orientation) {
case UIDeviceOrientationPortraitUpsideDown:
return @"portraitDown";
case UIDeviceOrientationLandscapeLeft:
return @"landscapeLeft";
case UIDeviceOrientationLandscapeRight:
return @"landscapeRight";
case UIDeviceOrientationPortrait:
default:
return @"portraitUp";
};
}
#pragma mark - resolution preset
FLTResolutionPreset FLTGetFLTResolutionPresetForString(NSString *preset) {
if ([preset isEqualToString:@"veryLow"]) {
return FLTResolutionPresetVeryLow;
} else if ([preset isEqualToString:@"low"]) {
return FLTResolutionPresetLow;
} else if ([preset isEqualToString:@"medium"]) {
return FLTResolutionPresetMedium;
} else if ([preset isEqualToString:@"high"]) {
return FLTResolutionPresetHigh;
} else if ([preset isEqualToString:@"veryHigh"]) {
return FLTResolutionPresetVeryHigh;
} else if ([preset isEqualToString:@"ultraHigh"]) {
return FLTResolutionPresetUltraHigh;
} else if ([preset isEqualToString:@"max"]) {
return FLTResolutionPresetMax;
} else {
return FLTResolutionPresetInvalid;
}
}
#pragma mark - video format
OSType FLTGetVideoFormatFromString(NSString *videoFormatString) {
if ([videoFormatString isEqualToString:@"bgra8888"]) {
return kCVPixelFormatType_32BGRA;
} else if ([videoFormatString isEqualToString:@"yuv420"]) {
return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
} else {
NSLog(@"The selected imageFormatGroup is not supported by iOS. Defaulting to brga8888");
return kCVPixelFormatType_32BGRA;
}
}
#pragma mark - file format
FCPFileFormat FCPGetFileFormatFromString(NSString *fileFormatString) {
if ([fileFormatString isEqualToString:@"jpg"]) {
return FCPFileFormatJPEG;
} else if ([fileFormatString isEqualToString:@"heif"]) {
return FCPFileFormatHEIF;
} else {
return FCPFileFormatInvalid;
}
} | packages/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.m",
"repo_id": "packages",
"token_count": 1786
} | 1,000 |
# camera_platform_interface
A common platform interface for the [`camera`][1] plugin.
This interface allows platform-specific implementations of the `camera`
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.
# Usage
To implement a new platform-specific implementation of `camera`, extend
[`CameraPlatform`][2] with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the default
`CameraPlatform` by calling
`CameraPlatform.instance = MyPlatformCamera()`.
# Note on breaking changes
Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.
See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less-clean interface is preferable to a breaking change.
[1]: ../camera
[2]: lib/camera_platform_interface.dart
| packages/packages/camera/camera_platform_interface/README.md/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/README.md",
"repo_id": "packages",
"token_count": 220
} | 1,001 |
// 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.
/// Affect the quality of video recording and image capture:
///
/// A preset is treated as a target resolution, and exact values are not
/// guaranteed. Platform implementations may fall back to a higher or lower
/// resolution if a specific preset is not available.
enum ResolutionPreset {
/// 352x288 on iOS, ~240p on Android and Web
low,
/// ~480p
medium,
/// ~720p
high,
/// ~1080p
veryHigh,
/// ~2160p
ultraHigh,
/// The highest resolution available.
max,
}
| packages/packages/camera/camera_platform_interface/lib/src/types/resolution_preset.dart/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/lib/src/types/resolution_preset.dart",
"repo_id": "packages",
"token_count": 180
} | 1,002 |
// 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:html';
import 'package:async/async.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_web/camera_web.dart';
import 'package:camera_web/src/camera.dart';
import 'package:camera_web/src/camera_service.dart';
import 'package:camera_web/src/types/types.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mocktail/mocktail.dart';
import 'helpers/helpers.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('CameraPlugin', () {
const int cameraId = 1;
late Window window;
late Navigator navigator;
late MediaDevices mediaDevices;
late VideoElement videoElement;
late Screen screen;
late ScreenOrientation screenOrientation;
late Document document;
late Element documentElement;
late CameraService cameraService;
setUp(() async {
window = MockWindow();
navigator = MockNavigator();
mediaDevices = MockMediaDevices();
videoElement = getVideoElementWithBlankStream(const Size(10, 10));
when(() => window.navigator).thenReturn(navigator);
when(() => navigator.mediaDevices).thenReturn(mediaDevices);
screen = MockScreen();
screenOrientation = MockScreenOrientation();
when(() => screen.orientation).thenReturn(screenOrientation);
when(() => window.screen).thenReturn(screen);
document = MockDocument();
documentElement = MockElement();
when(() => document.documentElement).thenReturn(documentElement);
when(() => window.document).thenReturn(document);
cameraService = MockCameraService();
when(
() => cameraService.getMediaStreamForOptions(
any(),
cameraId: any(named: 'cameraId'),
),
).thenAnswer(
(_) async => videoElement.captureStream(),
);
CameraPlatform.instance = CameraPlugin(
cameraService: cameraService,
)..window = window;
});
setUpAll(() {
registerFallbackValue(MockMediaStreamTrack());
registerFallbackValue(MockCameraOptions());
registerFallbackValue(FlashMode.off);
});
testWidgets('CameraPlugin is the live instance',
(WidgetTester tester) async {
expect(CameraPlatform.instance, isA<CameraPlugin>());
});
group('availableCameras', () {
setUp(() {
when(
() => cameraService.getFacingModeForVideoTrack(
any(),
),
).thenReturn(null);
when(mediaDevices.enumerateDevices).thenAnswer(
(_) async => <dynamic>[],
);
});
testWidgets('requests video permissions', (WidgetTester tester) async {
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
verify(
() => cameraService.getMediaStreamForOptions(const CameraOptions()),
).called(1);
});
testWidgets(
'releases the camera stream '
'used to request video permissions', (WidgetTester tester) async {
final MockMediaStreamTrack videoTrack = MockMediaStreamTrack();
bool videoTrackStopped = false;
when(videoTrack.stop).thenAnswer((Invocation _) {
videoTrackStopped = true;
});
when(
() => cameraService.getMediaStreamForOptions(const CameraOptions()),
).thenAnswer(
(_) => Future<MediaStream>.value(
FakeMediaStream(<MediaStreamTrack>[videoTrack]),
),
);
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
expect(videoTrackStopped, isTrue);
});
testWidgets(
'gets a video stream '
'for a video input device', (WidgetTester tester) async {
final FakeMediaDeviceInfo videoDevice = FakeMediaDeviceInfo(
'1',
'Camera 1',
MediaDeviceKind.videoInput,
);
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[videoDevice]),
);
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
verify(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(
deviceId: videoDevice.deviceId,
),
),
),
).called(1);
});
testWidgets(
'does not get a video stream '
'for the video input device '
'with an empty device id', (WidgetTester tester) async {
final FakeMediaDeviceInfo videoDevice = FakeMediaDeviceInfo(
'',
'Camera 1',
MediaDeviceKind.videoInput,
);
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[videoDevice]),
);
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
verifyNever(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(
deviceId: videoDevice.deviceId,
),
),
),
);
});
testWidgets(
'gets the facing mode '
'from the first available video track '
'of the video input device', (WidgetTester tester) async {
final FakeMediaDeviceInfo videoDevice = FakeMediaDeviceInfo(
'1',
'Camera 1',
MediaDeviceKind.videoInput,
);
final FakeMediaStream videoStream = FakeMediaStream(
<MediaStreamTrack>[MockMediaStreamTrack(), MockMediaStreamTrack()]);
when(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(deviceId: videoDevice.deviceId),
),
),
).thenAnswer((Invocation _) => Future<MediaStream>.value(videoStream));
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[videoDevice]),
);
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
verify(
() => cameraService.getFacingModeForVideoTrack(
videoStream.getVideoTracks().first,
),
).called(1);
});
testWidgets(
'returns appropriate camera descriptions '
'for multiple video devices '
'based on video streams', (WidgetTester tester) async {
final FakeMediaDeviceInfo firstVideoDevice = FakeMediaDeviceInfo(
'1',
'Camera 1',
MediaDeviceKind.videoInput,
);
final FakeMediaDeviceInfo secondVideoDevice = FakeMediaDeviceInfo(
'4',
'Camera 4',
MediaDeviceKind.videoInput,
);
// Create a video stream for the first video device.
final FakeMediaStream firstVideoStream = FakeMediaStream(
<MediaStreamTrack>[MockMediaStreamTrack(), MockMediaStreamTrack()]);
// Create a video stream for the second video device.
final FakeMediaStream secondVideoStream =
FakeMediaStream(<MediaStreamTrack>[MockMediaStreamTrack()]);
// Mock media devices to return two video input devices
// and two audio devices.
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[
firstVideoDevice,
FakeMediaDeviceInfo(
'2',
'Audio Input 2',
MediaDeviceKind.audioInput,
),
FakeMediaDeviceInfo(
'3',
'Audio Output 3',
MediaDeviceKind.audioOutput,
),
secondVideoDevice,
]),
);
// Mock camera service to return the first video stream
// for the first video device.
when(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(deviceId: firstVideoDevice.deviceId),
),
),
).thenAnswer(
(Invocation _) => Future<MediaStream>.value(firstVideoStream));
// Mock camera service to return the second video stream
// for the second video device.
when(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(deviceId: secondVideoDevice.deviceId),
),
),
).thenAnswer(
(Invocation _) => Future<MediaStream>.value(secondVideoStream));
// Mock camera service to return a user facing mode
// for the first video stream.
when(
() => cameraService.getFacingModeForVideoTrack(
firstVideoStream.getVideoTracks().first,
),
).thenReturn('user');
when(() => cameraService.mapFacingModeToLensDirection('user'))
.thenReturn(CameraLensDirection.front);
// Mock camera service to return an environment facing mode
// for the second video stream.
when(
() => cameraService.getFacingModeForVideoTrack(
secondVideoStream.getVideoTracks().first,
),
).thenReturn('environment');
when(() => cameraService.mapFacingModeToLensDirection('environment'))
.thenReturn(CameraLensDirection.back);
final List<CameraDescription> cameras =
await CameraPlatform.instance.availableCameras();
// Expect two cameras and ignore two audio devices.
expect(
cameras,
equals(<CameraDescription>[
CameraDescription(
name: firstVideoDevice.label!,
lensDirection: CameraLensDirection.front,
sensorOrientation: 0,
),
CameraDescription(
name: secondVideoDevice.label!,
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
)
]),
);
});
testWidgets(
'sets camera metadata '
'for the camera description', (WidgetTester tester) async {
final FakeMediaDeviceInfo videoDevice = FakeMediaDeviceInfo(
'1',
'Camera 1',
MediaDeviceKind.videoInput,
);
final FakeMediaStream videoStream = FakeMediaStream(
<MediaStreamTrack>[MockMediaStreamTrack(), MockMediaStreamTrack()]);
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[videoDevice]),
);
when(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(deviceId: videoDevice.deviceId),
),
),
).thenAnswer((Invocation _) => Future<MediaStream>.value(videoStream));
when(
() => cameraService.getFacingModeForVideoTrack(
videoStream.getVideoTracks().first,
),
).thenReturn('left');
when(() => cameraService.mapFacingModeToLensDirection('left'))
.thenReturn(CameraLensDirection.external);
final CameraDescription camera =
(await CameraPlatform.instance.availableCameras()).first;
expect(
(CameraPlatform.instance as CameraPlugin).camerasMetadata,
equals(<CameraDescription, CameraMetadata>{
camera: CameraMetadata(
deviceId: videoDevice.deviceId!,
facingMode: 'left',
)
}),
);
});
testWidgets(
'releases the video stream '
'of a video input device', (WidgetTester tester) async {
final FakeMediaDeviceInfo videoDevice = FakeMediaDeviceInfo(
'1',
'Camera 1',
MediaDeviceKind.videoInput,
);
final FakeMediaStream videoStream = FakeMediaStream(
<MediaStreamTrack>[MockMediaStreamTrack(), MockMediaStreamTrack()]);
when(mediaDevices.enumerateDevices).thenAnswer(
(_) => Future<List<dynamic>>.value(<Object>[videoDevice]),
);
when(
() => cameraService.getMediaStreamForOptions(
CameraOptions(
video: VideoConstraints(deviceId: videoDevice.deviceId),
),
),
).thenAnswer((Invocation _) => Future<MediaStream>.value(videoStream));
final List<CameraDescription> _ =
await CameraPlatform.instance.availableCameras();
for (final MediaStreamTrack videoTrack
in videoStream.getVideoTracks()) {
verify(videoTrack.stop).called(1);
}
});
group('throws CameraException', () {
testWidgets(
'with notSupported error '
'when there are no media devices', (WidgetTester tester) async {
when(() => navigator.mediaDevices).thenReturn(null);
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
CameraErrorCode.notSupported.toString(),
),
),
);
});
testWidgets('when MediaDevices.enumerateDevices throws DomException',
(WidgetTester tester) async {
final FakeDomException exception =
FakeDomException(DomException.UNKNOWN);
when(mediaDevices.enumerateDevices).thenThrow(exception);
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets(
'when CameraService.getMediaStreamForOptions '
'throws CameraWebException', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.security,
'description',
);
when(() => cameraService.getMediaStreamForOptions(any()))
.thenThrow(exception);
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
testWidgets(
'when CameraService.getMediaStreamForOptions '
'throws PlatformException', (WidgetTester tester) async {
final PlatformException exception = PlatformException(
code: CameraErrorCode.notSupported.toString(),
message: 'message',
);
when(() => cameraService.getMediaStreamForOptions(any()))
.thenThrow(exception);
expect(
() => CameraPlatform.instance.availableCameras(),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.code,
),
),
);
});
});
});
group('createCamera', () {
group('creates a camera', () {
const Size ultraHighResolutionSize = Size(3840, 2160);
const Size maxResolutionSize = Size(3840, 2160);
const CameraDescription cameraDescription = CameraDescription(
name: 'name',
lensDirection: CameraLensDirection.front,
sensorOrientation: 0,
);
const CameraMetadata cameraMetadata = CameraMetadata(
deviceId: 'deviceId',
facingMode: 'user',
);
setUp(() {
// Add metadata for the camera description.
(CameraPlatform.instance as CameraPlugin)
.camerasMetadata[cameraDescription] = cameraMetadata;
when(
() => cameraService.mapFacingModeToCameraType('user'),
).thenReturn(CameraType.user);
});
testWidgets('with appropriate options', (WidgetTester tester) async {
when(
() => cameraService
.mapResolutionPresetToSize(ResolutionPreset.ultraHigh),
).thenReturn(ultraHighResolutionSize);
final int cameraId = await CameraPlatform.instance.createCamera(
cameraDescription,
ResolutionPreset.ultraHigh,
enableAudio: true,
);
expect(
(CameraPlatform.instance as CameraPlugin).cameras[cameraId],
isA<Camera>()
.having(
(Camera camera) => camera.textureId,
'textureId',
cameraId,
)
.having(
(Camera camera) => camera.options,
'options',
CameraOptions(
audio: const AudioConstraints(enabled: true),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.user),
width: VideoSizeConstraint(
ideal: ultraHighResolutionSize.width.toInt(),
),
height: VideoSizeConstraint(
ideal: ultraHighResolutionSize.height.toInt(),
),
deviceId: cameraMetadata.deviceId,
),
),
),
);
});
testWidgets(
'with a max resolution preset '
'and enabled audio set to false '
'when no options are specified', (WidgetTester tester) async {
when(
() => cameraService.mapResolutionPresetToSize(ResolutionPreset.max),
).thenReturn(maxResolutionSize);
final int cameraId = await CameraPlatform.instance.createCamera(
cameraDescription,
null,
);
expect(
(CameraPlatform.instance as CameraPlugin).cameras[cameraId],
isA<Camera>().having(
(Camera camera) => camera.options,
'options',
CameraOptions(
audio: const AudioConstraints(),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.user),
width: VideoSizeConstraint(
ideal: maxResolutionSize.width.toInt(),
),
height: VideoSizeConstraint(
ideal: maxResolutionSize.height.toInt(),
),
deviceId: cameraMetadata.deviceId,
),
),
),
);
});
});
testWidgets(
'throws CameraException '
'with missingMetadata error '
'if there is no metadata '
'for the given camera description', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.createCamera(
const CameraDescription(
name: 'name',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.ultraHigh,
),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
CameraErrorCode.missingMetadata.toString(),
),
),
);
});
});
group('initializeCamera', () {
late Camera camera;
late VideoElement videoElement;
late StreamController<Event> errorStreamController, abortStreamController;
late StreamController<MediaStreamTrack> endedStreamController;
setUp(() {
camera = MockCamera();
videoElement = MockVideoElement();
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
endedStreamController = StreamController<MediaStreamTrack>();
when(camera.getVideoSize).thenReturn(const Size(10, 10));
when(camera.initialize)
.thenAnswer((Invocation _) => Future<void>.value());
when(camera.play).thenAnswer((Invocation _) => Future<void>.value());
when(() => camera.videoElement).thenReturn(videoElement);
when(() => videoElement.onError).thenAnswer((Invocation _) =>
FakeElementStream<Event>(errorStreamController.stream));
when(() => videoElement.onAbort).thenAnswer((Invocation _) =>
FakeElementStream<Event>(abortStreamController.stream));
when(() => camera.onEnded)
.thenAnswer((Invocation _) => endedStreamController.stream);
});
testWidgets('initializes and plays the camera',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.initializeCamera(cameraId);
verify(camera.initialize).called(1);
verify(camera.play).called(1);
});
testWidgets('starts listening to the camera video error and abort events',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(errorStreamController.hasListener, isFalse);
expect(abortStreamController.hasListener, isFalse);
await CameraPlatform.instance.initializeCamera(cameraId);
expect(errorStreamController.hasListener, isTrue);
expect(abortStreamController.hasListener, isTrue);
});
testWidgets('starts listening to the camera ended events',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(endedStreamController.hasListener, isFalse);
await CameraPlatform.instance.initializeCamera(cameraId);
expect(endedStreamController.hasListener, isTrue);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.initializeCamera(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when camera throws CameraWebException',
(WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.permissionDenied,
'description',
);
when(camera.initialize).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.initializeCamera(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
testWidgets('when camera throws DomException',
(WidgetTester tester) async {
final FakeDomException exception =
FakeDomException(DomException.NOT_ALLOWED);
when(camera.initialize)
.thenAnswer((Invocation _) => Future<void>.value());
when(camera.play).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.initializeCamera(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
});
});
group('lockCaptureOrientation', () {
setUp(() {
when(
() => cameraService.mapDeviceOrientationToOrientationType(any()),
).thenReturn(OrientationType.portraitPrimary);
});
testWidgets(
'requests full-screen mode '
'on documentElement', (WidgetTester tester) async {
await CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.portraitUp,
);
verify(documentElement.requestFullscreen).called(1);
});
testWidgets(
'locks the capture orientation '
'based on the given device orientation', (WidgetTester tester) async {
when(
() => cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.landscapeRight,
),
).thenReturn(OrientationType.landscapeSecondary);
await CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.landscapeRight,
);
verify(
() => cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.landscapeRight,
),
).called(1);
verify(
() => screenOrientation.lock(
OrientationType.landscapeSecondary,
),
).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with orientationNotSupported error '
'when screen is not supported', (WidgetTester tester) async {
when(() => window.screen).thenReturn(null);
expect(
() => CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.portraitUp,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets(
'with orientationNotSupported error '
'when screen orientation is not supported',
(WidgetTester tester) async {
when(() => screen.orientation).thenReturn(null);
expect(
() => CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.portraitUp,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets(
'with orientationNotSupported error '
'when documentElement is not available',
(WidgetTester tester) async {
when(() => document.documentElement).thenReturn(null);
expect(
() => CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.portraitUp,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets('when lock throws DomException',
(WidgetTester tester) async {
final FakeDomException exception =
FakeDomException(DomException.NOT_ALLOWED);
when(() => screenOrientation.lock(any())).thenThrow(exception);
expect(
() => CameraPlatform.instance.lockCaptureOrientation(
cameraId,
DeviceOrientation.portraitDown,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
});
});
group('unlockCaptureOrientation', () {
setUp(() {
when(
() => cameraService.mapDeviceOrientationToOrientationType(any()),
).thenReturn(OrientationType.portraitPrimary);
});
testWidgets('unlocks the capture orientation',
(WidgetTester tester) async {
await CameraPlatform.instance.unlockCaptureOrientation(
cameraId,
);
verify(screenOrientation.unlock).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with orientationNotSupported error '
'when screen is not supported', (WidgetTester tester) async {
when(() => window.screen).thenReturn(null);
expect(
() => CameraPlatform.instance.unlockCaptureOrientation(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets(
'with orientationNotSupported error '
'when screen orientation is not supported',
(WidgetTester tester) async {
when(() => screen.orientation).thenReturn(null);
expect(
() => CameraPlatform.instance.unlockCaptureOrientation(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets(
'with orientationNotSupported error '
'when documentElement is not available',
(WidgetTester tester) async {
when(() => document.documentElement).thenReturn(null);
expect(
() => CameraPlatform.instance.unlockCaptureOrientation(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.orientationNotSupported.toString(),
),
),
);
});
testWidgets('when unlock throws DomException',
(WidgetTester tester) async {
final FakeDomException exception =
FakeDomException(DomException.NOT_ALLOWED);
when(screenOrientation.unlock).thenThrow(exception);
expect(
() => CameraPlatform.instance.unlockCaptureOrientation(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
});
});
group('takePicture', () {
testWidgets('captures a picture', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
final MockXFile capturedPicture = MockXFile();
when(camera.takePicture)
.thenAnswer((Invocation _) => Future<XFile>.value(capturedPicture));
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
final XFile picture =
await CameraPlatform.instance.takePicture(cameraId);
verify(camera.takePicture).called(1);
expect(picture, equals(capturedPicture));
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.takePicture(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when takePicture throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(camera.takePicture).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.takePicture(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when takePicture throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.takePicture).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.takePicture(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('startVideoRecording', () {
late Camera camera;
setUp(() {
camera = MockCamera();
when(camera.startVideoRecording).thenAnswer((Invocation _) async {});
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => const Stream<ErrorEvent>.empty());
});
testWidgets('starts a video recording', (WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.startVideoRecording(cameraId);
verify(camera.startVideoRecording).called(1);
});
testWidgets('listens to the onVideoRecordingError stream',
(WidgetTester tester) async {
final StreamController<ErrorEvent> videoRecordingErrorController =
StreamController<ErrorEvent>();
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => videoRecordingErrorController.stream);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.startVideoRecording(cameraId);
expect(
videoRecordingErrorController.hasListener,
isTrue,
);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.startVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when startVideoRecording throws DomException',
(WidgetTester tester) async {
final FakeDomException exception =
FakeDomException(DomException.INVALID_STATE);
when(camera.startVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.startVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when startVideoRecording throws CameraWebException',
(WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.startVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.startVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('startVideoCapturing', () {
late Camera camera;
setUp(() {
camera = MockCamera();
when(camera.startVideoRecording).thenAnswer((Invocation _) async {});
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => const Stream<ErrorEvent>.empty());
});
testWidgets('fails if trying to stream', (WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.startVideoCapturing(VideoCaptureOptions(
cameraId,
streamCallback: (CameraImageData imageData) {})),
throwsA(
isA<UnimplementedError>(),
),
);
});
});
group('stopVideoRecording', () {
testWidgets('stops a video recording', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
final MockXFile capturedVideo = MockXFile();
when(camera.stopVideoRecording)
.thenAnswer((Invocation _) => Future<XFile>.value(capturedVideo));
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
final XFile video =
await CameraPlatform.instance.stopVideoRecording(cameraId);
verify(camera.stopVideoRecording).called(1);
expect(video, capturedVideo);
});
testWidgets('stops listening to the onVideoRecordingError stream',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final StreamController<ErrorEvent> videoRecordingErrorController =
StreamController<ErrorEvent>();
when(camera.startVideoRecording).thenAnswer((Invocation _) async {});
when(camera.stopVideoRecording)
.thenAnswer((Invocation _) => Future<XFile>.value(MockXFile()));
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => videoRecordingErrorController.stream);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.startVideoRecording(cameraId);
final XFile _ =
await CameraPlatform.instance.stopVideoRecording(cameraId);
expect(
videoRecordingErrorController.hasListener,
isFalse,
);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.stopVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when stopVideoRecording throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.INVALID_STATE);
when(camera.stopVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.stopVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when stopVideoRecording throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.stopVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.stopVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('pauseVideoRecording', () {
testWidgets('pauses a video recording', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
when(camera.pauseVideoRecording).thenAnswer((Invocation _) async {});
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.pauseVideoRecording(cameraId);
verify(camera.pauseVideoRecording).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.pauseVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when pauseVideoRecording throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.INVALID_STATE);
when(camera.pauseVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.pauseVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when pauseVideoRecording throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.pauseVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.pauseVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('resumeVideoRecording', () {
testWidgets('resumes a video recording', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
when(camera.resumeVideoRecording).thenAnswer((Invocation _) async {});
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.resumeVideoRecording(cameraId);
verify(camera.resumeVideoRecording).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.resumeVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when resumeVideoRecording throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.INVALID_STATE);
when(camera.resumeVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.resumeVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when resumeVideoRecording throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.resumeVideoRecording).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.resumeVideoRecording(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('setFlashMode', () {
testWidgets('calls setFlashMode on the camera',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
const FlashMode flashMode = FlashMode.always;
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.setFlashMode(
cameraId,
flashMode,
);
verify(() => camera.setFlashMode(flashMode)).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setFlashMode(
cameraId,
FlashMode.always,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when setFlashMode throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(() => camera.setFlashMode(any())).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.setFlashMode(
cameraId,
FlashMode.always,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when setFlashMode throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(() => camera.setFlashMode(any())).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.setFlashMode(
cameraId,
FlashMode.torch,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
testWidgets('setExposureMode throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setExposureMode(
cameraId,
ExposureMode.auto,
),
throwsUnimplementedError,
);
});
testWidgets('setExposurePoint throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setExposurePoint(
cameraId,
const Point<double>(0, 0),
),
throwsUnimplementedError,
);
});
testWidgets('getMinExposureOffset throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.getMinExposureOffset(cameraId),
throwsUnimplementedError,
);
});
testWidgets('getMaxExposureOffset throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.getMaxExposureOffset(cameraId),
throwsUnimplementedError,
);
});
testWidgets('getExposureOffsetStepSize throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.getExposureOffsetStepSize(cameraId),
throwsUnimplementedError,
);
});
testWidgets('setExposureOffset throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setExposureOffset(
cameraId,
0,
),
throwsUnimplementedError,
);
});
testWidgets('setFocusMode throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setFocusMode(
cameraId,
FocusMode.auto,
),
throwsUnimplementedError,
);
});
testWidgets('setFocusPoint throws UnimplementedError',
(WidgetTester tester) async {
expect(
() => CameraPlatform.instance.setFocusPoint(
cameraId,
const Point<double>(0, 0),
),
throwsUnimplementedError,
);
});
group('getMaxZoomLevel', () {
testWidgets('calls getMaxZoomLevel on the camera',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
const double maximumZoomLevel = 100.0;
when(camera.getMaxZoomLevel).thenReturn(maximumZoomLevel);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
await CameraPlatform.instance.getMaxZoomLevel(
cameraId,
),
equals(maximumZoomLevel),
);
verify(camera.getMaxZoomLevel).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() async => CameraPlatform.instance.getMaxZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when getMaxZoomLevel throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(camera.getMaxZoomLevel).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.getMaxZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when getMaxZoomLevel throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.getMaxZoomLevel).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.getMaxZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('getMinZoomLevel', () {
testWidgets('calls getMinZoomLevel on the camera',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
const double minimumZoomLevel = 100.0;
when(camera.getMinZoomLevel).thenReturn(minimumZoomLevel);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
await CameraPlatform.instance.getMinZoomLevel(
cameraId,
),
equals(minimumZoomLevel),
);
verify(camera.getMinZoomLevel).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() async => CameraPlatform.instance.getMinZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when getMinZoomLevel throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(camera.getMinZoomLevel).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.getMinZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when getMinZoomLevel throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.getMinZoomLevel).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.getMinZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('setZoomLevel', () {
testWidgets('calls setZoomLevel on the camera',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
const double zoom = 100.0;
await CameraPlatform.instance.setZoomLevel(cameraId, zoom);
verify(() => camera.setZoomLevel(zoom)).called(1);
});
group('throws CameraException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() async => CameraPlatform.instance.setZoomLevel(
cameraId,
100.0,
),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when setZoomLevel throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(() => camera.setZoomLevel(any())).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.setZoomLevel(
cameraId,
100.0,
),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when setZoomLevel throws PlatformException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final PlatformException exception = PlatformException(
code: CameraErrorCode.notSupported.toString(),
message: 'message',
);
when(() => camera.setZoomLevel(any())).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.setZoomLevel(
cameraId,
100.0,
),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.code,
),
),
);
});
testWidgets('when setZoomLevel throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(() => camera.setZoomLevel(any())).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.setZoomLevel(
cameraId,
100.0,
),
throwsA(
isA<CameraException>().having(
(CameraException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
group('pausePreview', () {
testWidgets('calls pause on the camera', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.pausePreview(cameraId);
verify(camera.pause).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() async => CameraPlatform.instance.pausePreview(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when pause throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(camera.pause).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.pausePreview(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
});
});
group('resumePreview', () {
testWidgets('calls play on the camera', (WidgetTester tester) async {
final MockCamera camera = MockCamera();
when(camera.play).thenAnswer((Invocation _) async {});
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.resumePreview(cameraId);
verify(camera.play).called(1);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() async => CameraPlatform.instance.resumePreview(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when play throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.NOT_SUPPORTED);
when(camera.play).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.resumePreview(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
testWidgets('when play throws CameraWebException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.unknown,
'description',
);
when(camera.play).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() async => CameraPlatform.instance.resumePreview(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.code.toString(),
),
),
);
});
});
});
testWidgets(
'buildPreview returns an HtmlElementView '
'with an appropriate view type', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: cameraId,
cameraService: cameraService,
);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
CameraPlatform.instance.buildPreview(cameraId),
isA<widgets.HtmlElementView>().having(
(widgets.HtmlElementView view) => view.viewType,
'viewType',
camera.getViewType(),
),
);
});
group('dispose', () {
late Camera camera;
late VideoElement videoElement;
late StreamController<Event> errorStreamController, abortStreamController;
late StreamController<MediaStreamTrack> endedStreamController;
late StreamController<ErrorEvent> videoRecordingErrorController;
setUp(() {
camera = MockCamera();
videoElement = MockVideoElement();
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
endedStreamController = StreamController<MediaStreamTrack>();
videoRecordingErrorController = StreamController<ErrorEvent>();
when(camera.getVideoSize).thenReturn(const Size(10, 10));
when(camera.initialize)
.thenAnswer((Invocation _) => Future<void>.value());
when(camera.play).thenAnswer((Invocation _) => Future<void>.value());
when(camera.dispose).thenAnswer((Invocation _) => Future<void>.value());
when(() => camera.videoElement).thenReturn(videoElement);
when(() => videoElement.onError).thenAnswer((Invocation _) =>
FakeElementStream<Event>(errorStreamController.stream));
when(() => videoElement.onAbort).thenAnswer((Invocation _) =>
FakeElementStream<Event>(abortStreamController.stream));
when(() => camera.onEnded)
.thenAnswer((Invocation _) => endedStreamController.stream);
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => videoRecordingErrorController.stream);
when(camera.startVideoRecording).thenAnswer((Invocation _) async {});
});
testWidgets('disposes the correct camera', (WidgetTester tester) async {
const int firstCameraId = 0;
const int secondCameraId = 1;
final MockCamera firstCamera = MockCamera();
final MockCamera secondCamera = MockCamera();
when(firstCamera.dispose)
.thenAnswer((Invocation _) => Future<void>.value());
when(secondCamera.dispose)
.thenAnswer((Invocation _) => Future<void>.value());
// Save cameras in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras.addAll(<int, Camera>{
firstCameraId: firstCamera,
secondCameraId: secondCamera,
});
// Dispose the first camera.
await CameraPlatform.instance.dispose(firstCameraId);
// The first camera should be disposed.
verify(firstCamera.dispose).called(1);
verifyNever(secondCamera.dispose);
// The first camera should be removed from the camera plugin.
expect(
(CameraPlatform.instance as CameraPlugin).cameras,
equals(<int, Camera>{
secondCameraId: secondCamera,
}),
);
});
testWidgets('cancels the camera video error and abort subscriptions',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.initializeCamera(cameraId);
await CameraPlatform.instance.dispose(cameraId);
expect(errorStreamController.hasListener, isFalse);
expect(abortStreamController.hasListener, isFalse);
});
testWidgets('cancels the camera ended subscriptions',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.initializeCamera(cameraId);
await CameraPlatform.instance.dispose(cameraId);
expect(endedStreamController.hasListener, isFalse);
});
testWidgets('cancels the camera video recording error subscriptions',
(WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
await CameraPlatform.instance.initializeCamera(cameraId);
await CameraPlatform.instance.startVideoRecording(cameraId);
await CameraPlatform.instance.dispose(cameraId);
expect(videoRecordingErrorController.hasListener, isFalse);
});
group('throws PlatformException', () {
testWidgets(
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => CameraPlatform.instance.dispose(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
testWidgets('when dispose throws DomException',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final FakeDomException exception =
FakeDomException(DomException.INVALID_ACCESS);
when(camera.dispose).thenThrow(exception);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
() => CameraPlatform.instance.dispose(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
exception.name,
),
),
);
});
});
});
group('getCamera', () {
testWidgets('returns the correct camera', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: cameraId,
cameraService: cameraService,
);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
expect(
(CameraPlatform.instance as CameraPlugin).getCamera(cameraId),
equals(camera),
);
});
testWidgets(
'throws PlatformException '
'with notFound error '
'if the camera does not exist', (WidgetTester tester) async {
expect(
() => (CameraPlatform.instance as CameraPlugin).getCamera(cameraId),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notFound.toString(),
),
),
);
});
});
group('events', () {
late Camera camera;
late VideoElement videoElement;
late StreamController<Event> errorStreamController, abortStreamController;
late StreamController<MediaStreamTrack> endedStreamController;
late StreamController<ErrorEvent> videoRecordingErrorController;
setUp(() {
camera = MockCamera();
videoElement = MockVideoElement();
errorStreamController = StreamController<Event>();
abortStreamController = StreamController<Event>();
endedStreamController = StreamController<MediaStreamTrack>();
videoRecordingErrorController = StreamController<ErrorEvent>();
when(camera.getVideoSize).thenReturn(const Size(10, 10));
when(camera.initialize)
.thenAnswer((Invocation _) => Future<void>.value());
when(camera.play).thenAnswer((Invocation _) => Future<void>.value());
when(() => camera.videoElement).thenReturn(videoElement);
when(() => videoElement.onError).thenAnswer((Invocation _) =>
FakeElementStream<Event>(errorStreamController.stream));
when(() => videoElement.onAbort).thenAnswer((Invocation _) =>
FakeElementStream<Event>(abortStreamController.stream));
when(() => camera.onEnded)
.thenAnswer((Invocation _) => endedStreamController.stream);
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => videoRecordingErrorController.stream);
when(() => camera.startVideoRecording())
.thenAnswer((Invocation _) async {});
});
testWidgets(
'onCameraInitialized emits a CameraInitializedEvent '
'on initializeCamera', (WidgetTester tester) async {
// Mock the camera to use a blank video stream of size 1280x720.
const Size videoSize = Size(1280, 720);
videoElement = getVideoElementWithBlankStream(videoSize);
when(
() => cameraService.getMediaStreamForOptions(
any(),
cameraId: cameraId,
),
).thenAnswer((Invocation _) async => videoElement.captureStream());
final Camera camera = Camera(
textureId: cameraId,
cameraService: cameraService,
);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
final Stream<CameraInitializedEvent> eventStream =
CameraPlatform.instance.onCameraInitialized(cameraId);
final StreamQueue<CameraInitializedEvent> streamQueue =
StreamQueue<CameraInitializedEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
expect(
await streamQueue.next,
equals(
CameraInitializedEvent(
cameraId,
videoSize.width,
videoSize.height,
ExposureMode.auto,
false,
FocusMode.auto,
false,
),
),
);
await streamQueue.cancel();
});
testWidgets('onCameraResolutionChanged emits an empty stream',
(WidgetTester tester) async {
final Stream<CameraResolutionChangedEvent> stream =
CameraPlatform.instance.onCameraResolutionChanged(cameraId);
expect(await stream.isEmpty, isTrue);
});
testWidgets(
'onCameraClosing emits a CameraClosingEvent '
'on the camera ended event', (WidgetTester tester) async {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
final Stream<CameraClosingEvent> eventStream =
CameraPlatform.instance.onCameraClosing(cameraId);
final StreamQueue<CameraClosingEvent> streamQueue =
StreamQueue<CameraClosingEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
endedStreamController.add(MockMediaStreamTrack());
expect(
await streamQueue.next,
equals(
const CameraClosingEvent(cameraId),
),
);
await streamQueue.cancel();
});
group('onCameraError', () {
setUp(() {
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
});
testWidgets(
'emits a CameraErrorEvent '
'on the camera video error event '
'with a message', (WidgetTester tester) async {
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
final FakeMediaError error = FakeMediaError(
MediaError.MEDIA_ERR_NETWORK,
'A network error occured.',
);
final CameraErrorCode errorCode =
CameraErrorCode.fromMediaError(error);
when(() => videoElement.error).thenReturn(error);
errorStreamController.add(Event('error'));
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: $errorCode, error message: ${error.message}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on the camera video error event '
'with no message', (WidgetTester tester) async {
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
final FakeMediaError error =
FakeMediaError(MediaError.MEDIA_ERR_NETWORK);
final CameraErrorCode errorCode =
CameraErrorCode.fromMediaError(error);
when(() => videoElement.error).thenReturn(error);
errorStreamController.add(Event('error'));
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: $errorCode, error message: No further diagnostic information can be determined or provided.',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on the camera video abort event', (WidgetTester tester) async {
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
abortStreamController.add(Event('abort'));
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
"Error code: ${CameraErrorCode.abort}, error message: The video element's source has not fully loaded.",
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on takePicture error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.takePicture).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.takePicture(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on setFlashMode error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(() => camera.setFlashMode(any())).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.setFlashMode(
cameraId,
FlashMode.always,
),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on getMaxZoomLevel error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.zoomLevelNotSupported,
'description',
);
when(camera.getMaxZoomLevel).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.getMaxZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on getMinZoomLevel error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.zoomLevelNotSupported,
'description',
);
when(camera.getMinZoomLevel).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.getMinZoomLevel(
cameraId,
),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on setZoomLevel error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.zoomLevelNotSupported,
'description',
);
when(() => camera.setZoomLevel(any())).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.setZoomLevel(
cameraId,
100.0,
),
throwsA(
isA<CameraException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on resumePreview error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.unknown,
'description',
);
when(camera.play).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.resumePreview(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on startVideoRecording error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(() => camera.onVideoRecordingError)
.thenAnswer((Invocation _) => const Stream<ErrorEvent>.empty());
when(
() => camera.startVideoRecording(
maxVideoDuration: any(named: 'maxVideoDuration'),
),
).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.startVideoRecording(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on the camera video recording error event',
(WidgetTester tester) async {
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
await CameraPlatform.instance.initializeCamera(cameraId);
await CameraPlatform.instance.startVideoRecording(cameraId);
final FakeErrorEvent errorEvent = FakeErrorEvent('type', 'message');
videoRecordingErrorController.add(errorEvent);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on stopVideoRecording error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.stopVideoRecording).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.stopVideoRecording(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on pauseVideoRecording error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.pauseVideoRecording).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.pauseVideoRecording(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a CameraErrorEvent '
'on resumeVideoRecording error', (WidgetTester tester) async {
final CameraWebException exception = CameraWebException(
cameraId,
CameraErrorCode.notStarted,
'description',
);
when(camera.resumeVideoRecording).thenThrow(exception);
final Stream<CameraErrorEvent> eventStream =
CameraPlatform.instance.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
expect(
() async => CameraPlatform.instance.resumeVideoRecording(cameraId),
throwsA(
isA<PlatformException>(),
),
);
expect(
await streamQueue.next,
equals(
CameraErrorEvent(
cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
),
);
await streamQueue.cancel();
});
});
testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent',
(WidgetTester tester) async {
final MockCamera camera = MockCamera();
final MockXFile capturedVideo = MockXFile();
final Stream<VideoRecordedEvent> stream =
Stream<VideoRecordedEvent>.value(
VideoRecordedEvent(cameraId, capturedVideo, Duration.zero));
when(() => camera.onVideoRecordedEvent)
.thenAnswer((Invocation _) => stream);
// Save the camera in the camera plugin.
(CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera;
final StreamQueue<VideoRecordedEvent> streamQueue =
StreamQueue<VideoRecordedEvent>(
CameraPlatform.instance.onVideoRecordedEvent(cameraId));
expect(
await streamQueue.next,
equals(
VideoRecordedEvent(cameraId, capturedVideo, Duration.zero),
),
);
});
group('onDeviceOrientationChanged', () {
group('emits an empty stream', () {
testWidgets('when screen is not supported',
(WidgetTester tester) async {
when(() => window.screen).thenReturn(null);
final Stream<DeviceOrientationChangedEvent> stream =
CameraPlatform.instance.onDeviceOrientationChanged();
expect(await stream.isEmpty, isTrue);
});
testWidgets('when screen orientation is not supported',
(WidgetTester tester) async {
when(() => screen.orientation).thenReturn(null);
final Stream<DeviceOrientationChangedEvent> stream =
CameraPlatform.instance.onDeviceOrientationChanged();
expect(await stream.isEmpty, isTrue);
});
});
testWidgets('emits the initial DeviceOrientationChangedEvent',
(WidgetTester tester) async {
when(
() => cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.portraitPrimary,
),
).thenReturn(DeviceOrientation.portraitUp);
// Set the initial screen orientation to portraitPrimary.
when(() => screenOrientation.type)
.thenReturn(OrientationType.portraitPrimary);
final StreamController<Event> eventStreamController =
StreamController<Event>();
when(() => screenOrientation.onChange)
.thenAnswer((Invocation _) => eventStreamController.stream);
final Stream<DeviceOrientationChangedEvent> eventStream =
CameraPlatform.instance.onDeviceOrientationChanged();
final StreamQueue<DeviceOrientationChangedEvent> streamQueue =
StreamQueue<DeviceOrientationChangedEvent>(eventStream);
expect(
await streamQueue.next,
equals(
const DeviceOrientationChangedEvent(
DeviceOrientation.portraitUp,
),
),
);
await streamQueue.cancel();
});
testWidgets(
'emits a DeviceOrientationChangedEvent '
'when the screen orientation is changed',
(WidgetTester tester) async {
when(
() => cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.landscapePrimary,
),
).thenReturn(DeviceOrientation.landscapeLeft);
when(
() => cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.portraitSecondary,
),
).thenReturn(DeviceOrientation.portraitDown);
final StreamController<Event> eventStreamController =
StreamController<Event>();
when(() => screenOrientation.onChange)
.thenAnswer((Invocation _) => eventStreamController.stream);
final Stream<DeviceOrientationChangedEvent> eventStream =
CameraPlatform.instance.onDeviceOrientationChanged();
final StreamQueue<DeviceOrientationChangedEvent> streamQueue =
StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Change the screen orientation to landscapePrimary and
// emit an event on the screenOrientation.onChange stream.
when(() => screenOrientation.type)
.thenReturn(OrientationType.landscapePrimary);
eventStreamController.add(Event('change'));
expect(
await streamQueue.next,
equals(
const DeviceOrientationChangedEvent(
DeviceOrientation.landscapeLeft,
),
),
);
// Change the screen orientation to portraitSecondary and
// emit an event on the screenOrientation.onChange stream.
when(() => screenOrientation.type)
.thenReturn(OrientationType.portraitSecondary);
eventStreamController.add(Event('change'));
expect(
await streamQueue.next,
equals(
const DeviceOrientationChangedEvent(
DeviceOrientation.portraitDown,
),
),
);
await streamQueue.cancel();
});
});
});
});
}
| packages/packages/camera/camera_web/example/integration_test/camera_web_test.dart/0 | {
"file_path": "packages/packages/camera/camera_web/example/integration_test/camera_web_test.dart",
"repo_id": "packages",
"token_count": 45624
} | 1,003 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
/// Options used to create a camera with the given
/// [audio] and [video] media constraints.
///
/// These options represent web `MediaStreamConstraints`
/// and can be used to request the browser for media streams
/// with audio and video tracks containing the requested types of media.
///
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints
@immutable
class CameraOptions {
/// Creates a new instance of [CameraOptions]
/// with the given [audio] and [video] constraints.
const CameraOptions({
AudioConstraints? audio,
VideoConstraints? video,
}) : audio = audio ?? const AudioConstraints(),
video = video ?? const VideoConstraints();
/// The audio constraints for the camera.
final AudioConstraints audio;
/// The video constraints for the camera.
final VideoConstraints video;
/// Converts the current instance to a Map.
Map<String, dynamic> toJson() {
return <String, Object>{
'audio': audio.toJson(),
'video': video.toJson(),
};
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is CameraOptions &&
other.audio == audio &&
other.video == video;
}
@override
int get hashCode => Object.hash(audio, video);
}
/// Indicates whether the audio track is requested.
///
/// By default, the audio track is not requested.
@immutable
class AudioConstraints {
/// Creates a new instance of [AudioConstraints]
/// with the given [enabled] constraint.
const AudioConstraints({this.enabled = false});
/// Whether the audio track should be enabled.
final bool enabled;
/// Converts the current instance to a Map.
Object toJson() => enabled;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is AudioConstraints && other.enabled == enabled;
}
@override
int get hashCode => enabled.hashCode;
}
/// Defines constraints that the video track must have
/// to be considered acceptable.
@immutable
class VideoConstraints {
/// Creates a new instance of [VideoConstraints]
/// with the given constraints.
const VideoConstraints({
this.facingMode,
this.width,
this.height,
this.deviceId,
});
/// The facing mode of the video track.
final FacingModeConstraint? facingMode;
/// The width of the video track.
final VideoSizeConstraint? width;
/// The height of the video track.
final VideoSizeConstraint? height;
/// The device id of the video track.
final String? deviceId;
/// Converts the current instance to a Map.
Object toJson() {
final Map<String, dynamic> json = <String, dynamic>{};
if (width != null) {
json['width'] = width!.toJson();
}
if (height != null) {
json['height'] = height!.toJson();
}
if (facingMode != null) {
json['facingMode'] = facingMode!.toJson();
}
if (deviceId != null) {
json['deviceId'] = <String, Object>{'exact': deviceId!};
}
return json;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is VideoConstraints &&
other.facingMode == facingMode &&
other.width == width &&
other.height == height &&
other.deviceId == deviceId;
}
@override
int get hashCode => Object.hash(facingMode, width, height, deviceId);
}
/// The camera type used in [FacingModeConstraint].
///
/// Specifies whether the requested camera should be facing away
/// or toward the user.
enum CameraType {
/// The camera is facing away from the user, viewing their environment.
/// This includes the back camera on a smartphone.
environment._('environment'),
/// The camera is facing toward the user.
/// This includes the front camera on a smartphone.
user._('user');
const CameraType._(this._type);
final String _type;
@override
String toString() => _type;
}
/// Indicates the direction in which the desired camera should be pointing.
@immutable
class FacingModeConstraint {
/// Creates a new instance of [FacingModeConstraint]
/// with [ideal] constraint set to [type].
factory FacingModeConstraint(CameraType type) =>
FacingModeConstraint._(ideal: type);
/// Creates a new instance of [FacingModeConstraint]
/// with the given [ideal] and [exact] constraints.
const FacingModeConstraint._({this.ideal, this.exact});
/// Creates a new instance of [FacingModeConstraint]
/// with [exact] constraint set to [type].
factory FacingModeConstraint.exact(CameraType type) =>
FacingModeConstraint._(exact: type);
/// The ideal facing mode constraint.
///
/// If this constraint is used, then the camera would ideally have
/// the desired facing [type] but it may be considered optional.
final CameraType? ideal;
/// The exact facing mode constraint.
///
/// If this constraint is used, then the camera must have
/// the desired facing [type] to be considered acceptable.
final CameraType? exact;
/// Converts the current instance to a Map.
Object toJson() {
return <String, Object>{
if (ideal != null) 'ideal': ideal.toString(),
if (exact != null) 'exact': exact.toString(),
};
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is FacingModeConstraint &&
other.ideal == ideal &&
other.exact == exact;
}
@override
int get hashCode => Object.hash(ideal, exact);
}
/// The size of the requested video track used in
/// [VideoConstraints.width] and [VideoConstraints.height].
///
/// The obtained video track will have a size between [minimum] and [maximum]
/// with ideally a size of [ideal]. The size is determined by
/// the capabilities of the hardware and the other specified constraints.
@immutable
class VideoSizeConstraint {
/// Creates a new instance of [VideoSizeConstraint] with the given
/// [minimum], [ideal] and [maximum] constraints.
const VideoSizeConstraint({this.minimum, this.ideal, this.maximum});
/// The minimum video size.
final int? minimum;
/// The ideal video size.
///
/// The video would ideally have the [ideal] size
/// but it may be considered optional. If not possible
/// to satisfy, the size will be as close as possible
/// to [ideal].
final int? ideal;
/// The maximum video size.
final int? maximum;
/// Converts the current instance to a Map.
Object toJson() {
final Map<String, dynamic> json = <String, dynamic>{};
if (ideal != null) {
json['ideal'] = ideal;
}
if (minimum != null) {
json['min'] = minimum;
}
if (maximum != null) {
json['max'] = maximum;
}
return json;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is VideoSizeConstraint &&
other.minimum == minimum &&
other.ideal == ideal &&
other.maximum == maximum;
}
@override
int get hashCode => Object.hash(minimum, ideal, maximum);
}
| packages/packages/camera/camera_web/lib/src/types/camera_options.dart/0 | {
"file_path": "packages/packages/camera/camera_web/lib/src/types/camera_options.dart",
"repo_id": "packages",
"token_count": 2354
} | 1,004 |
// 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.
#include "string_utils.h"
#include <shobjidl.h>
#include <windows.h>
#include <string>
namespace camera_windows {
// Converts the given UTF-16 string to UTF-8.
std::string Utf8FromUtf16(const std::wstring& utf16_string) {
if (utf16_string.empty()) {
return std::string();
}
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(),
static_cast<int>(utf16_string.length()), nullptr, 0, nullptr, nullptr);
std::string utf8_string;
if (target_length == 0 || target_length > utf8_string.max_size()) {
return utf8_string;
}
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(),
static_cast<int>(utf16_string.length()), utf8_string.data(),
target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}
// Converts the given UTF-8 string to UTF-16.
std::wstring Utf16FromUtf8(const std::string& utf8_string) {
if (utf8_string.empty()) {
return std::wstring();
}
int target_length =
::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),
static_cast<int>(utf8_string.length()), nullptr, 0);
std::wstring utf16_string;
if (target_length == 0 || target_length > utf16_string.max_size()) {
return utf16_string;
}
utf16_string.resize(target_length);
int converted_length =
::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),
static_cast<int>(utf8_string.length()),
utf16_string.data(), target_length);
if (converted_length == 0) {
return std::wstring();
}
return utf16_string;
}
} // namespace camera_windows
| packages/packages/camera/camera_windows/windows/string_utils.cpp/0 | {
"file_path": "packages/packages/camera/camera_windows/windows/string_utils.cpp",
"repo_id": "packages",
"token_count": 813
} | 1,005 |
// 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:cross_file/cross_file.dart';
import 'package:cross_file_example/readme_excerpts.dart';
import 'package:test/test.dart';
const bool kIsWeb = bool.fromEnvironment('dart.library.js_interop');
void main() {
test('instantiateXFile loads asset file', () async {
// Ensure that the snippet code runs successfully.
final XFile xFile = await instantiateXFile();
// It should have a nonempty path and name.
expect(xFile.path, allOf(isNotNull, isNotEmpty));
expect(xFile.name, allOf(isNotNull, isNotEmpty));
// And the example file should have contents.
final String fileContent = await xFile.readAsString();
expect(fileContent, allOf(isNotNull, isNotEmpty));
}, skip: kIsWeb);
}
| packages/packages/cross_file/example/test/readme_excerpts_test.dart/0 | {
"file_path": "packages/packages/cross_file/example/test/readme_excerpts_test.dart",
"repo_id": "packages",
"token_count": 285
} | 1,006 |
CSS Colors
==========
This package defines color constants for the CSS colors. These color constants
use the [Color](https://api.flutter.dev/flutter/dart-ui/Color-class.html) class
from `dart:ui`, which means they're useful for Flutter apps.
Use
---
<?code-excerpt "test/css_colors_test.dart (Usage)"?>
```dart
final Container orange = Container(color: CSSColors.orange);
```
| packages/packages/css_colors/README.md/0 | {
"file_path": "packages/packages/css_colors/README.md",
"repo_id": "packages",
"token_count": 121
} | 1,007 |
// 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 androidx.test.espresso.flutter.action.ActionUtil.loopUntilCompletion;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.allAsList;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import android.graphics.Rect;
import android.util.Log;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.View;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.action.GeneralClickAction;
import androidx.test.espresso.action.Press;
import androidx.test.espresso.action.Tap;
import androidx.test.espresso.action.TypeTextAction;
import androidx.test.espresso.flutter.api.FlutterTestingProtocol;
import androidx.test.espresso.flutter.api.SyntheticAction;
import androidx.test.espresso.flutter.api.WidgetAction;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.annotations.Expose;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** An action that types text on a Flutter widget. */
public final class FlutterTypeTextAction implements WidgetAction {
private static final String TAG = FlutterTypeTextAction.class.getSimpleName();
private static final String GET_LOCAL_RECT_TASK_NAME = "FlutterTypeTextAction#getLocalRect";
private static final String FLUTTER_IDLE_TASK_NAME = "FlutterTypeTextAction#flutterIsIdle";
private final String stringToBeTyped;
private final boolean tapToFocus;
private final ExecutorService executor;
/**
* Constructs with the given input string. If the string is empty it results in no-op (nothing is
* typed). By default this action sends a tap event to the center of the widget to attain focus
* before typing.
*
* @param stringToBeTyped String To be typed in.
*/
FlutterTypeTextAction(@Nonnull String stringToBeTyped, @Nonnull ExecutorService executor) {
this(stringToBeTyped, executor, true);
}
/**
* Constructs with the given input string. If the string is empty it results in no-op (nothing is
* typed). By default this action sends a tap event to the center of the widget to attain focus
* before typing.
*
* @param stringToBeTyped String To be typed in.
* @param tapToFocus indicates whether a tap should be sent to the underlying widget before
* typing.
*/
FlutterTypeTextAction(
@Nonnull String stringToBeTyped, @Nonnull ExecutorService executor, boolean tapToFocus) {
this.stringToBeTyped = checkNotNull(stringToBeTyped, "The text to type in cannot be null.");
this.executor = checkNotNull(executor);
this.tapToFocus = tapToFocus;
}
@Override
public ListenableFuture<Void> perform(
@Nullable WidgetMatcher targetWidget,
@Nonnull View flutterView,
@Nonnull FlutterTestingProtocol flutterTestingProtocol,
@Nonnull UiController androidUiController) {
// No-op if string is empty.
if (stringToBeTyped.length() == 0) {
Log.w(TAG, "Text string is empty resulting in no-op (nothing is typed).");
return immediateFuture(null);
}
try {
ListenableFuture<Void> setTextEntryEmulationFuture =
JdkFutureAdapters.listenInPoolThread(
flutterTestingProtocol.perform(null, new SetTextEntryEmulationAction(false)));
ListenableFuture<Rect> widgetRectFuture =
JdkFutureAdapters.listenInPoolThread(flutterTestingProtocol.getLocalRect(targetWidget));
// Waits until both Futures return and then proceeds.
Rect widgetRectInDp =
(Rect)
loopUntilCompletion(
GET_LOCAL_RECT_TASK_NAME,
androidUiController,
allAsList(widgetRectFuture, setTextEntryEmulationFuture),
executor)
.get(0);
// Clicks at the center of the Flutter widget (with no visibility check).
//
// Calls the click action separately so we get a chance to ensure Flutter is idle before
// typing text.
WidgetCoordinatesCalculator coordinatesCalculator =
new WidgetCoordinatesCalculator(widgetRectInDp);
if (tapToFocus) {
GeneralClickAction clickAction =
new GeneralClickAction(
Tap.SINGLE,
coordinatesCalculator,
Press.FINGER,
InputDevice.SOURCE_UNKNOWN,
MotionEvent.BUTTON_PRIMARY);
clickAction.perform(androidUiController, flutterView);
loopUntilCompletion(
FLUTTER_IDLE_TASK_NAME,
androidUiController,
flutterTestingProtocol.waitUntilIdle(),
executor);
}
// Then types in text.
ViewAction typeTextAction = new TypeTextAction(stringToBeTyped, false);
typeTextAction.perform(androidUiController, flutterView);
// Espresso will wait for the main thread to finish, so nothing else to wait for in the
// testing thread.
return immediateFuture(null);
} catch (InterruptedException ie) {
return immediateFailedFuture(ie);
} catch (ExecutionException ee) {
return immediateFailedFuture(ee.getCause());
} finally {
androidUiController.loopMainThreadUntilIdle();
}
}
@Override
public String toString() {
return String.format(Locale.ROOT, "type text(%s)", stringToBeTyped);
}
/**
* The {@link SyntheticAction} that configures text entry emulation.
*
* <p>If the text entry emulation is enabled, the operating system's configured keyboard will not
* be invoked when the widget is focused. Explicitly disables the text entry emulation when text
* input is supposed to be sent using the system's keyboard.
*
* <p>By default, the text entry emulation is enabled in the Flutter testing protocol.
*/
private static final class SetTextEntryEmulationAction extends SyntheticAction {
@Expose private final boolean enabled;
/**
* Constructs with the given text entry emulation setting.
*
* @param enabled whether the text entry emulation is enabled. When {@code enabled} is {@code
* true}, the system's configured keyboard will not be invoked when the widget is focused.
*/
public SetTextEntryEmulationAction(boolean enabled) {
super("set_text_entry_emulation");
this.enabled = enabled;
}
/**
* Constructs with the given text entry emulation setting and also a timeout setting for this
* action.
*
* @param enabled whether the text entry emulation is enabled. When {@code enabled} is {@code
* true}, the system's configured keyboard will not be invoked when the widget is focused.
* @param timeOutInMillis the timeout setting of this action.
*/
public SetTextEntryEmulationAction(boolean enabled, long timeOutInMillis) {
super("set_text_entry_emulation", timeOutInMillis);
this.enabled = enabled;
}
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterTypeTextAction.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterTypeTextAction.java",
"repo_id": "packages",
"token_count": 2594
} | 1,008 |
// 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.exception;
import androidx.test.espresso.EspressoException;
/**
* Indicates that a {@code WidgetMatcher} matched multiple widgets in the Flutter UI hierarchy when
* only one widget was expected.
*/
public final class AmbiguousWidgetMatcherException extends RuntimeException
implements EspressoException {
private static final long serialVersionUID = 0L;
public AmbiguousWidgetMatcherException(String message) {
super(message);
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/exception/AmbiguousWidgetMatcherException.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/exception/AmbiguousWidgetMatcherException.java",
"repo_id": "packages",
"token_count": 173
} | 1,009 |
// 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;
import androidx.test.espresso.flutter.api.SyntheticAction;
import com.google.gson.annotations.Expose;
/** Represents an action that retrieves the Flutter widget's diagnostics information. */
final class GetWidgetDiagnosticsAction extends SyntheticAction {
@Expose private final String diagnosticsType = "widget";
/**
* Sets the depth of the retrieved diagnostics tree as 0. This means only the information of the
* root widget will be retrieved.
*/
@Expose private final int subtreeDepth = 0;
/** Always includes the diagnostics properties of this widget. */
@Expose private final boolean includeProperties = true;
GetWidgetDiagnosticsAction() {
super("get_diagnostics_tree");
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsAction.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsAction.java",
"repo_id": "packages",
"token_count": 257
} | 1,010 |
// 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.model;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Builder for {@link WidgetInfo}.
*
* <p>Internal only. Users of Espresso framework should rarely have the needs to build their own
* {@link WidgetInfo} instance.
*/
public class WidgetInfoBuilder {
@Nullable private String valueKey;
private String runtimeType;
@Nullable private String text;
@Nullable private String tooltip;
/** Empty constructor. */
public WidgetInfoBuilder() {}
/**
* Constructs the builder with the given {@code runtimeType}.
*
* @param runtimeType the runtime type of the widget. Cannot be null.
*/
public WidgetInfoBuilder(@Nonnull String runtimeType) {
this.runtimeType = checkNotNull(runtimeType, "RuntimeType cannot be null.");
}
/**
* Sets the value key of the widget.
*
* @param valueKey the value key of the widget that shall be set. Could be null.
*/
public WidgetInfoBuilder setValueKey(@Nullable String valueKey) {
this.valueKey = valueKey;
return this;
}
/**
* Sets the runtime type of the widget.
*
* @param runtimeType the runtime type of the widget that shall be set. Cannot be null.
*/
public WidgetInfoBuilder setRuntimeType(@Nonnull String runtimeType) {
this.runtimeType = checkNotNull(runtimeType, "RuntimeType cannot be null.");
return this;
}
/**
* Sets the text of the widget.
*
* @param text the text of the widget that shall be set. Can be null.
*/
public WidgetInfoBuilder setText(@Nullable String text) {
this.text = text;
return this;
}
/**
* Sets the tooltip of the widget.
*
* @param tooltip the tooltip of the widget that shall be set. Can be null.
*/
public WidgetInfoBuilder setTooltip(@Nullable String tooltip) {
this.tooltip = tooltip;
return this;
}
/** Builds and returns the {@code WidgetInfo} instance. */
public WidgetInfo build() {
return new WidgetInfo(valueKey, runtimeType, text, tooltip);
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/model/WidgetInfoBuilder.java",
"repo_id": "packages",
"token_count": 702
} | 1,011 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.0.12
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Updates README to improve example of using google_sign_in plugin with the `googleapis` package.
## 2.0.11
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.0.10
* Adds compatibility with `http` 1.0.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
* Aligns Dart and Flutter SDK constraints.
## 2.0.9
* Makes the extension compatible with `google_sign_in` version `^5.0.0` and `^6.0.0`.
* Fixes a small typo in the code (`oath` -> `oauth`).
* Updates example app to use `google_sign_in: ^6.0.0`.
## 2.0.8
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.0.7
* Fixes lint warnings.
## 2.0.6
* Drops support for Flutter <2.8.
## 2.0.5
* Updates README to reference the correct github URL.
## 2.0.4
* Update example with the latest changes from `google_sign_in`, so it builds again on Android. [#89301](https://github.com/flutter/flutter/issues/89301).
## 2.0.3
* Adjust formatting of code snippets in README.
## 2.0.2
* Update example to use a scope name as a constant from the People API, instead of a hardcoded string.
* Remove `x` bit from README and pubspec.yaml
## 2.0.1
* Rehomed to `flutter/packages` repository.
* Update to `googleapis_auth: ^1.1.0`.
## 2.0.0
* Migrate to null safety.
* Fixes the requested scopes to use the `GoogleSignIn` instance's `scopes`.
## 1.0.4
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
## 1.0.3
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
## 1.0.2
* Update Flutter SDK constraint.
## 1.0.1
* Update android compileSdkVersion to 29.
## 1.0.0
* First published version.
| packages/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md",
"repo_id": "packages",
"token_count": 676
} | 1,012 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AD_UNIT_ID_FOR_BANNER_TEST</key>
<string>ca-app-pub-3940256099942544/2934735716</string>
<key>AD_UNIT_ID_FOR_INTERSTITIAL_TEST</key>
<string>ca-app-pub-3940256099942544/4411468910</string>
<key>CLIENT_ID</key>
<string>479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com</string>
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u</string>
<key>ANDROID_CLIENT_ID</key>
<string>479882132969-jie8r1me6dsra60pal6ejaj8dgme3tg0.apps.googleusercontent.com</string>
<key>API_KEY</key>
<string>AIzaSyBECOwLTAN6PU4Aet1b2QLGIb3kRK8Xjew</string>
<key>GCM_SENDER_ID</key>
<string>479882132969</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>io.flutter.plugins.googleSignInExample</string>
<key>PROJECT_ID</key>
<string>my-flutter-proj</string>
<key>STORAGE_BUCKET</key>
<string>my-flutter-proj.appspot.com</string>
<key>IS_ADS_ENABLED</key>
<true></true>
<key>IS_ANALYTICS_ENABLED</key>
<false></false>
<key>IS_APPINVITE_ENABLED</key>
<true></true>
<key>IS_GCM_ENABLED</key>
<true></true>
<key>IS_SIGNIN_ENABLED</key>
<true></true>
<key>GOOGLE_APP_ID</key>
<string>1:479882132969:ios:2643f950e0a0da08</string>
<key>DATABASE_URL</key>
<string>https://my-flutter-proj.firebaseio.com</string>
<key>SERVER_CLIENT_ID</key>
<string>YOUR_SERVER_CLIENT_ID</string>
</dict>
</plist>
| packages/packages/extension_google_sign_in_as_googleapis_auth/example/ios/Runner/GoogleService-Info.plist/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/ios/Runner/GoogleService-Info.plist",
"repo_id": "packages",
"token_count": 792
} | 1,013 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 1.0.3
* Fixes a typo in documentation comments.
* Updates support matrix in README to indicate that iOS 11 is no longer supported.
* Clients on versions of Flutter that still support iOS 11 can continue to use this
package with iOS 11, but will not receive any further updates to the iOS implementation.
## 1.0.2
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 1.0.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.
## 1.0.0
* Removes the deprecated `getSavePath` in favor of `getSaveLocation`.
## 0.9.5
* Adds an endorsed Android implementation.
## 0.9.4
* Adds `getSaveLocation` and deprecates `getSavePath`.
* Updates minimum supported macOS version to 10.14.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 0.9.3
* Adds `getDirectoryPaths` for selecting multiple directories.
## 0.9.2+5
* Updates references to the deprecated `macUTIs`.
* Aligns Dart and Flutter SDK constraints.
## 0.9.2+4
* Updates iOS minimum version in README.
## 0.9.2+3
* 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.2+2
* Improves API docs and examples.
* Changes XTypeGroup initialization from final to const.
* Updates minimum Flutter version to 2.10.
## 0.9.2
* Adds an endorsed iOS implementation.
## 0.9.1
* Adds an endorsed Linux implementation.
## 0.9.0
* **BREAKING CHANGE**: The following methods:
* `openFile`
* `openFiles`
* `getSavePath`
can throw `ArgumentError`s if called with any `XTypeGroup`s that
do not contain appropriate filters for the current platform. For
example, an `XTypeGroup` that only specifies `webWildCards` will
throw on non-web platforms.
To avoid runtime errors, ensure that all `XTypeGroup`s (other than
wildcards) set filters that cover every platform your application
targets. See the README for details.
## 0.8.4+3
* Improves API docs and examples.
* Minor fixes for new analysis options.
## 0.8.4+2
* Removes unnecessary imports.
* Adds OS version support information to README.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.8.4+1
* Adds README information about macOS entitlements.
* Adds necessary entitlement to macOS example.
## 0.8.4
* Adds an endorsed macOS implementation.
## 0.8.3
* Adds an endorsed Windows implementation.
## 0.8.2+1
* Minor code cleanup for new analysis rules.
* Updated package description.
## 0.8.2
* Update `platform_plugin_interface` version requirement.
## 0.8.1
Endorse the web implementation.
## 0.8.0
Migrate to null safety.
## 0.7.0+2
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
## 0.7.0+1
* Update Flutter SDK constraint.
## 0.7.0
* Initial Open Source release.
| packages/packages/file_selector/file_selector/CHANGELOG.md/0 | {
"file_path": "packages/packages/file_selector/file_selector/CHANGELOG.md",
"repo_id": "packages",
"token_count": 997
} | 1,014 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Screen that shows an example of getDirectoryPath
class GetDirectoryPage extends StatelessWidget {
/// Default Constructor
GetDirectoryPage({super.key});
final bool _isIOS = !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS;
Future<void> _getDirectoryPath(BuildContext context) async {
const String confirmButtonText = 'Choose';
final String? directoryPath = await getDirectoryPath(
confirmButtonText: confirmButtonText,
);
if (directoryPath == null) {
// Operation was canceled by the user.
return;
}
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => TextDisplay(directoryPath),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open a text file'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
onPressed: _isIOS ? null : () => _getDirectoryPath(context),
child: const Text(
'Press to ask user to choose a directory.',
),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog
class TextDisplay extends StatelessWidget {
/// Default Constructor
const TextDisplay(this.directoryPath, {super.key});
/// Directory path
final String directoryPath;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(directoryPath),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| packages/packages/file_selector/file_selector/example/lib/get_directory_page.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector/example/lib/get_directory_page.dart",
"repo_id": "packages",
"token_count": 932
} | 1,015 |
name: file_selector_ios
description: iOS implementation of the file_selector plugin.
repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.5.1+8
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: file_selector
platforms:
ios:
dartPluginClass: FileSelectorIOS
pluginClass: FFSFileSelectorPlugin
dependencies:
file_selector_platform_interface: ^2.3.0
flutter:
sdk: flutter
dev_dependencies:
build_runner: ^2.3.0
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^13.0.0
topics:
- files
- file-selection
- file-selector
| packages/packages/file_selector/file_selector_ios/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_ios/pubspec.yaml",
"repo_id": "packages",
"token_count": 326
} | 1,016 |
// 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.
#include <flutter_linux/flutter_linux.h>
#include "include/file_selector_linux/file_selector_plugin.h"
// Creates a GtkFileChooserNative for the given method call.
GtkFileChooserNative* create_dialog_for_method(GtkWindow* window,
const gchar* method,
FlValue* properties);
| packages/packages/file_selector/file_selector_linux/linux/file_selector_plugin_private.h/0 | {
"file_path": "packages/packages/file_selector/file_selector_linux/linux/file_selector_plugin_private.h",
"repo_id": "packages",
"token_count": 227
} | 1,017 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select one or more directories using `getDirectoryPaths`,
/// then displays the selected directories in a dialog.
class GetMultipleDirectoriesPage extends StatelessWidget {
/// Default Constructor
const GetMultipleDirectoriesPage({super.key});
Future<void> _getDirectoryPaths(BuildContext context) async {
const String confirmButtonText = 'Choose';
final List<String?> directoriesPaths =
await FileSelectorPlatform.instance.getDirectoryPaths(
confirmButtonText: confirmButtonText,
);
if (directoriesPaths.isEmpty) {
// Operation was canceled by the user.
return;
}
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) =>
TextDisplay(directoriesPaths.join('\n')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Select multiple directories'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
child: const Text(
'Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog.
class TextDisplay extends StatelessWidget {
/// Creates a `TextDisplay`.
const TextDisplay(this.directoryPaths, {super.key});
/// The paths selected in the dialog.
final String directoryPaths;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(directoryPaths),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| packages/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart",
"repo_id": "packages",
"token_count": 966
} | 1,018 |
// 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.
@TestOn('chrome') // web-only package.
library;
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:file_selector_web/src/utils.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('FileSelectorWeb utils', () {
group('acceptedTypesToString', () {
test('works', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[
XTypeGroup(label: 'images', webWildCards: <String>['images/*']),
XTypeGroup(label: 'jpgs', extensions: <String>['jpg', 'jpeg']),
XTypeGroup(label: 'pngs', mimeTypes: <String>['image/png']),
];
final String accepts = acceptedTypesToString(acceptedTypes);
expect(accepts, 'images/*,.jpg,.jpeg,image/png');
});
test('works with an empty list', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[];
final String accepts = acceptedTypesToString(acceptedTypes);
expect(accepts, '');
});
test('works with extensions', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[
XTypeGroup(label: 'jpgs', extensions: <String>['jpeg', 'jpg']),
XTypeGroup(label: 'pngs', extensions: <String>['png']),
];
final String accepts = acceptedTypesToString(acceptedTypes);
expect(accepts, '.jpeg,.jpg,.png');
});
test('works with mime types', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[
XTypeGroup(
label: 'jpgs', mimeTypes: <String>['image/jpeg', 'image/jpg']),
XTypeGroup(label: 'pngs', mimeTypes: <String>['image/png']),
];
final String accepts = acceptedTypesToString(acceptedTypes);
expect(accepts, 'image/jpeg,image/jpg,image/png');
});
test('works with web wild cards', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[
XTypeGroup(label: 'images', webWildCards: <String>['image/*']),
XTypeGroup(label: 'audios', webWildCards: <String>['audio/*']),
XTypeGroup(label: 'videos', webWildCards: <String>['video/*']),
];
final String accepts = acceptedTypesToString(acceptedTypes);
expect(accepts, 'image/*,audio/*,video/*');
});
test('throws for a type group that does not support web', () {
const List<XTypeGroup> acceptedTypes = <XTypeGroup>[
XTypeGroup(
label: 'text', uniformTypeIdentifiers: <String>['public.text']),
];
expect(() => acceptedTypesToString(acceptedTypes), throwsArgumentError);
});
});
});
}
| packages/packages/file_selector/file_selector_web/test/utils_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_web/test/utils_test.dart",
"repo_id": "packages",
"token_count": 1120
} | 1,019 |
// 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.
#ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_
#define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <functional>
#include "file_dialog_controller.h"
#include "messages.g.h"
namespace file_selector_windows {
// Abstraction for accessing the Flutter view's root window, to allow for faking
// in unit tests without creating fake window hierarchies, as well as to work
// around https://github.com/flutter/flutter/issues/90694.
using FlutterRootWindowProvider = std::function<HWND()>;
class FileSelectorPlugin : public flutter::Plugin, public FileSelectorApi {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar);
// Creates a new plugin instance for the given registar, using the given
// factory to create native dialog controllers.
FileSelectorPlugin(
FlutterRootWindowProvider window_provider,
std::unique_ptr<FileDialogControllerFactory> dialog_controller_factory);
virtual ~FileSelectorPlugin();
// FileSelectorApi
ErrorOr<FileDialogResult> ShowOpenDialog(
const SelectionOptions& options, const std::string* initial_directory,
const std::string* confirm_button_text) override;
ErrorOr<FileDialogResult> ShowSaveDialog(
const SelectionOptions& options, const std::string* initialDirectory,
const std::string* suggestedName,
const std::string* confirmButtonText) override;
private:
// The provider for the root window to attach the dialog to.
FlutterRootWindowProvider get_root_window_;
// The factory for creating dialog controller instances.
std::unique_ptr<FileDialogControllerFactory> controller_factory_;
};
} // namespace file_selector_windows
#endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_
| packages/packages/file_selector/file_selector_windows/windows/file_selector_plugin.h/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/windows/file_selector_plugin.h",
"repo_id": "packages",
"token_count": 621
} | 1,020 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 0.1.8
* Adds `transitionDuration` parameter for specifying how long the animation should be.
## 0.1.7+2
* Fixes new lint warnings.
## 0.1.7+1
* Adds pub topics to package metadata.
## 0.1.7
* Fix top padding for NavigationBar.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.1.6
* Added support for displaying an AppBar on any Breakpoint by introducing appBarBreakpoint
## 0.1.5
* Added support for Right-to-left (RTL) directionality.
* Fixes stale ignore: prefer_const_constructors.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 0.1.4
* Use Material 3 NavigationBar instead of BottomNavigationBar
## 0.1.3
* Fixes `groupAlignment` property not available in `standardNavigationRail` - [flutter/flutter#121994](https://github.com/flutter/flutter/issues/121994)
## 0.1.2
* Fixes `NavigationRail` items not considering `NavigationRailTheme` values - [flutter/flutter#121135](https://github.com/flutter/flutter/issues/121135)
* When `NavigationRailTheme` is provided, it will use the theme for values that the user has not given explicit theme-related values for.
## 0.1.1
* Fixes flutter/flutter#121135) `selectedIcon` parameter not displayed even if it is provided.
## 0.1.0+1
* Aligns Dart and Flutter SDK constraints.
## 0.1.0
* Change the `selectedIndex` parameter on `standardNavigationRail` to allow null values to indicate "no destination".
* An explicitly null `currentIndex` parameter passed to `standardBottomNavigationBar` will also default to 0, just like implicitly null missing parameters.
## 0.0.9
* Fix passthrough of `leadingExtendedNavRail`, `leadingUnextendedNavRail` and `trailingNavRail`
## 0.0.8
Make fuchsia a mobile platform.
## 0.0.7
* Patch duplicate key error in SlotLayout.
## 0.0.6
* Change type of `appBar` parameter from `AppBar?` to `PreferredSizeWidget?`
## 0.0.5
* Calls onDestinationChanged callback in bottom nav bar.
## 0.0.4
* Fix static analyzer warnings using `core` lint.
## 0.0.3
* First published version.
## 0.0.2
* Adds some more examples.
## 0.0.1+1
* Updates text theme parameters to avoid deprecation issues.
## 0.0.1
* Initial release
| packages/packages/flutter_adaptive_scaffold/CHANGELOG.md/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/CHANGELOG.md",
"repo_id": "packages",
"token_count": 728
} | 1,021 |