text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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:io_flip/scripts/scripts.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class _MockScriptsCubit extends Mock implements ScriptsCubit {} void main() { group('ScriptsView', () { late ScriptsCubit cubit; void mockState(ScriptsState state) { whenListen( cubit, Stream.value(state), initialState: state, ); } setUp(() { cubit = _MockScriptsCubit(); }); testWidgets('renders correctly', (tester) async { mockState( ScriptsState( status: ScriptsStateStatus.loaded, current: 'script', ), ); await tester.pumpSubject(cubit); expect(find.byType(ScriptsView), findsOneWidget); }); testWidgets('saves the script', (tester) async { when(() => cubit.updateScript(any())).thenAnswer((_) async {}); mockState( ScriptsState( status: ScriptsStateStatus.loaded, current: 'script', ), ); await tester.pumpSubject(cubit); await tester.tap(find.byType(Icon)); await tester.pump(); verify(() => cubit.updateScript('script')).called(1); }); testWidgets('renders a loading indicator when is saving', (tester) async { mockState( ScriptsState( status: ScriptsStateStatus.loading, current: 'script', ), ); await tester.pumpSubject(cubit); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets('renders an error message', (tester) async { final initial = ScriptsState( status: ScriptsStateStatus.loaded, current: 'script', ); final loading = ScriptsState( status: ScriptsStateStatus.loading, current: 'script', ); final state = ScriptsState( status: ScriptsStateStatus.failed, current: 'script', ); whenListen( cubit, Stream.fromIterable([ initial, loading, state, ]), initialState: initial, ); await tester.pumpSubject(cubit); await tester.pump(); expect(find.byType(SnackBar), findsOneWidget); }); }); } extension ScriptsViewTest on WidgetTester { Future<void> pumpSubject( ScriptsCubit cubit, ) { return pumpApp( BlocProvider<ScriptsCubit>.value( value: cubit, child: ScriptsView(), ), ); } }
io_flip/test/scripts/views/scripts_view_test.dart/0
{ "file_path": "io_flip/test/scripts/views/scripts_view_test.dart", "repo_id": "io_flip", "token_count": 1193 }
939
# Codemagic Remarks: # - As the encrypt button is no longer available in Codemagic web ui # to encrypt the variable see this curl request https://docs.codemagic.io/rest-api/applications/#curl-example definitions: environment: prod_emails: &prod_emails - [email protected] tst_emails: &tst_emails - [email protected] # common_environment: &common_environment # FLUTTER_PROJECT_DIRECTORY: flutter_news_example automatic_ios_signing: &automatic_ios_signing # Encrypt the **content** of the API key for AppStore Connect # - Log in to App Store Connect and navigate to Users and Access > Keys. # - Click on the + sign to generate a new API key. # - Enter the name for the key and select an access level: either Developer or App Manager. # - Click Generate. # - As soon as the key is generated, you can see it added in the list of active keys. # Click Download API Key to save the private key for later. Note that the key can only be downloaded once. # Save the key in the project 1Password or Lastpass. # Encrypt the CONTENT of the p8 file and provide below in APP_STORE_CONNECT_PRIVATE_KEY. APP_STORE_CONNECT_ISSUER_ID: TODO APP_STORE_CONNECT_KEY_IDENTIFIER: TODO APP_STORE_CONNECT_PRIVATE_KEY: TODO # Generate the ssh key: # ssh-keygen -t rsa -b 2048 -m PEM -f ./codemagic_private_key -q -N "" # This will be used by app-store-connect to generate the signing certificates. # Save the key in the project 1Password or Lastpass. # Encrypt the CONTENT of the file and provide below in CERTIFICATE_PRIVATE_KEY. CERTIFICATE_PRIVATE_KEY: TODO android_signing: &android_signing # Generate the project Android keystore either via Android Studio or command: # keytool -genkey -v -keystore ./[project_name]-prod.keystore -alias [project_name] -keyalg RSA -keysize 2048 -validity 10000 # Save the key and password in the project 1Password or Lastpass # See instruction: https://docs.codemagic.io/code-signing-yaml/signing-android/#set-up-code-signing-with-user-specified-keys FCI_KEYSTORE_PATH: /tmp/keystore.keystore FCI_KEYSTORE: TODO FCI_KEYSTORE_PASSWORD: TODO FCI_KEY_PASSWORD: TODO FCI_KEY_ALIAS: flutter-news-example # The Google Play service account key should be generated by the owner of Google Play account # See instruction https://docs.codemagic.io/knowledge-base/google-play-api/ # Encrypt the **content** of the Service Account Key GPLAY_KEY: TODO workflows: development: name: development working_directory: flutter_news_example max_build_duration: 60 environment: flutter: 3.3.10 xcode: latest cocoapods: default vars: <<: *automatic_ios_signing <<: *android_signing FLAVOR: development BUNDLE_ID: com.flutter.news.example.dev cache: cache_paths: - $HOME/Library/Caches/CocoaPods - $HOME/.pub-cache - $HOME/.gradle/caches triggering: events: - tag # Include or exclude watched branches. branch_patterns: - pattern: "main" include: true source: true # Include or exclude watched tag labels. tag_patterns: - pattern: "*" include: true # Set to `true` to automatically cancel outdated webhook builds. cancel_previous_builds: true scripts: - &get_latest_tag name: Get latest tag script: set TAG=$(git describe --tags) - &set_up_key_properties name: Set up Android key.properties script: | echo $FCI_KEYSTORE | base64 --decode > $FCI_KEYSTORE_PATH cat >> "$FCI_BUILD_DIR/flutter_news_example/android/key.properties" <<EOF storePassword=$FCI_KEYSTORE_PASSWORD keyPassword=$FCI_KEY_PASSWORD keyAlias=$FCI_KEY_ALIAS storeFile=$FCI_KEYSTORE_PATH EOF - &set_up_local_properties name: Set up Android local properties script: echo "flutter.sdk=$HOME/programs/flutter" > "$FCI_BUILD_DIR/flutter_news_example/android/local.properties" - &setup_keychain name: Setup keychain script: keychain initialize - &fetch_signing_files name: Fetch signing files script: | app-store-connect fetch-signing-files "${BUNDLE_ID}" \ --type IOS_APP_STORE \ --create - &get_packages name: Get packages script: flutter packages pub get - &build_apk name: Build Android APK script: flutter build apk --release --flavor ${FLAVOR} -t lib/main/main_${FLAVOR}.dart --build-number=$PROJECT_BUILD_NUMBER - &build_aab name: Build Android AAB script: flutter build appbundle --release --flavor ${FLAVOR} -t lib/main/main_${FLAVOR}.dart --build-number=$PROJECT_BUILD_NUMBER - &setup_signing_certificates name: Set up signing certificate script: keychain add-certificates - &use_profiles name: Use Xcode profiles script: xcode-project use-profiles - &pod_install name: Run pod install script: find . -name "Podfile" -execdir pod install \; - &build_ios name: Build and sign iOS script: flutter build ipa --release --flavor ${FLAVOR} -t lib/main/main_${FLAVOR}.dart --build-number=$PROJECT_BUILD_NUMBER --export-options-plist=/Users/builder/export_options.plist artifacts: - build/app/outputs/apk/${FLAVOR}/release/*.apk - build/app/outputs/bundle/${FLAVOR}Release/*.aab - build/app/outputs/mapping/**/mapping.txt - build/ios/ipa/*.ipa - /tmp/xcodebuild_logs/*.log - flutter_drive.log publishing: app_store_connect: api_key: $APP_STORE_CONNECT_PRIVATE_KEY key_id: $APP_STORE_CONNECT_KEY_IDENTIFIER issuer_id: $APP_STORE_CONNECT_ISSUER_ID email: recipients: *tst_emails google_play: credentials: $GPLAY_KEY track: internal production: name: production working_directory: flutter_news_example max_build_duration: 60 environment: flutter: 3.3.10 xcode: latest cocoapods: default vars: <<: *automatic_ios_signing <<: *android_signing FLAVOR: production BUNDLE_ID: com.flutter.news.example cache: cache_paths: - $HOME/Library/Caches/CocoaPods - $HOME/.pub-cache - $HOME/.gradle/caches scripts: - *get_latest_tag - *set_up_key_properties - *set_up_local_properties - *setup_keychain - *fetch_signing_files - *get_packages - *build_apk - *build_aab - *setup_signing_certificates - *use_profiles - *pod_install - *build_ios artifacts: - build/app/outputs/apk/${FLAVOR}/release/*.apk - build/app/outputs/bundle/${FLAVOR}Release/*.aab - build/app/outputs/mapping/**/mapping.txt - build/ios/ipa/*.ipa - /tmp/xcodebuild_logs/*.log - flutter_drive.log publishing: app_store_connect: api_key: $APP_STORE_CONNECT_PRIVATE_KEY key_id: $APP_STORE_CONNECT_KEY_IDENTIFIER issuer_id: $APP_STORE_CONNECT_ISSUER_ID email: recipients: *prod_emails google_play: credentials: $GPLAY_KEY track: internal
news_toolkit/codemagic.yaml/0
{ "file_path": "news_toolkit/codemagic.yaml", "repo_id": "news_toolkit", "token_count": 3218 }
940
--- sidebar_position: 3 description: Learn how to write and run tests in your application. --- # Testing Flutter News Toolkit applications come with 100% test coverage out of the box. Tests are located in a parallel file structure relative to your source code, residing in a `test` directory that mirrors the source code `lib` directory. Tests are automatically run on your app using [Very Good Workflows](https://github.com/VeryGoodOpenSource/very_good_workflows). Changes made to your source code, such as [removing advertisements](/project_configuration/ads#remove-ads), might reduce test coverage or cause existing tests to fail. We recommend maintaining 100% test coverage within your application to support stability and scalability, but your application functionality won't be compromised if you forgo 100% test coverage. To support 100% test coverage in your application, ensure that your tests capture any changes you make to the app behavior. For example, if you implement a new widget, `your_widget.dart`, create a corresponding `your_widget_test.dart` file that properly tests the new widget's behavior. Your Flutter app's test suite contains [bloc, unit, and widget tests](https://docs.flutter.dev/testing). :::info The Flutter community offers [excellent testing resources](https://verygood.ventures/blog/flutter-testing-resources) to guide you in developing effective tests for your application. ::: ## Unit tests Unit tests evaluate a single method, function, or class within your codebase. You should test that your unit behaves appropriately under all conditions under which it might be executed. For example, `news_repository_test.dart` tests whether the `NewsRepository` class can be instantiated, handle error cases correctly, and correctly execute its behavior under both success and error conditions. :::info Flutter's [Introduction to unit testing](https://docs.flutter.dev/cookbook/testing/unit/introduction) recipe provides further information on unit testing. ::: ## Widget tests Widget tests verify that a single widget behaves correctly within the Flutter framework using a testing environment that enables UI interactions and behaviors. For example the following test from `bottom_nav_bar_test.dart` checks that the proper behavior is executed when the user interacts with the `BottomNavBar` widget: ```dart testWidgets('calls onTap when navigation bar item is tapped', (tester) async { final completer = Completer<void>(); await tester.pumpApp( Scaffold( body: Container(), bottomNavigationBar: BottomNavBar( currentIndex: 0, onTap: (value) => completer.complete(), ), ), ); await tester.ensureVisible(find.byType(BottomNavigationBar)); await tester.tap(find.byIcon(Icons.home_outlined)); expect(completer.isCompleted, isTrue); }); ``` :::info Flutter's [Introduction to widget testing](https://docs.flutter.dev/cookbook/testing/widget/introduction) recipe provides further information on widget testing. ::: ## Bloc tests Bloc tests verify that your app's [bloc state management library](https://bloclibrary.dev) behaves as expected under a variety of conditions. A bloc test sets up the test's initial conditions, instantiates the block, and tests whether the bloc behaves as expected. The following test from `analytics_bloc_test.dart` checks whether the `AnalyticsBloc` responds appropriately to user authentication: ```dart blocTest<AnalyticsBloc, AnalyticsState>( 'calls AnalyticsRepository.setUserId ' 'with user id when user is authenticated', setUp: () => when(() => userRepository.user) .thenAnswer((_) => Stream.value(user)), build: () => AnalyticsBloc( analyticsRepository: analyticsRepository, userRepository: userRepository, ), verify: (_) { verify(() => analyticsRepository.setUserId(user.id)).called(1); }, ); ``` The test above verifies that a mocked repository is called correctly. Depending on what bloc behavior you are testing, bloc tests can also verify that an error is thrown or that the bloc's state is correct. :::info The [bloc library testing documentation](https://bloclibrary.dev/#/testing) provides a thorough introduction to testing blocs. :::
news_toolkit/docs/docs/flutter_development/testing.md/0
{ "file_path": "news_toolkit/docs/docs/flutter_development/testing.md", "repo_id": "news_toolkit", "token_count": 1170 }
941
--- sidebar_position: 2 description: Learn how to connect your news server to a custom data source. --- # Connecting your data source The template's [Dart Frog](https://dartfrog.vgv.dev) API acts as an intermediary between your CMS and the client application, organizing your content into the [blocks](/server_development/blocks) that form the basis of content organization within the app. If you don't intend to write custom code to support the necessary block-organized endpoints from your CMS, you should create and deploy an API that uses the `NewsDataSource` interface to collect and transform data. Your implementation of the `NewsDataSource` is called by the route handlers laid out in the `api/routes` directory. The data source then requests data from your CMS and organizes it into the block-based data expected by the client before returning it to the route handler to be served to your client application. For more information about the structure and capabilities of the Dart Frog server that uses your data source, consult the [Dart Frog documentation](https://dartfrog.vgv.dev/docs/category/basics). The `NewsDataSource` class (`api/lib/src/data/news_data_source.dart`) provides an interface that your data source must implement. Feel free to remove methods that provide data that you don't intend to use in the client app, or to add methods to provide data for functionality that you intend on adding to your app. ## Creating a new data source Begin by defining a new class that implements `NewsDataSource`: ```dart class YourCustomDataSource implements NewsDataSource ``` Your data source should have a means of interacting with your CMS as a field such as an [HTTP](https://pub.dev/packages/http) or [Dio](https://pub.dev/packages/dio) client, and you might want to create separate named constructors if you have different CMS URLs for different flavors, such as `development` and `production`. ## Implementing your data source After creating your data source class, implement the methods defined in `NewsDataSource`: ```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. Future<Article?> getArticle({ required String id, int limit = 20, int offset = 0, }); /// 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(); } ``` For example, an implementation of `getArticle()` might look like: ```dart @override Future<Article?> getArticle({ required String id, int limit = 20, int offset = 0, bool preview = false, }) async { final uri = Uri.parse('$YOUR_CMS_BASE_URL/posts/$id'); final response = await httpClient.get(uri); if (response.statusCode != HttpStatus.ok) { throw YourAppApiFailureException( body: response.body, statusCode: response.statusCode, ); } final responseJson = response.jsonMap(); if (responseJson.isNotFound) return null; final post = Post.fromJson(responseJson); final article = post.toArticle(); return article; } ``` The above example references a class not included in the template, `Post`: ```dart class Post { const Post({ required this.id, required this.date, required this.link, required this.title, required this.content, required this.author, required this.image, required this.category, }); final int id; final DateTime date; final String link; final String title; final String content; final Author author; final String image; final PostCategory category; } ``` Since your CMS presumably doesn't respond with data in the block-based format used by the `Article` class, you might want to define classes like `Post` that mirror the data types and formats that your CMS returns. You can use a package like [json_serializable](https://pub.dev/packages/json_serializable) to generate code to create a `Post` object from the JSON returned from your CMS (see [JSON and serialization - Flutter Documentation](https://docs.flutter.dev/development/data-and-backend/json)). You can then [add an extension method](https://dart.dev/guides/language/extension-methods) such as `toArticle()` on your `Post` class that uses the relevant data from the `Post` object and to create and return an `Article` object that is served to your client app. This structure of `JSON -> Intermediary Object -> API Model` can be repeated when implementing any data source method, which receives data from your CMS that differs from what the method is expected to return. ## Injecting your data source After creating your data source, inject it into your API route handler through the [Dart Frog middleware](https://dartfrog.vgv.dev/docs/basics/dependency-injection). First, instantiate your data source: ```dart final yourCustomDataSource = YourCustomDataSource(); ``` Then, inject it through the middleware as a `NewsDataSource`: ```dart handler.use(provider<NewsDataSource>((_) => yourCustomDataSource)); ``` As the template already contains a `NewsDataSource` dependency injection, you can simply instantiate your data source and then replace `inMemoryNewsDataSource` with `yourCustomDataSource`.
news_toolkit/docs/docs/server_development/connecting_your_data_source.md/0
{ "file_path": "news_toolkit/docs/docs/server_development/connecting_your_data_source.md", "repo_id": "news_toolkit", "token_count": 1893 }
942
include: package:very_good_analysis/analysis_options.5.1.0.yaml analyzer: exclude: - lib/l10n/* - lib/generated/* - lib/**/*.g.dart - assets/**/*.gen.dart - packages/**/*.gen.dart linter: rules: public_member_api_docs: false
news_toolkit/flutter_news_example/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 111 }
943
FORMAT: 1A HOST: http://localhost:8080 # Flutter News Example API (v1.0.0) Flutter News Example API is an API which allows consumers to interact with sample news content. # Root [/] ## Status Check [GET] This action allows consumers to verify the status of the server. A response status code `204` indicates that the server is healthy. + Response 204 (application/json) ## Articles [/api/v1/articles] Resources related to news articles. ### Get Article [GET /api/v1/articles/{id}{?limit,offset}] This action allows you to query article content for a specific article. + Parameters + id (required, string) - The article identifier. + limit (optional, number) - The number of content blocks to return. + Default: 20 + offset (optional, number) - The (zero-based) offset of the first item in the collection to return. + Default: 0 + Response 200 (application/json) + Attributes (object) + content (required, array[Block]) - The list of blocks that composes the article content. + total_count (optional, number) - The total number of available blocks. + url (required, string) - The url for the associated article. + Body { "content": [ { "title": "Breaking News", "type": "__section_header__" }, ], "total_count": 42, "url": "https://dailyglobe.com" } ### Get Related Articles [GET /api/v1/articles/{id}/related{?limit,offset}] This action allows you to query article content related to a specific article. + Parameters + id (required, string) - The article identifier. + limit (optional, number) - The number of content blocks to return. + Default: 20 + offset (optional, number) - The (zero-based) offset of the first item in the collection to return. + Default: 0 + Response 200 (application/json) + Attributes (object) + related_articles (required, array[Block]) - The list of blocks that composes the related articles list. + total_count (optional, number) - The total number of available blocks. + Body { "related_articles": [ { "id": "b1fc2ffc-eb02-42ce-af65-79702172a987", "category": "health", "author": "Northwestern University", "published_at": "2022-03-11T00:00:00.000", "image_url": "https://scitechdaily.com/images/Ear-Hearing-Concept.jpg", "title": "Restoring Hearing: New Tool To Create Ear Hair Cells Lost Due to Aging or Noise - SciTechDaily", "description": "‘We have overcome a major hurdle’ to restore hearing, investigators say. Gene discovery allows the production of inner or outer ear hair cells, death of outer hair cells due to aging or noise cause most hearing loss...", "is_premium": false, "type": "__post_small__" } ], "total_count": 1, } ## Categories [/api/v1/categories] Resources related to news categories. ### Get Categories [GET] This action allows you to query all available news categories. + Response 200 (application/json) + Attributes (object) + categories (required, array[Category]) - The list of available news categories. + Body { "categories": [ "technology", "sports", "top" ] } ## Feed [/api/v1/feed{?category,limit,offset}] Resources related to the news feed. + Parameters + category (optional, Category) - The headline category. + Default: general + Members + business + entertainment + general + health + science + sports + technology + limit (optional, number) - The number of results to return. + Default: 20 + offset (optional, number) - The (zero-based) offset of the first item in the collection to return. + Default: 0 ### Get Feed [GET] This action allows you to query feeds. + Response 200 (application/json) + Attributes (object) + feed (required, array[Block]) - The list of blocks that composes the feed. + total_count (optional, number) - The total number of available blocks. + Body { "feed": [ { "title": "Breaking News", "type": "__section_header__" }, { "type": "__divider_horizontal__" }, { "id": "499305f6-5096-4051-afda-824dcfc7df23", "category": "technology", "author": "Sean Hollister", "published_at": "2022-03-09T00:00:00.000", "image_url": "https://cdn.vox-cdn.com/thumbor/OTpmptgr7XcTVAJ27UBvIxl0vrg=/0x146:2040x1214/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/22049166/shollister_201117_4303_0003.0.jpg", "title": "Nvidia and AMD GPUs are returning to shelves and prices are finally falling", "is_premium": false, "type": "__post_large__", "action": { "article_id": "499305f6-5096-4051-afda-824dcfc7df23", "type": "__navigate_to_article__" } }, { "type": "__spacer__", "spacing": "medium" }, { "id": "82c49bf1-946d-4920-a801-302291f367b5", "category": "sports", "author": "Tom Dierberger", "published_at": "2022-03-10T00:00:00.000", "image_url":"https://www.nbcsports.com/sites/rsnunited/files/styles/metatags_opengraph/public/article/hero/pat-bev-ja-morant-USA.jpg", "title": "Patrick Beverley throws shade at Warriors for Ja Morant struggles - NBC Sports", "description": "Patrick Beverley is no longer participating in the NBA playoffs, but he sure has a lot to say. In Game 2 between the Warriors and Memphis Grizzlies on Tuesday night, Ja Morant torched the Dubs for 47 points...", "is_premium": false, "type": "__post_medium__", "action": { "article_id": "82c49bf1-946d-4920-a801-302291f367b5", "type": "__navigate_to_article__" } }, { "spacing": "small", "type": "__spacer__" }, { "id": "b1fc2ffc-eb02-42ce-af65-79702172a987", "category": "health", "author": "Northwestern University", "published_at": "2022-03-11T00:00:00.000", "image_url": "https://scitechdaily.com/images/Ear-Hearing-Concept.jpg", "title": "Restoring Hearing: New Tool To Create Ear Hair Cells Lost Due to Aging or Noise - SciTechDaily", "description": "‘We have overcome a major hurdle’ to restore hearing, investigators say. Gene discovery allows the production of inner or outer ear hair cells, death of outer hair cells due to aging or noise cause most hearing loss...", "is_premium": false, "type": "__post_small__", "action": { "article_id": "b1fc2ffc-eb02-42ce-af65-79702172a987", "type": "__navigate_to_article__" } }, { "spacing": "extraSmall", "type": "__spacer__" }, { "category": "science", "tiles": [ { "id": "384a15ff-a50e-46d5-96a7-8864facdcc48", "category": "science", "author": "Loren Grush", "published_at": "2022-05-06T00:00:00.000", "image_url": "https://cdn.vox-cdn.com/thumbor/eqkJgsUMn-iJOrN98c4gduFGDT8=/0x74:1050x624/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/23441881/Screen_Shot_2022_05_06_at_1.13.12_AM.png", "title": "SpaceX successfully returns four astronauts from the International Space Station - The Verge", "is_premium": false, "type": "__post_grid_tile__", "action": { "article_id": "384a15ff-a50e-46d5-96a7-8864facdcc48", "type": "__navigate_to_article__" } }, { "id": "13e448bb-cd26-4ae0-b138-4a67067f7a93", "category": "science", "author": "Daniel Strain", "published_at": "2022-05-06T00:00:00.000", "image_url": "https://scx2.b-cdn.net/gfx/news/2022/a-surging-glow-in-a-di.jpg", "title": "A surging glow in a distant galaxy could change the way we look at black holes", "is_premium": false, "type": "__post_grid_tile__", "action": { "article_id": "13e448bb-cd26-4ae0-b138-4a67067f7a93", "type": "__navigate_to_article__" } } ], "type": "__post_grid_group__" }, } ], "total_count": 100, } ## Newsletter [/api/v1/newsletter] Resources related to newsletters. ### Subscribe to Newsletter [POST /api/v1/newsletter/subscription] This action allows you to subscribe a user to a newsletter. + Request + Body { "email": "<EMAIL_ADDRESS>" } + Response 201 (application/json) ## Search [/api/v1/search] Resources related to search. ### Popular Search [GET /api/v1/search/popular] This action allows you to search for popular news content. + Response 200 (application/json) + Attributes (object) + topics (required, array[string]) - The list of popular topics. + articles (required, array[Block]) - The list of popular article blocks. + Body { "topics": ["Aging", "Health", "Genetics"], "articles": [ { "id": "b1fc2ffc-eb02-42ce-af65-79702172a987", "category": "health", "author": "Northwestern University", "published_at": "2022-03-11T00:00:00.000", "image_url": "https://scitechdaily.com/images/Ear-Hearing-Concept.jpg", "title": "Restoring Hearing: New Tool To Create Ear Hair Cells Lost Due to Aging or Noise - SciTechDaily", "description": "‘We have overcome a major hurdle’ to restore hearing, investigators say. Gene discovery allows the production of inner or outer ear hair cells, death of outer hair cells due to aging or noise cause most hearing loss...", "is_premium": false, "type": "__post_small__" } ], } ### Relevant Search [GET /api/v1/search/relevant{?q}] This action allows you to search for relevant news content. + Parameters + q (required, string) - The query string. + Response 200 (application/json) + Attributes (object) + topics (required, array[string]) - The list of relevant topics. + articles (required, array[Block]) - The list of relevant article blocks. + Body { "topics": ["Aging", "Health", "Genetics"], "articles": [ { "id": "b1fc2ffc-eb02-42ce-af65-79702172a987", "category": "health", "author": "Northwestern University", "published_at": "2022-03-11T00:00:00.000", "image_url": "https://scitechdaily.com/images/Ear-Hearing-Concept.jpg", "title": "Restoring Hearing: New Tool To Create Ear Hair Cells Lost Due to Aging or Noise - SciTechDaily", "description": "‘We have overcome a major hurdle’ to restore hearing, investigators say. Gene discovery allows the production of inner or outer ear hair cells, death of outer hair cells due to aging or noise cause most hearing loss...", "is_premium": false, "type": "__post_small__" } ], } ## Subscriptions [/api/v1/subscriptions] Resources related to subscriptions. ### Create a Subscription [POST] This action allows you to create a subscription for the associated user. + Response 201 (application/json) ### Get Subscriptions [GET] This action allows you to query all available subscriptions. + Response 200 (application/json) + Attributes (object) + subscriptions (required, array[Subscription]) - The list of subscriptions. + Body { "subscriptions": [ { "id": "17e79fca-853a-40e3-b4a7-291a64d3846b", "name": "premium", "cost": { "monthly": 1499, "annual":16200 }, "benefits": [ "No ads", "Access to premium content", "Unlimited reads" ] } ], } ## Users [/api/v1/users] Resources related to users. ### Get Current User [GET /api/v1/users/me] This action allows you query information about the current user. + Response 200 (application/json) + Attributes (object) + user (required, User) - The currently authenticated user. + Body { "user": { "id": "2e99887d-d672-4b96-ad6a-123c1c7fa3fa", "subscription_plan": "premium", } } # Data Structures ## Block (object) + type (required, BlockType) - the block type. ## BlockType (enum) + "__section_header__" - a section header block + "__divider_horizontal__" - a divider horizontal block + "__spacer__" - a spacer block + "__post_large__" - a post large block + "__post_medium__" - a post medium block + "__post_small__" - a post small block + "__post_grid_group__" - a post grid group block + "__post_grid_tile__" - a post grid tile block + "__text_caption__" - a text caption block + "__text_headline__" - a text headline block + "__text_lead_paragraph__" - a text lead paragraph block + "__text_paragraph__" - a text paragraph block + "__image__" - an image block + "__video__" - a video block + "__unknown__" - an unrecognized block + "__trending_story__ - a trending story block ## Category (enum) + business - news relating to business + entertainment - news relating to entertainment + top - breaking news + health - news relating to health + science - news relating to science + sports - news relating to sports + technology - news relating to technology ## Subscription (object) + id (required, string) - the unique subscription identifier + name (required, string) - the human readable subscription name + cost (required, SubscriptionCost) - the cost for the subscription + benefits (required, array[string]) - list of benefits associated with the subscription ## SubscriptionCost (object) + monthly (required, number) - the monthly cost of the subscription in cents + annual (required, number) - the annual cost of the subscription in cents ## SubscriptionPlan (enum) + none - no subscription plan + basic - a basic subscription plan + plus - a plus subscription plan + premium - a premium subscription plan ## User (object) + id (required, string) - the unique user identifier (username) + subscription_plan (required, SubscriptionPlan) - the user's current subscription plan.
news_toolkit/flutter_news_example/api/docs/api.apib/0
{ "file_path": "news_toolkit/flutter_news_example/api/docs/api.apib", "repo_id": "news_toolkit", "token_count": 8741 }
944
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'user.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** User _$UserFromJson(Map<String, dynamic> json) => User( id: json['id'] as String, subscription: $enumDecode(_$SubscriptionPlanEnumMap, json['subscription']), ); Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{ 'id': instance.id, 'subscription': _$SubscriptionPlanEnumMap[instance.subscription]!, }; const _$SubscriptionPlanEnumMap = { SubscriptionPlan.none: 'none', SubscriptionPlan.basic: 'basic', SubscriptionPlan.plus: 'plus', SubscriptionPlan.premium: 'premium', };
news_toolkit/flutter_news_example/api/lib/src/data/models/user.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/data/models/user.g.dart", "repo_id": "news_toolkit", "token_count": 253 }
945
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'popular_search_response.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** PopularSearchResponse _$PopularSearchResponseFromJson( Map<String, dynamic> json) => PopularSearchResponse( articles: const NewsBlocksConverter().fromJson(json['articles'] as List), topics: (json['topics'] as List<dynamic>).map((e) => e as String).toList(), ); Map<String, dynamic> _$PopularSearchResponseToJson( PopularSearchResponse instance) => <String, dynamic>{ 'articles': const NewsBlocksConverter().toJson(instance.articles), 'topics': instance.topics, };
news_toolkit/flutter_news_example/api/lib/src/models/popular_search_response/popular_search_response.g.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/lib/src/models/popular_search_response/popular_search_response.g.dart", "repo_id": "news_toolkit", "token_count": 251 }
946
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'block_action.g.dart'; /// The different types of actions. enum BlockActionType { /// A navigation action represents an internal navigation to the provided uri. navigation, /// An unknown action type. unknown } /// {@macro block_action} /// A class which represents an action that can occur /// when interacting with a block. /// {@endtemplate} abstract class BlockAction { /// {@macro block_action} const BlockAction({ required this.type, required this.actionType, }); /// The type key used to identify the type of this action. final String type; /// The type of this action. final BlockActionType actionType; /// Converts the current instance to a `Map<String, dynamic>`. Map<String, dynamic> toJson(); /// Deserialize [json] into a [BlockAction] instance. /// Returns [UnknownBlockAction] when the [json] is not a recognized type. static BlockAction fromJson(Map<String, dynamic> json) { final type = json['type'] as String?; switch (type) { case NavigateToArticleAction.identifier: return NavigateToArticleAction.fromJson(json); case NavigateToVideoArticleAction.identifier: return NavigateToVideoArticleAction.fromJson(json); case NavigateToFeedCategoryAction.identifier: return NavigateToFeedCategoryAction.fromJson(json); case NavigateToSlideshowAction.identifier: return NavigateToSlideshowAction.fromJson(json); } return const UnknownBlockAction(); } } /// {@template navigate_to_article_action} /// A block action which represents navigation to the article with [articleId]. /// {@endtemplate} @JsonSerializable() class NavigateToArticleAction with EquatableMixin implements BlockAction { /// {@macro navigate_to_article_action} const NavigateToArticleAction({ required this.articleId, this.type = NavigateToArticleAction.identifier, }); /// Converts a `Map<String, dynamic>` /// into a [NavigateToArticleAction] instance. factory NavigateToArticleAction.fromJson(Map<String, dynamic> json) => _$NavigateToArticleActionFromJson(json); /// The identifier of this block action. static const identifier = '__navigate_to_article__'; /// The id of the article to navigate to. final String articleId; @override BlockActionType get actionType => BlockActionType.navigation; @override final String type; @override Map<String, dynamic> toJson() => _$NavigateToArticleActionToJson(this); @override List<Object?> get props => [type, actionType, articleId]; } /// {@template navigate_to_video_article_action} /// A block action which represents navigation to the video article /// with [articleId]. /// {@endtemplate} @JsonSerializable() class NavigateToVideoArticleAction with EquatableMixin implements BlockAction { /// {@macro navigate_to_video_article_action} const NavigateToVideoArticleAction({ required this.articleId, this.type = NavigateToVideoArticleAction.identifier, }); /// Converts a `Map<String, dynamic>` /// into a [NavigateToVideoArticleAction] instance. factory NavigateToVideoArticleAction.fromJson(Map<String, dynamic> json) => _$NavigateToVideoArticleActionFromJson(json); /// The identifier of this block action. static const identifier = '__navigate_to_video_article__'; /// The id of the video article to navigate to. final String articleId; @override BlockActionType get actionType => BlockActionType.navigation; @override final String type; @override Map<String, dynamic> toJson() => _$NavigateToVideoArticleActionToJson(this); @override List<Object?> get props => [type, actionType, articleId]; } /// {@template navigate_to_feed_category_action} /// A block action which represents navigation to the feed [category]. /// {@endtemplate} @JsonSerializable() class NavigateToFeedCategoryAction with EquatableMixin implements BlockAction { /// {@macro navigate_to_feed_category_action} const NavigateToFeedCategoryAction({ required this.category, this.type = NavigateToFeedCategoryAction.identifier, }); /// Converts a `Map<String, dynamic>` /// into a [NavigateToFeedCategoryAction] instance. factory NavigateToFeedCategoryAction.fromJson(Map<String, dynamic> json) => _$NavigateToFeedCategoryActionFromJson(json); /// The identifier of this block action. static const identifier = '__navigate_to_feed_category__'; /// The category of feed to navigate to. final Category category; @override BlockActionType get actionType => BlockActionType.navigation; @override final String type; @override Map<String, dynamic> toJson() => _$NavigateToFeedCategoryActionToJson(this); @override List<Object?> get props => [type, actionType, category]; } /// {@template navigate_to_slideshow_action} /// A block action which represents navigation to the slideshow. /// {@endtemplate} @JsonSerializable() class NavigateToSlideshowAction with EquatableMixin implements BlockAction { /// {@macro navigate_to_slideshow_action} const NavigateToSlideshowAction({ required this.articleId, required this.slideshow, this.type = NavigateToSlideshowAction.identifier, }); /// Converts a `Map<String, dynamic>` /// into a [NavigateToSlideshowAction] instance. factory NavigateToSlideshowAction.fromJson(Map<String, dynamic> json) => _$NavigateToSlideshowActionFromJson(json); /// The identifier of this block action. static const identifier = '__navigate_to_slideshow__'; /// The id of the associated article. final String articleId; /// The slideshow content. final SlideshowBlock slideshow; @override BlockActionType get actionType => BlockActionType.navigation; @override final String type; @override Map<String, dynamic> toJson() => _$NavigateToSlideshowActionToJson(this); @override List<Object?> get props => [type, articleId, actionType, slideshow]; } /// {@template unknown_block_action} /// A block action which represents an unknown type. /// {@endtemplate} @JsonSerializable() class UnknownBlockAction with EquatableMixin implements BlockAction { /// {@macro unknown_block_action} const UnknownBlockAction({ this.type = UnknownBlockAction.identifier, }); /// Converts a `Map<String, dynamic>` into a [UnknownBlock] instance. factory UnknownBlockAction.fromJson(Map<String, dynamic> json) => _$UnknownBlockActionFromJson(json); /// The identifier of this block action. static const identifier = '__unknown__'; @override BlockActionType get actionType => BlockActionType.unknown; @override final String type; @override Map<String, dynamic> toJson() => _$UnknownBlockActionToJson(this); @override List<Object?> get props => [type, actionType]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/block_action.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/block_action.dart", "repo_id": "news_toolkit", "token_count": 2089 }
947
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'post_grid_group_block.g.dart'; /// {@template post_grid_group_block} /// A block which represents a post grid group. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=391%3A18875 /// {@endtemplate} @JsonSerializable() class PostGridGroupBlock with EquatableMixin implements NewsBlock { /// {@macro post_grid_group_block} const PostGridGroupBlock({ required this.category, required this.tiles, this.type = PostGridGroupBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [PostGridGroupBlock] instance. factory PostGridGroupBlock.fromJson(Map<String, dynamic> json) => _$PostGridGroupBlockFromJson(json); /// The post grid block type identifier. static const identifier = '__post_grid_group__'; /// The category of this post grid group. final PostCategory category; /// The associated list of [PostGridTileBlock] tiles. @NewsBlocksConverter() final List<PostGridTileBlock> tiles; @override final String type; @override Map<String, dynamic> toJson() => _$PostGridGroupBlockToJson(this); @override List<Object?> get props => [category, tiles, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_grid_group_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/post_grid_group_block.dart", "repo_id": "news_toolkit", "token_count": 438 }
948
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'slideshow_introduction_block.g.dart'; /// {@template slideshow_introduction_block} /// A block which represents a slideshow introduction. /// {@endtemplate} @JsonSerializable() class SlideshowIntroductionBlock with EquatableMixin implements NewsBlock { /// {@macro slideshow_introduction_block} const SlideshowIntroductionBlock({ required this.title, required this.coverImageUrl, this.type = SlideshowIntroductionBlock.identifier, this.action, }); /// Converts a `Map<String, dynamic>` /// into a [SlideshowIntroductionBlock] instance. factory SlideshowIntroductionBlock.fromJson(Map<String, dynamic> json) => _$SlideshowIntroductionBlockFromJson(json); /// The title of this slideshow. final String title; /// The slideshow cover image URL. final String coverImageUrl; /// An optional action which occurs upon interaction. @BlockActionConverter() final BlockAction? action; /// The slideshow introduction block type identifier. static const identifier = '__slideshow_introduction__'; @override Map<String, dynamic> toJson() => _$SlideshowIntroductionBlockToJson(this); @override List<Object> get props => [ title, coverImageUrl, type, ]; @override final String type; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_introduction_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/slideshow_introduction_block.dart", "repo_id": "news_toolkit", "token_count": 434 }
949
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:news_blocks/news_blocks.dart'; part 'video_block.g.dart'; /// {@template video_block} /// A block which represents a video. /// https://www.figma.com/file/RajSN6YbRqTuqvdKYtij3b/Google-News-Template-App-v3?node-id=812%3A31908 /// {@endtemplate} @JsonSerializable() class VideoBlock with EquatableMixin implements NewsBlock { /// {@macro video_block} const VideoBlock({ required this.videoUrl, this.type = VideoBlock.identifier, }); /// Converts a `Map<String, dynamic>` into a [VideoBlock] instance. factory VideoBlock.fromJson(Map<String, dynamic> json) => _$VideoBlockFromJson(json); /// The video block type identifier. static const identifier = '__video__'; /// The url of this video. final String videoUrl; @override final String type; @override Map<String, dynamic> toJson() => _$VideoBlockToJson(this); @override List<Object> get props => [videoUrl, type]; }
news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/video_block.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/lib/src/video_block.dart", "repo_id": "news_toolkit", "token_count": 357 }
950
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; class CustomPostBlock extends PostBlock { CustomPostBlock({super.action}) : super( id: 'id', category: PostCategory.technology, author: 'author', publishedAt: DateTime(2022, 03, 09), title: 'title', type: 'type', ); @override Map<String, dynamic> toJson() => throw UnimplementedError(); } void main() { group('PostBlock', () { test('can be extended', () { expect(CustomPostBlock.new, returnsNormally); }); }); group('PostBlockActions', () { test( 'hasNavigationAction returns true ' 'when BlockActionType is navigation', () { expect( CustomPostBlock( action: NavigateToArticleAction(articleId: 'articleId'), ).hasNavigationAction, isTrue, ); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/post_block_test.dart", "repo_id": "news_toolkit", "token_count": 398 }
951
// ignore_for_file: prefer_const_constructors import 'package:news_blocks/news_blocks.dart'; import 'package:test/test.dart'; void main() { group('UnknownBlock', () { test('can be (de)serialized', () { final block = UnknownBlock(); expect(UnknownBlock.fromJson(block.toJson()), equals(block)); }); }); }
news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/unknown_block_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/packages/news_blocks/test/src/unknown_block_test.dart", "repo_id": "news_toolkit", "token_count": 122 }
952
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/_middleware.dart'; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('middleware', () { test('provides NewsDataSource instance.', () async { final context = _MockRequestContext(); final handler = middleware( (_) { expect(context.read<NewsDataSource>(), isNotNull); return Response(); }, ); final request = Request('GET', Uri.parse('http://127.0.0.1/')); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()) .thenReturn(InMemoryNewsDataSource()); when(() => context.provide<NewsDataSource>(any())).thenReturn(context); when(() => context.provide<RequestUser>(any())).thenReturn(context); await handler(context); }); }); }
news_toolkit/flutter_news_example/api/test/routes/_middleware_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/routes/_middleware_test.dart", "repo_id": "news_toolkit", "token_count": 380 }
953
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 {} void main() { group('newsDataSourceProvider', () { test('provides a NewsDataSource instance', () async { NewsDataSource? value; final context = _MockRequestContext(); final handler = newsDataSourceProvider()( (_) { value = context.read<NewsDataSource>(); return Response(body: ''); }, ); final request = Request.get(Uri.parse('http://localhost/')); when(() => context.request).thenReturn(request); when(() => context.read<NewsDataSource>()) .thenReturn(InMemoryNewsDataSource()); when(() => context.provide<NewsDataSource>(any())).thenReturn(context); when(() => context.provide<RequestUser>(any())).thenReturn(context); await handler(context); expect(value, isNotNull); }); }); }
news_toolkit/flutter_news_example/api/test/src/middleware/news_data_source_provider_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/api/test/src/middleware/news_data_source_provider_test.dart", "repo_id": "news_toolkit", "token_count": 390 }
954
<?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>CLIENT_ID</key> <string>737894073936-ccvknt0jpr1nk3uhftg14k8duirosg9t.apps.googleusercontent.com</string> <key>REVERSED_CLIENT_ID</key> <string>com.googleusercontent.apps.737894073936-ccvknt0jpr1nk3uhftg14k8duirosg9t</string> <key>ANDROID_CLIENT_ID</key> <string>737894073936-epltqsgbon16uf53qm3l49vsva3ejp7f.apps.googleusercontent.com</string> <key>API_KEY</key> <string>AIzaSyCR94XfTOV3fjENKDoKQuqX6pmuGwJPS5I</string> <key>GCM_SENDER_ID</key> <string>737894073936</string> <key>PLIST_VERSION</key> <string>1</string> <key>BUNDLE_ID</key> <string>com.flutter.news.example.dev</string> <key>PROJECT_ID</key> <string>news-template-644a1</string> <key>STORAGE_BUCKET</key> <string>news-template-644a1.appspot.com</string> <key>IS_ADS_ENABLED</key> <false></false> <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:737894073936:ios:b9ecf7c188122cfcb03355</string> </dict> </plist>
news_toolkit/flutter_news_example/ios/Runner/development/GoogleService-Info.plist/0
{ "file_path": "news_toolkit/flutter_news_example/ios/Runner/development/GoogleService-Info.plist", "repo_id": "news_toolkit", "token_count": 620 }
955
part of 'app_bloc.dart'; enum AppStatus { onboardingRequired(), authenticated(), unauthenticated(); bool get isLoggedIn => this == AppStatus.authenticated || this == AppStatus.onboardingRequired; } class AppState extends Equatable { const AppState({ required this.status, this.user = User.anonymous, this.showLoginOverlay = false, }); const AppState.authenticated( User user, ) : this( status: AppStatus.authenticated, user: user, ); const AppState.onboardingRequired(User user) : this( status: AppStatus.onboardingRequired, user: user, ); const AppState.unauthenticated() : this(status: AppStatus.unauthenticated); final AppStatus status; final User user; final bool showLoginOverlay; bool get isUserSubscribed => user.subscriptionPlan != SubscriptionPlan.none; @override List<Object?> get props => [ status, user, showLoginOverlay, isUserSubscribed, ]; AppState copyWith({ AppStatus? status, User? user, bool? showLoginOverlay, }) { return AppState( status: status ?? this.status, user: user ?? this.user, showLoginOverlay: showLoginOverlay ?? this.showLoginOverlay, ); } }
news_toolkit/flutter_news_example/lib/app/bloc/app_state.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/app/bloc/app_state.dart", "repo_id": "news_toolkit", "token_count": 490 }
956
import 'package:app_ui/app_ui.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; class ArticleThemeOverride extends StatelessWidget { const ArticleThemeOverride({ required this.isVideoArticle, required this.child, super.key, }); final bool isVideoArticle; final Widget child; @override Widget build(BuildContext context) { final textHighColor = isVideoArticle ? AppColors.highEmphasisPrimary : AppColors.highEmphasisSurface; final textMediumColor = isVideoArticle ? AppColors.mediumEmphasisPrimary : AppColors.mediumEmphasisSurface; return ContentThemeOverrideBuilder( builder: (context) { final theme = Theme.of(context); final textTheme = theme.textTheme; return Theme( data: theme.copyWith( extensions: [ ArticleThemeColors( captionNormal: textHighColor, captionLight: textMediumColor, ), ], textTheme: textTheme.copyWith( displayMedium: textTheme.displayMedium?.copyWith( color: textHighColor, ), titleLarge: textTheme.titleLarge?.copyWith(color: textHighColor), bodyLarge: textTheme.bodyLarge?.copyWith(color: textMediumColor), ), ), child: child, ); }, ); } } class ArticleThemeColors extends ThemeExtension<ArticleThemeColors> with EquatableMixin { const ArticleThemeColors({ required this.captionNormal, required this.captionLight, }); final Color captionNormal; final Color captionLight; @override ArticleThemeColors copyWith({ Color? captionNormal, Color? captionLight, }) { return ArticleThemeColors( captionNormal: captionNormal ?? this.captionNormal, captionLight: captionLight ?? this.captionLight, ); } @override ArticleThemeColors lerp(ThemeExtension<ArticleThemeColors>? other, double t) { if (other is! ArticleThemeColors) { return this; } return ArticleThemeColors( captionNormal: Color.lerp(captionNormal, other.captionNormal, t)!, captionLight: Color.lerp(captionLight, other.captionLight, t)!, ); } @override List<Object> get props => [captionNormal, captionLight]; }
news_toolkit/flutter_news_example/lib/article/widgets/article_theme_override.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/article/widgets/article_theme_override.dart", "repo_id": "news_toolkit", "token_count": 946 }
957
export 'feed_view.dart';
news_toolkit/flutter_news_example/lib/feed/view/view.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/feed/view/view.dart", "repo_id": "news_toolkit", "token_count": 10 }
958
import 'dart:async'; import 'package:analytics_repository/analytics_repository.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:user_repository/user_repository.dart'; part 'login_with_email_link_event.dart'; part 'login_with_email_link_state.dart'; class LoginWithEmailLinkBloc extends Bloc<LoginWithEmailLinkEvent, LoginWithEmailLinkState> { LoginWithEmailLinkBloc({ required UserRepository userRepository, }) : _userRepository = userRepository, super(const LoginWithEmailLinkState()) { on<LoginWithEmailLinkSubmitted>(_onLoginWithEmailLinkSubmitted); _incomingEmailLinksSub = _userRepository.incomingEmailLinks .handleError(addError) .listen((emailLink) => add(LoginWithEmailLinkSubmitted(emailLink))); } final UserRepository _userRepository; late StreamSubscription<Uri> _incomingEmailLinksSub; Future<void> _onLoginWithEmailLinkSubmitted( LoginWithEmailLinkSubmitted event, Emitter<LoginWithEmailLinkState> emit, ) async { try { emit(state.copyWith(status: LoginWithEmailLinkStatus.loading)); final currentUser = await _userRepository.user.first; if (!currentUser.isAnonymous) { throw LogInWithEmailLinkFailure( Exception( 'The user is already logged in', ), ); } final emailLink = event.emailLink; if (!emailLink.queryParameters.containsKey('continueUrl')) { throw LogInWithEmailLinkFailure( Exception( 'No `continueUrl` parameter found in the received email link', ), ); } final redirectUrl = Uri.tryParse(emailLink.queryParameters['continueUrl']!); if (!(redirectUrl?.queryParameters.containsKey('email') ?? false)) { throw LogInWithEmailLinkFailure( Exception( 'No `email` parameter found in the received email link', ), ); } await _userRepository.logInWithEmailLink( email: redirectUrl!.queryParameters['email']!, emailLink: emailLink.toString(), ); emit(state.copyWith(status: LoginWithEmailLinkStatus.success)); } catch (error, stackTrace) { emit(state.copyWith(status: LoginWithEmailLinkStatus.failure)); addError(error, stackTrace); } } @override Future<void> close() { _incomingEmailLinksSub.cancel(); return super.close(); } }
news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_bloc.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/login/bloc/login_with_email_link_bloc.dart", "repo_id": "news_toolkit", "token_count": 949 }
959
import 'package:flutter_news_example/src/version.dart'; int buildNumber([String version = packageVersion]) { final versionSegments = version.split('+'); if (versionSegments.isEmpty) return 0; return int.tryParse(versionSegments.last) ?? 0; }
news_toolkit/flutter_news_example/lib/main/build_number.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/main/build_number.dart", "repo_id": "news_toolkit", "token_count": 79 }
960
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/newsletter/newsletter.dart' hide NewsletterEvent; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:news_repository/news_repository.dart'; import 'package:visibility_detector/visibility_detector.dart'; class Newsletter extends StatelessWidget { const Newsletter({super.key}); @override Widget build(BuildContext context) { return BlocProvider<NewsletterBloc>( create: (context) => NewsletterBloc( newsRepository: context.read<NewsRepository>(), ), child: const NewsletterView(), ); } } class NewsletterView extends StatefulWidget { const NewsletterView({super.key}); @override State<NewsletterView> createState() => _NewsletterViewState(); } class _NewsletterViewState extends State<NewsletterView> { bool _newsletterShown = false; @override Widget build(BuildContext context) { final isEmailValid = context.select<NewsletterBloc, bool>((bloc) => bloc.state.isValid); return VisibilityDetector( key: const Key('newsletterView'), onVisibilityChanged: _newsletterShown ? null : (visibility) { if (!visibility.visibleBounds.isEmpty) { context .read<AnalyticsBloc>() .add(TrackAnalyticsEvent(NewsletterEvent.impression())); setState(() { _newsletterShown = true; }); } }, child: BlocConsumer<NewsletterBloc, NewsletterState>( listener: (context, state) { if (state.status == NewsletterStatus.failure) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar(content: Text(context.l10n.subscribeErrorMessage)), ); } else if (state.status == NewsletterStatus.success) { context .read<AnalyticsBloc>() .add(TrackAnalyticsEvent(NewsletterEvent.signUp())); } }, builder: (context, state) { if (state.status == NewsletterStatus.success) { return NewsletterSucceeded( headerText: context.l10n.subscribeSuccessfulHeader, content: SizedBox( height: AppSpacing.xxxlg + AppSpacing.md, width: AppSpacing.xxxlg + AppSpacing.md, child: Assets.icons.envelopeOpen.svg(), ), footerText: context.l10n.subscribeSuccessfulEmailBody, ); } return NewsletterSignUp( headerText: context.l10n.subscribeEmailHeader, bodyText: context.l10n.subscribeEmailBody, email: AppEmailTextField( hintText: context.l10n.subscribeEmailHint, onChanged: (email) => context .read<NewsletterBloc>() .add(EmailChanged(email: email)), ), buttonText: context.l10n.subscribeEmailButtonText, onPressed: isEmailValid ? () => context .read<NewsletterBloc>() .add(const NewsletterSubscribed()) : null, ); }, ), ); } }
news_toolkit/flutter_news_example/lib/newsletter/view/newsletter.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/newsletter/view/newsletter.dart", "repo_id": "news_toolkit", "token_count": 1623 }
961
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; class OnboardingViewItem extends StatelessWidget { const OnboardingViewItem({ required this.pageNumberTitle, required this.title, required this.subtitle, required this.primaryButton, required this.secondaryButton, super.key, }); final String pageNumberTitle; final String title; final String subtitle; final Widget primaryButton; final Widget secondaryButton; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.only( top: AppSpacing.xxlg, left: AppSpacing.lg, right: AppSpacing.lg, ), child: Container( padding: const EdgeInsets.symmetric( vertical: AppSpacing.xlg + AppSpacing.sm, horizontal: AppSpacing.lg, ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: AppColors.white, ), child: CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Column( children: [ Text( key: const Key('onboardingItem_pageNumberTitle'), pageNumberTitle, style: theme.textTheme.labelSmall?.apply( color: AppColors.secondary.shade600, ), textAlign: TextAlign.center, ), const SizedBox(height: AppSpacing.lg + AppSpacing.sm), Text( key: const Key('onboardingItem_title'), title, style: theme.textTheme.headlineMedium?.apply( color: AppColors.highEmphasisSurface, ), textAlign: TextAlign.center, ), const SizedBox(height: AppSpacing.lg), Text( key: const Key('onboardingItem_subtitle'), subtitle, style: theme.textTheme.titleMedium?.apply( color: AppColors.mediumEmphasisSurface, ), textAlign: TextAlign.center, ), const Spacer(), primaryButton, const SizedBox(height: AppSpacing.sm), secondaryButton ], ), ), ], ), ), ); } }
news_toolkit/flutter_news_example/lib/onboarding/widgets/onboarding_view_item.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/onboarding/widgets/onboarding_view_item.dart", "repo_id": "news_toolkit", "token_count": 1389 }
962
// Generated code. Do not modify. const packageVersion = '0.0.1+1';
news_toolkit/flutter_news_example/lib/src/version.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/src/version.dart", "repo_id": "news_toolkit", "token_count": 24 }
963
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_news_example/l10n/l10n.dart'; import 'package:flutter_news_example/terms_of_service/terms_of_service.dart'; class TermsOfServicePage extends StatelessWidget { const TermsOfServicePage({super.key}); static Route<void> route() => MaterialPageRoute<void>( builder: (_) => const TermsOfServicePage(), ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: const AppBackButton(), ), body: const Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TermsOfServiceHeader(), TermsOfServiceBody( contentPadding: EdgeInsets.symmetric( horizontal: AppSpacing.xlg, vertical: AppSpacing.xs, ), ), SizedBox(height: AppSpacing.lg) ], ), ); } } @visibleForTesting class TermsOfServiceHeader extends StatelessWidget { const TermsOfServiceHeader({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.xlg, vertical: AppSpacing.lg, ), child: Text( context.l10n.termsOfServiceModalTitle, style: theme.textTheme.headlineMedium, ), ); } }
news_toolkit/flutter_news_example/lib/terms_of_service/view/terms_of_service_page.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/terms_of_service/view/terms_of_service_page.dart", "repo_id": "news_toolkit", "token_count": 613 }
964
export 'user_profile_button.dart'; export 'user_profile_subscribe_box.dart';
news_toolkit/flutter_news_example/lib/user_profile/widgets/widgets.dart/0
{ "file_path": "news_toolkit/flutter_news_example/lib/user_profile/widgets/widgets.dart", "repo_id": "news_toolkit", "token_count": 27 }
965
// ignore_for_file: prefer_const_constructors import 'package:analytics_repository/analytics_repository.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_test/flutter_test.dart'; class TestEvent extends Equatable with AnalyticsEventMixin { const TestEvent({required this.id}); final String id; @override AnalyticsEvent get event { return AnalyticsEvent( 'TestEvent', properties: <String, String>{'test-key': id}, ); } } void main() { group('AnalyticsEventMixin', () { const id = 'mock-id'; test('uses value equality', () { expect(TestEvent(id: id), equals(TestEvent(id: id))); }); }); }
news_toolkit/flutter_news_example/packages/analytics_repository/test/models/analytics_event_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/analytics_repository/test/models/analytics_event_test.dart", "repo_id": "news_toolkit", "token_count": 238 }
966
#import "GeneratedPluginRegistrant.h"
news_toolkit/flutter_news_example/packages/app_ui/gallery/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/ios/Runner/Runner-Bridging-Header.h", "repo_id": "news_toolkit", "token_count": 13 }
967
name: gallery description: Gallery project to showcase app_ui version: 0.0.1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: app_ui: path: ../ flutter: sdk: flutter dev_dependencies: very_good_analysis: ^5.1.0 flutter: uses-material-design: true
news_toolkit/flutter_news_example/packages/app_ui/gallery/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/gallery/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 121 }
968
/// Default Spacing in App UI. abstract class AppSpacing { /// The default unit of spacing static const double spaceUnit = 16; /// xxxs spacing value (1pt) static const double xxxs = 0.0625 * spaceUnit; /// xxs spacing value (2pt) static const double xxs = 0.125 * spaceUnit; /// xs spacing value (4pt) static const double xs = 0.25 * spaceUnit; /// sm spacing value (8pt) static const double sm = 0.5 * spaceUnit; /// md spacing value (12pt) static const double md = 0.75 * spaceUnit; /// lg spacing value (16pt) static const double lg = spaceUnit; /// xlg spacing value (24pt) static const double xlg = 1.5 * spaceUnit; /// xxlg spacing value (40pt) static const double xxlg = 2.5 * spaceUnit; /// xxxlg pacing value (64pt) static const double xxxlg = 4 * spaceUnit; }
news_toolkit/flutter_news_example/packages/app_ui/lib/src/spacing/app_spacing.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/lib/src/spacing/app_spacing.dart", "repo_id": "news_toolkit", "token_count": 272 }
969
export 'pump_app.dart';
news_toolkit/flutter_news_example/packages/app_ui/test/src/helpers/helpers.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/app_ui/test/src/helpers/helpers.dart", "repo_id": "news_toolkit", "token_count": 11 }
970
import 'package:clock/clock.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_news_example_api/client.dart'; import 'package:storage/storage.dart'; part 'article_storage.dart'; /// {@template article_failure} /// A base failure for the article repository failures. /// {@endtemplate} abstract class ArticleFailure with EquatableMixin implements Exception { /// {@macro article_failure} const ArticleFailure(this.error); /// The error which was caught. final Object error; @override List<Object> get props => [error]; } /// {@template get_article_failure} /// Thrown when fetching an article fails. /// {@endtemplate} class GetArticleFailure extends ArticleFailure { /// {@macro get_article_failure} const GetArticleFailure(super.error); } /// {@template get_related_articles_failure} /// Thrown when fetching related articles fails. /// {@endtemplate} class GetRelatedArticlesFailure extends ArticleFailure { /// {@macro get_related_articles_failure} const GetRelatedArticlesFailure(super.error); } /// {@template increment_article_views_failure} /// Thrown when incrementing article views fails. /// {@endtemplate} class IncrementArticleViewsFailure extends ArticleFailure { /// {@macro increment_article_views_failure} const IncrementArticleViewsFailure(super.error); } /// {@template decrement_article_views_failure} /// Thrown when decrementing article views fails. /// {@endtemplate} class DecrementArticleViewsFailure extends ArticleFailure { /// {@macro decrement_article_views_failure} const DecrementArticleViewsFailure(super.error); } /// {@template reset_article_views_failure} /// Thrown when resetting article views fails. /// {@endtemplate} class ResetArticleViewsFailure extends ArticleFailure { /// {@macro reset_article_views_failure} const ResetArticleViewsFailure(super.error); } /// {@template fetch_article_views_failure} /// Thrown when fetching article views fails. /// {@endtemplate} class FetchArticleViewsFailure extends ArticleFailure { /// {@macro fetch_article_views_failure} const FetchArticleViewsFailure(super.error); } /// {@template increment_total_article_views_failure} /// Thrown when incrementing total article views fails. /// {@endtemplate} class IncrementTotalArticleViewsFailure extends ArticleFailure { /// {@macro increment_total_article_views_failure} const IncrementTotalArticleViewsFailure(super.error); } /// {@template fetch_total_article_views_failure} /// Thrown when fetching total article views fails. /// {@endtemplate} class FetchTotalArticleViewsFailure extends ArticleFailure { /// {@macro fetch_total_article_views_failure} const FetchTotalArticleViewsFailure(super.error); } /// {@template article_views} /// Represents the number of article views and the date /// when the number of article views was last reset. /// {@endtemplate} class ArticleViews { /// {@macro article_views} ArticleViews(this.views, this.resetAt); /// The number of article views. final int views; /// The date when the number of article views was last reset. final DateTime? resetAt; } /// {@template article_repository} /// A repository that manages article data. /// {@endtemplate} class ArticleRepository { /// {@macro article_repository} const ArticleRepository({ required FlutterNewsExampleApiClient apiClient, required ArticleStorage storage, }) : _apiClient = apiClient, _storage = storage; final FlutterNewsExampleApiClient _apiClient; final ArticleStorage _storage; /// Requests article content metadata. /// /// Supported parameters: /// * [id] - Article id for which content is requested. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. /// * [preview] - Whether to return a preview of the article. Future<ArticleResponse> getArticle({ required String id, int? limit, int? offset, bool preview = false, }) async { try { return await _apiClient.getArticle( id: id, limit: limit, offset: offset, preview: preview, ); } catch (error, stackTrace) { Error.throwWithStackTrace(GetArticleFailure(error), stackTrace); } } /// Requests related articles. /// /// Supported parameters: /// * [id] - Article id for which related content is requested. /// * [limit] - The number of results to return. /// * [offset] - The (zero-based) offset of the first item /// in the collection to return. Future<RelatedArticlesResponse> getRelatedArticles({ required String id, int? limit, int? offset, }) async { try { return await _apiClient.getRelatedArticles( id: id, limit: limit, offset: offset, ); } catch (error, stackTrace) { Error.throwWithStackTrace(GetRelatedArticlesFailure(error), stackTrace); } } /// Increments the number of article views by 1. Future<void> incrementArticleViews() async { try { final currentArticleViews = await _storage.fetchArticleViews(); await _storage.setArticleViews(currentArticleViews + 1); } catch (error, stackTrace) { Error.throwWithStackTrace( IncrementArticleViewsFailure(error), stackTrace, ); } } /// Decrements the number of article views by 1. Future<void> decrementArticleViews() async { try { final currentArticleViews = await _storage.fetchArticleViews(); await _storage.setArticleViews(currentArticleViews - 1); } catch (error, stackTrace) { Error.throwWithStackTrace( DecrementArticleViewsFailure(error), stackTrace, ); } } /// Resets the number of article views. Future<void> resetArticleViews() async { try { await Future.wait([ _storage.setArticleViews(0), _storage.setArticleViewsResetDate(clock.now()), ]); } catch (error, stackTrace) { Error.throwWithStackTrace( ResetArticleViewsFailure(error), stackTrace, ); } } /// Fetches the number of article views. Future<ArticleViews> fetchArticleViews() async { try { late int views; late DateTime? resetAt; await Future.wait([ (() async => views = await _storage.fetchArticleViews())(), (() async => resetAt = await _storage.fetchArticleViewsResetDate())(), ]); return ArticleViews(views, resetAt); } catch (error, stackTrace) { Error.throwWithStackTrace( FetchArticleViewsFailure(error), stackTrace, ); } } /// Increments the number of total article views by 1. Future<void> incrementTotalArticleViews() async { try { final totalArticleViews = await _storage.fetchTotalArticleViews(); await _storage.setTotalArticleViews(totalArticleViews + 1); } catch (error, stackTrace) { Error.throwWithStackTrace( IncrementTotalArticleViewsFailure(error), stackTrace, ); } } /// Fetches the number of total article views. Future<int> fetchTotalArticleViews() async { try { return await _storage.fetchTotalArticleViews(); } catch (error, stackTrace) { Error.throwWithStackTrace( FetchTotalArticleViewsFailure(error), stackTrace, ); } } }
news_toolkit/flutter_news_example/packages/article_repository/lib/src/article_repository.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/article_repository/lib/src/article_repository.dart", "repo_id": "news_toolkit", "token_count": 2479 }
971
# firebase_authentication_client [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A Firebase implementation of the authentication client interface [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysi
news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/README.md/0
{ "file_path": "news_toolkit/flutter_news_example/packages/authentication_client/firebase_authentication_client/README.md", "repo_id": "news_toolkit", "token_count": 175 }
972
name: deep_link_client description: A Dart package which provides a deep link stream publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: equatable: ^2.0.3 firebase_core: ^2.24.2 firebase_dynamic_links: ^5.0.3 plugin_platform_interface: ^2.1.3 rxdart: ^0.27.3 dev_dependencies: firebase_core_platform_interface: ^5.0.0 flutter_test: sdk: flutter mocktail: ^1.0.2 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/deep_link_client/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/deep_link_client/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 187 }
973
name: form_inputs description: A Dart package which exposes reusable form inputs and validation rules publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: formz: ^0.7.0 dev_dependencies: test: ^1.21.4 very_good_analysis: ^5.1.0
news_toolkit/flutter_news_example/packages/form_inputs/pubspec.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/form_inputs/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 99 }
974
<svg width="70" height="78" viewBox="0 0 70 78" fill="none" xmlns="http://www.w3.org/2000/svg"> <g> <path d="M59 35 11 62.713V7.287L59 35Z" fill="#fff"/> </g> </svg>
news_toolkit/flutter_news_example/packages/news_blocks_ui/assets/icons/play_icon.svg/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/assets/icons/play_icon.svg", "repo_id": "news_toolkit", "token_count": 84 }
975
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; /// {@template post_large} /// A reusable post large block widget. /// {@endtemplate} class PostLarge extends StatelessWidget { /// {@macro post_large} const PostLarge({ required this.block, required this.premiumText, required this.isLocked, this.onPressed, super.key, }); /// The associated [PostLargeBlock] instance. final PostLargeBlock block; /// Text displayed when post is premium content. final String premiumText; /// Whether this post is a locked post. final bool isLocked; /// An optional callback which is invoked when the action is triggered. /// A [Uri] from the associated [BlockAction] is provided to the callback. final BlockActionCallback? onPressed; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => block.hasNavigationAction ? onPressed?.call(block.action!) : null, child: PostLargeContainer( isContentOverlaid: block.isContentOverlaid, children: [ PostLargeImage( isContentOverlaid: block.isContentOverlaid, imageUrl: block.imageUrl!, isLocked: isLocked, ), PostContent( author: block.author, categoryName: block.category.name, publishedAt: block.publishedAt, title: block.title, isPremium: block.isPremium, premiumText: premiumText, isContentOverlaid: block.isContentOverlaid, ), ], ), ); } } /// {@template post_large_container} /// A post container of large block widget which decides on build layout. /// {@endtemplate} @visibleForTesting class PostLargeContainer extends StatelessWidget { /// {@macro post_large_container} const PostLargeContainer({ required this.children, required this.isContentOverlaid, super.key, }); /// List containing children to be laid out. final List<Widget> children; /// Whether the content of this post should be overlaid on the image. /// /// Defaults to false. final bool isContentOverlaid; @override Widget build(BuildContext context) { return isContentOverlaid ? Stack( key: const Key('postLarge_stack'), alignment: Alignment.bottomLeft, children: children, ) : Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: Column( key: const Key('postLarge_column'), children: children, ), ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_large/post_large.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/post_large/post_large.dart", "repo_id": "news_toolkit", "token_count": 1088 }
976
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; /// {@template trending_story} /// A reusable trending story news block widget. /// {@endtemplate} class TrendingStory extends StatelessWidget { /// {@macro trending_story} const TrendingStory({required this.title, required this.block, super.key}); /// Title of the trending story. final String title; /// The associated [TrendingStoryBlock] instance. final TrendingStoryBlock block; @override Widget build(BuildContext context) { final theme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only( left: AppSpacing.lg, top: AppSpacing.md, ), child: Text( title, style: theme.labelSmall?.apply(color: AppColors.secondary), ), ), PostSmall(block: block.content) ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/trending_story.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/trending_story.dart", "repo_id": "news_toolkit", "token_count": 451 }
977
import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; /// {@template slideshow_category} /// A widget displaying a slideshow label. /// A widget displaying a slideshow category. /// {@endtemplate} class SlideshowCategory extends StatelessWidget { /// {@macro slideshow_category} const SlideshowCategory({ required this.slideshowText, this.isIntroduction = true, super.key, }); /// Whether this slideshow category is /// being displayed in an introduction. final bool isIntroduction; /// Text displayed in the slideshow category widget. final String slideshowText; @override Widget build(BuildContext context) { final backgroundColor = isIntroduction ? AppColors.secondary : AppColors.transparent; final textColor = isIntroduction ? AppColors.white : AppColors.orange; const horizontalSpacing = AppSpacing.xs; return Column( children: [ Align( alignment: Alignment.centerLeft, child: DecoratedBox( decoration: BoxDecoration(color: backgroundColor), child: Padding( padding: const EdgeInsets.fromLTRB( horizontalSpacing, 0, horizontalSpacing, AppSpacing.xxs, ), child: Text( slideshowText.toUpperCase(), style: Theme.of(context) .textTheme .labelSmall ?.copyWith(color: textColor), ), ), ), ), ], ); } }
news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/slideshow_category.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/lib/src/widgets/slideshow_category.dart", "repo_id": "news_toolkit", "token_count": 684 }
978
// ignore_for_file: prefer_const_constructors 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('NewsletterContainer', () { testWidgets('renders correctly', (tester) async { await tester.pumpContentThemedApp(NewsletterContainer()); expect( find.byWidgetPredicate( (widget) => widget is ColoredBox && widget.color == AppColors.secondary.shade800, ), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_container_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/newsletter/newsletter_container_test.dart", "repo_id": "news_toolkit", "token_count": 276 }
979
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/news_blocks_ui.dart'; import '../helpers/helpers.dart'; void main() { group('SectionHeader', () { setUpAll(setUpTolerantComparator); testWidgets('renders correctly without action', (tester) async { const widget = Center( child: SectionHeader( block: SectionHeaderBlock(title: 'example'), ), ); await tester.pumpApp(widget); await expectLater( find.byType(SectionHeader), matchesGoldenFile('section_header_without_action.png'), ); }); testWidgets('renders correctly with action', (tester) async { const widget = Center( child: SectionHeader( block: SectionHeaderBlock( title: 'example', action: NavigateToFeedCategoryAction(category: Category.top), ), ), ); await tester.pumpApp(widget); await expectLater( find.byType(SectionHeader), matchesGoldenFile('section_header_with_action.png'), ); }); testWidgets('onPressed is called with action on tap', (tester) async { final actions = <BlockAction>[]; const action = NavigateToFeedCategoryAction(category: Category.top); final widget = Center( child: SectionHeader( block: const SectionHeaderBlock( title: 'example', action: action, ), onPressed: actions.add, ), ); await tester.pumpApp(widget); await tester.tap(find.byType(IconButton)); expect(actions, equals([action])); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/section_header_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/section_header_test.dart", "repo_id": "news_toolkit", "token_count": 719 }
980
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:news_blocks_ui/src/widgets/widgets.dart'; import '../../helpers/helpers.dart'; void main() { group('BannerAdContainer', () { testWidgets('renders ColoredBox', (tester) async { await tester.pumpApp( BannerAdContainer( size: BannerAdSize.normal, child: SizedBox(), ), ); expect(find.byKey(Key('bannerAdContainer_coloredBox')), findsOneWidget); }); testWidgets('renders child', (tester) async { const childKey = Key('__child__'); await tester.pumpApp( BannerAdContainer( size: BannerAdSize.large, child: SizedBox(key: childKey), ), ); expect(find.byKey(childKey), findsOneWidget); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/banner_ad_container_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/banner_ad_container_test.dart", "repo_id": "news_toolkit", "token_count": 392 }
981
import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; import 'package:news_blocks_ui/src/widgets/share_button.dart'; import '../../helpers/helpers.dart'; void main() { group('ShareButton', () { testWidgets('calls onPress when tapped', (tester) async { final completer = Completer<void>(); await tester.pumpContentThemedApp( ShareButton( shareText: 'shareText', onPressed: completer.complete, ), ); await tester.tap(find.byType(ShareButton)); expect(completer.isCompleted, isTrue); }); }); }
news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/share_button_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/news_blocks_ui/test/src/widgets/share_button_test.dart", "repo_id": "news_toolkit", "token_count": 248 }
982
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/notifications_repository/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/notifications_repository/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
983
include: package:very_good_analysis/analysis_options.5.1.0.yaml
news_toolkit/flutter_news_example/packages/permission_client/analysis_options.yaml/0
{ "file_path": "news_toolkit/flutter_news_example/packages/permission_client/analysis_options.yaml", "repo_id": "news_toolkit", "token_count": 23 }
984
export 'src/share_launcher.dart';
news_toolkit/flutter_news_example/packages/share_launcher/lib/share_launcher.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/share_launcher/lib/share_launcher.dart", "repo_id": "news_toolkit", "token_count": 13 }
985
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:secure_storage/secure_storage.dart'; import 'package:storage/storage.dart'; class MockFlutterSecureStorage extends Mock implements FlutterSecureStorage {} void main() { const mockKey = 'mock-key'; const mockValue = 'mock-value'; final mockException = Exception('oops'); group('SecureStorage', () { late FlutterSecureStorage flutterSecureStorage; late SecureStorage secureStorage; setUp(() { flutterSecureStorage = MockFlutterSecureStorage(); secureStorage = SecureStorage(flutterSecureStorage); }); group('constructor', () { test('defaults to internal FlutterSecureStorage if none is provided', () { expect(() => const SecureStorage(), isNot(throwsA(isA<Exception>()))); }); }); group('read', () { test('returns value when FlutterSecureStorage returns successfully', () async { when(() => flutterSecureStorage.read(key: any(named: 'key'))) .thenAnswer((_) => Future.value(mockValue)); final actual = await secureStorage.read(key: mockKey); expect(actual, mockValue); }); test('returns null when FlutterSecureStorage returns null', () async { when(() => flutterSecureStorage.read(key: any(named: 'key'))) .thenAnswer((_) => Future<String?>.value()); final actual = await secureStorage.read(key: mockKey); expect(actual, isNull); }); test('throws StorageException when FlutterSecureStorage fails', () async { when(() => flutterSecureStorage.read(key: any(named: 'key'))) .thenThrow(mockException); try { await secureStorage.read(key: mockKey); } on StorageException catch (e) { expect(e.error, mockException); } }); }); group('write', () { test('completes when FlutterSecureStorage completes', () async { when( () => flutterSecureStorage.write( key: any(named: 'key'), value: any(named: 'value'), ), ).thenAnswer((_) => Future.value()); expect( secureStorage.write(key: mockKey, value: mockValue), completes, ); }); test('throws StorageException when FlutterSecureStorage fails', () async { when( () => flutterSecureStorage.write( key: any(named: 'key'), value: any(named: 'value'), ), ).thenThrow(mockException); try { await secureStorage.write(key: mockKey, value: mockValue); } on StorageException catch (e) { expect(e.error, mockException); } }); }); group('delete', () { test('completes when FlutterSecureStorage completes', () async { when(() => flutterSecureStorage.delete(key: any(named: 'key'))) .thenAnswer((_) => Future.value()); expect( secureStorage.delete(key: mockKey), completes, ); }); test('throws StorageException when FlutterSecureStorage fails', () async { when(() => flutterSecureStorage.delete(key: any(named: 'key'))) .thenThrow(mockException); try { await secureStorage.delete(key: mockKey); } on StorageException catch (e) { expect(e.error, mockException); } }); }); group('clear', () { test('completes when FlutterSecureStorage completes', () async { when(() => flutterSecureStorage.deleteAll()) .thenAnswer((_) => Future.value()); expect(secureStorage.clear(), completes); }); test('throws StorageException when FlutterSecureStorage fails', () async { when(() => flutterSecureStorage.deleteAll()).thenThrow(mockException); try { await secureStorage.clear(); } on StorageException catch (e) { expect(e.error, mockException); } }); }); }); }
news_toolkit/flutter_news_example/packages/storage/secure_storage/test/secure_storage_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/storage/secure_storage/test/secure_storage_test.dart", "repo_id": "news_toolkit", "token_count": 1664 }
986
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:authentication_client/authentication_client.dart'; import 'package:deep_link_client/deep_link_client.dart'; import 'package:flutter_news_example_api/client.dart' as api; import 'package:mocktail/mocktail.dart'; import 'package:package_info_client/package_info_client.dart'; import 'package:test/test.dart'; import 'package:user_repository/user_repository.dart'; class MockAuthenticationClient extends Mock implements AuthenticationClient {} class MockPackageInfoClient extends Mock implements PackageInfoClient {} class MockDeepLinkClient extends Mock implements DeepLinkClient {} class MockUserStorage extends Mock implements UserStorage {} class MockUser extends Mock implements AuthenticationUser {} class MockFlutterNewsExampleApiClient extends Mock implements api.FlutterNewsExampleApiClient {} class FakeLogInWithAppleFailure extends Fake implements LogInWithAppleFailure {} class FakeLogInWithGoogleFailure extends Fake implements LogInWithGoogleFailure {} class FakeLogInWithGoogleCanceled extends Fake implements LogInWithGoogleCanceled {} class FakeLogInWithTwitterFailure extends Fake implements LogInWithTwitterFailure {} class FakeLogInWithTwitterCanceled extends Fake implements LogInWithTwitterCanceled {} class FakeLogInWithFacebookFailure extends Fake implements LogInWithFacebookFailure {} class FakeLogInWithFacebookCanceled extends Fake implements LogInWithFacebookCanceled {} class FakeLogOutFailure extends Fake implements LogOutFailure {} class FakeSendLoginEmailLinkFailure extends Fake implements SendLoginEmailLinkFailure {} class FakeLogInWithEmailLinkFailure extends Fake implements LogInWithEmailLinkFailure {} void main() { group('UserRepository', () { late AuthenticationClient authenticationClient; late PackageInfoClient packageInfoClient; late DeepLinkClient deepLinkClient; late UserStorage storage; late StreamController<Uri> deepLinkClientController; late UserRepository userRepository; late MockFlutterNewsExampleApiClient apiClient; setUp(() { authenticationClient = MockAuthenticationClient(); packageInfoClient = MockPackageInfoClient(); deepLinkClient = MockDeepLinkClient(); storage = MockUserStorage(); deepLinkClientController = StreamController<Uri>.broadcast(); apiClient = MockFlutterNewsExampleApiClient(); when(() => deepLinkClient.deepLinkStream) .thenAnswer((_) => deepLinkClientController.stream); userRepository = UserRepository( apiClient: apiClient, authenticationClient: authenticationClient, packageInfoClient: packageInfoClient, deepLinkClient: deepLinkClient, storage: storage, ); }); test( 'currentSubscriptionPlan emits none ' 'when initialized and authenticationClient.user is anonymous', () async { when(() => authenticationClient.user).thenAnswer( (invocation) => Stream.value(AuthenticationUser.anonymous), ); final response = await userRepository.user.first; expect( response.subscriptionPlan, equals(api.SubscriptionPlan.none), ); }); group('user', () { test('calls user on AuthenticationClient', () { when(() => authenticationClient.user).thenAnswer( (_) => const Stream.empty(), ); userRepository.user; verify(() => authenticationClient.user).called(1); }); }); group('incomingEmailLinks', () { final validEmailLink = Uri.https('valid.email.link'); final validEmailLink2 = Uri.https('valid.email.link'); final invalidEmailLink = Uri.https('invalid.email.link'); test( 'emits a new email link ' 'for every valid email link from DeepLinkClient.deepLinkStream', () { when( () => authenticationClient.isLogInWithEmailLink( emailLink: validEmailLink.toString(), ), ).thenReturn(true); when( () => authenticationClient.isLogInWithEmailLink( emailLink: validEmailLink2.toString(), ), ).thenReturn(true); when( () => authenticationClient.isLogInWithEmailLink( emailLink: invalidEmailLink.toString(), ), ).thenReturn(false); expectLater( userRepository.incomingEmailLinks, emitsInOrder(<Uri>[ validEmailLink, validEmailLink2, ]), ); deepLinkClientController ..add(validEmailLink) ..add(invalidEmailLink) ..add(validEmailLink2); }); }); group('logInWithApple', () { test('calls logInWithApple on AuthenticationClient', () async { when( () => authenticationClient.logInWithApple(), ).thenAnswer((_) async {}); await userRepository.logInWithApple(); verify(() => authenticationClient.logInWithApple()).called(1); }); test('rethrows LogInWithAppleFailure', () async { final exception = FakeLogInWithAppleFailure(); when( () => authenticationClient.logInWithApple(), ).thenThrow(exception); expect( () => userRepository.logInWithApple(), throwsA(exception), ); }); test('throws LogInWithAppleFailure on generic exception', () async { when( () => authenticationClient.logInWithApple(), ).thenThrow(Exception()); expect( () => userRepository.logInWithApple(), throwsA(isA<LogInWithAppleFailure>()), ); }); }); group('logInWithGoogle', () { test('calls logInWithGoogle on AuthenticationClient', () async { when( () => authenticationClient.logInWithGoogle(), ).thenAnswer((_) async {}); await userRepository.logInWithGoogle(); verify(() => authenticationClient.logInWithGoogle()).called(1); }); test('rethrows LogInWithGoogleFailure', () async { final exception = FakeLogInWithGoogleFailure(); when(() => authenticationClient.logInWithGoogle()).thenThrow(exception); expect(() => userRepository.logInWithGoogle(), throwsA(exception)); }); test('rethrows LogInWithGoogleCanceled', () async { final exception = FakeLogInWithGoogleCanceled(); when(() => authenticationClient.logInWithGoogle()).thenThrow(exception); expect(userRepository.logInWithGoogle(), throwsA(exception)); }); test('throws LogInWithGoogleFailure on generic exception', () async { when( () => authenticationClient.logInWithGoogle(), ).thenThrow(Exception()); expect( () => userRepository.logInWithGoogle(), throwsA(isA<LogInWithGoogleFailure>()), ); }); }); group('logInWithTwitter', () { test('calls logInWithTwitter on AuthenticationClient', () async { when( () => authenticationClient.logInWithTwitter(), ).thenAnswer((_) async {}); await userRepository.logInWithTwitter(); verify(() => authenticationClient.logInWithTwitter()).called(1); }); test('rethrows LogInWithTwitterFailure', () async { final exception = FakeLogInWithTwitterFailure(); when(() => authenticationClient.logInWithTwitter()) .thenThrow(exception); expect(() => userRepository.logInWithTwitter(), throwsA(exception)); }); test('rethrows LogInWithTwitterCanceled', () async { final exception = FakeLogInWithTwitterCanceled(); when(() => authenticationClient.logInWithTwitter()) .thenThrow(exception); expect(userRepository.logInWithTwitter(), throwsA(exception)); }); test('throws LogInWithTwitterFailure on generic exception', () async { when( () => authenticationClient.logInWithTwitter(), ).thenThrow(Exception()); expect( () => userRepository.logInWithTwitter(), throwsA(isA<LogInWithTwitterFailure>()), ); }); }); group('logInWithFacebook', () { test('calls logInWithFacebook on AuthenticationClient', () async { when( () => authenticationClient.logInWithFacebook(), ).thenAnswer((_) async {}); await userRepository.logInWithFacebook(); verify(() => authenticationClient.logInWithFacebook()).called(1); }); test('rethrows LogInWithFacebookFailure', () async { final exception = FakeLogInWithFacebookFailure(); when(() => authenticationClient.logInWithFacebook()) .thenThrow(exception); expect(() => userRepository.logInWithFacebook(), throwsA(exception)); }); test('rethrows LogInWithFacebookCanceled', () async { final exception = FakeLogInWithFacebookCanceled(); when(() => authenticationClient.logInWithFacebook()) .thenThrow(exception); expect(userRepository.logInWithFacebook(), throwsA(exception)); }); test('throws LogInWithFacebookFailure on generic exception', () async { when( () => authenticationClient.logInWithFacebook(), ).thenThrow(Exception()); expect( () => userRepository.logInWithFacebook(), throwsA(isA<LogInWithFacebookFailure>()), ); }); }); group('sendLoginEmailLink', () { const packageName = 'appPackageName'; setUp(() { when( () => packageInfoClient.packageName, ).thenReturn(packageName); when( () => authenticationClient.sendLoginEmailLink( email: any(named: 'email'), appPackageName: any(named: 'appPackageName'), ), ).thenAnswer((_) async {}); }); test( 'calls sendLoginEmailLink on AuthenticationClient ' 'with email and app package name from PackageInfoClient', () async { await userRepository.sendLoginEmailLink( email: '[email protected]', ); verify( () => authenticationClient.sendLoginEmailLink( email: any(named: 'email'), appPackageName: packageName, ), ).called(1); }); test('rethrows SendLoginEmailLinkFailure', () async { final exception = FakeSendLoginEmailLinkFailure(); when( () => authenticationClient.sendLoginEmailLink( email: any(named: 'email'), appPackageName: any(named: 'appPackageName'), ), ).thenThrow(exception); expect( () => userRepository.sendLoginEmailLink( email: '[email protected]', ), throwsA(exception), ); }); test( 'throws FakeSendLoginEmailLinkFailure ' 'on generic exception', () async { when( () => authenticationClient.sendLoginEmailLink( email: any(named: 'email'), appPackageName: any(named: 'appPackageName'), ), ).thenThrow(Exception()); expect( () => userRepository.sendLoginEmailLink( email: '[email protected]', ), throwsA(isA<SendLoginEmailLinkFailure>()), ); }); }); group('logInWithEmailLink', () { const email = '[email protected]'; const emailLink = 'email.link'; test('calls logInWithEmailLink on AuthenticationClient', () async { when( () => authenticationClient.logInWithEmailLink( email: any(named: 'email'), emailLink: any(named: 'emailLink'), ), ).thenAnswer((_) async {}); await userRepository.logInWithEmailLink( email: email, emailLink: emailLink, ); verify( () => authenticationClient.logInWithEmailLink( email: email, emailLink: emailLink, ), ).called(1); }); test('rethrows LogInWithEmailLinkFailure', () async { final exception = FakeLogInWithEmailLinkFailure(); when( () => authenticationClient.logInWithEmailLink( email: any(named: 'email'), emailLink: any(named: 'emailLink'), ), ).thenThrow(exception); expect( () => userRepository.logInWithEmailLink( email: email, emailLink: emailLink, ), throwsA(exception), ); }); test('throws LogInWithEmailLinkFailure on generic exception', () async { when( () => authenticationClient.logInWithEmailLink( email: any(named: 'email'), emailLink: any(named: 'emailLink'), ), ).thenThrow(Exception()); expect( () => userRepository.logInWithEmailLink( email: email, emailLink: emailLink, ), throwsA(isA<LogInWithEmailLinkFailure>()), ); }); }); group('logOut', () { test('calls logOut on AuthenticationClient', () async { when(() => authenticationClient.logOut()).thenAnswer((_) async {}); await userRepository.logOut(); verify(() => authenticationClient.logOut()).called(1); }); test('rethrows LogOutFailure', () async { final exception = FakeLogOutFailure(); when(() => authenticationClient.logOut()).thenThrow(exception); expect(() => userRepository.logOut(), throwsA(exception)); }); test('throws LogOutFailure on generic exception', () async { when(() => authenticationClient.logOut()).thenThrow(Exception()); expect(() => userRepository.logOut(), throwsA(isA<LogOutFailure>())); }); }); group('UserFailure', () { final error = Exception('errorMessage'); group('FetchAppOpenedCountFailure', () { test('has correct props', () { expect(FetchAppOpenedCountFailure(error).props, [error]); }); }); group('IncrementAppOpenedCountFailure', () { test('has correct props', () { expect(IncrementAppOpenedCountFailure(error).props, [error]); }); }); }); group('fetchAppOpenedCount', () { test('returns the app opened count from UserStorage ', () async { when(storage.fetchAppOpenedCount).thenAnswer((_) async => 1); final result = await UserRepository( apiClient: apiClient, authenticationClient: authenticationClient, packageInfoClient: packageInfoClient, deepLinkClient: deepLinkClient, storage: storage, ).fetchAppOpenedCount(); expect(result, 1); }); test( 'throws a FetchAppOpenedCountFailure ' 'when fetching app opened count fails', () async { when(() => storage.fetchAppOpenedCount()).thenThrow(Exception()); expect( UserRepository( apiClient: apiClient, authenticationClient: authenticationClient, packageInfoClient: packageInfoClient, deepLinkClient: deepLinkClient, storage: storage, ).fetchAppOpenedCount(), throwsA(isA<FetchAppOpenedCountFailure>()), ); }); }); group('setAppOpenedCount', () { test('increments app opened count by 1 in UserStorage', () async { when(() => storage.fetchAppOpenedCount()).thenAnswer((_) async => 3); when( () => storage.setAppOpenedCount(count: 4), ).thenAnswer((_) async {}); await expectLater( UserRepository( apiClient: apiClient, authenticationClient: authenticationClient, packageInfoClient: packageInfoClient, deepLinkClient: deepLinkClient, storage: storage, ).incrementAppOpenedCount(), completes, ); }); test( 'throws a IncrementAppOpenedCountFailure ' 'when setting app opened count fails', () async { when( () => storage.setAppOpenedCount(count: any(named: 'count')), ).thenThrow(Exception()); expect( UserRepository( apiClient: apiClient, authenticationClient: authenticationClient, packageInfoClient: packageInfoClient, deepLinkClient: deepLinkClient, storage: storage, ).incrementAppOpenedCount(), throwsA(isA<IncrementAppOpenedCountFailure>()), ); }); }); group('updateSubscriptionPlan', () { test('calls getCurrentUser on ApiClient', () async { when(() => apiClient.getCurrentUser()).thenAnswer( (_) async => api.CurrentUserResponse( user: api.User( id: 'id', subscription: api.SubscriptionPlan.none, ), ), ); await userRepository.updateSubscriptionPlan(); verify(() => apiClient.getCurrentUser()).called(1); }); test('throws FetchCurrentSubscriptionFailure on failure', () async { when( () => apiClient.getCurrentUser(), ).thenThrow(Exception()); expect( () => userRepository.updateSubscriptionPlan(), throwsA(isA<FetchCurrentSubscriptionFailure>()), ); }); }); }); }
news_toolkit/flutter_news_example/packages/user_repository/test/src/user_repository_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/packages/user_repository/test/src/user_repository_test.dart", "repo_id": "news_toolkit", "token_count": 7110 }
987
// ignore_for_file: prefer_const_constructors, avoid_redundant_argument_values // ignore_for_file: prefer_const_literals_to_create_immutables import 'package:article_repository/article_repository.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:clock/clock.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_blocks/news_blocks.dart'; import 'package:share_launcher/share_launcher.dart'; import '../../helpers/helpers.dart'; class MockArticleRepository extends Mock implements ArticleRepository {} class MockShareLauncher extends Mock implements ShareLauncher {} void main() { initMockHydratedStorage(); group('ArticleBloc', () { const articleId = 'articleId'; final uri = Uri(path: 'text'); late ArticleRepository articleRepository; late ShareLauncher shareLauncher; late ArticleBloc articleBloc; final articleResponse = ArticleResponse( title: 'title', content: [ TextCaptionBlock(text: 'text', color: TextCaptionColor.normal), TextParagraphBlock(text: 'text'), ], totalCount: 4, url: Uri.parse('https://www.dglobe.com/'), isPreview: false, isPremium: true, ); final articleStatePopulated = ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: [ TextHeadlineBlock(text: 'text'), SpacerBlock(spacing: Spacing.large), ], uri: Uri.parse('https://www.dglobe.com/'), hasMoreContent: true, isPreview: false, isPremium: true, ); final relatedArticlesResponse = RelatedArticlesResponse( relatedArticles: articleResponse.content, totalCount: 2, ); setUp(() async { articleRepository = MockArticleRepository(); shareLauncher = MockShareLauncher(); articleBloc = ArticleBloc( articleId: articleId, shareLauncher: shareLauncher, articleRepository: articleRepository, ); when( () => articleRepository.getRelatedArticles( id: any(named: 'id'), offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenAnswer((_) async => relatedArticlesResponse); }); test('can be (de)serialized', () { final serialized = articleBloc.toJson(articleStatePopulated); final deserialized = articleBloc.fromJson(serialized!); expect(deserialized, articleStatePopulated); }); group('on ArticleRequested', () { setUp(() { when(articleRepository.incrementArticleViews).thenAnswer((_) async {}); when(articleRepository.resetArticleViews).thenAnswer((_) async {}); when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(3, DateTime(2022, 6, 7))); when(() => articleRepository.incrementTotalArticleViews()) .thenAnswer((_) async => {}); when(() => articleRepository.fetchTotalArticleViews()) .thenAnswer((_) async => 0); when( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), preview: any(named: 'preview'), ), ).thenAnswer((_) async => articleResponse); }); blocTest<ArticleBloc, ArticleState>( 'emits [loading, populated] ' 'when getArticle succeeds ' 'and there is more content to fetch', build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, relatedArticles: [], uri: articleResponse.url, hasMoreContent: true, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, ), ], ); blocTest<ArticleBloc, ArticleState>( 'emits [loading, populated] ' 'with appended content and relatedArticles ' 'when getArticle succeeds ' 'and there is no more content to fetch', seed: () => articleStatePopulated, build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ articleStatePopulated.copyWith(status: ArticleStatus.loading), articleStatePopulated.copyWith( status: ArticleStatus.populated, content: [ ...articleStatePopulated.content, ...articleResponse.content, ], contentTotalCount: articleResponse.totalCount, relatedArticles: relatedArticlesResponse.relatedArticles, hasMoreContent: false, ) ], ); blocTest<ArticleBloc, ArticleState>( 'emits [loading, failure] ' 'when getArticle fails', setUp: () => when( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenThrow(Exception()), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState(status: ArticleStatus.failure), ], ); blocTest<ArticleBloc, ArticleState>( 'emits [loading, failure] ' 'when getRelatedArticles fails', seed: () => articleStatePopulated, setUp: () { when( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenAnswer((_) async => articleResponse); when( () => articleRepository.getRelatedArticles( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), ), ).thenThrow(Exception()); }, build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ articleStatePopulated.copyWith(status: ArticleStatus.loading), articleStatePopulated.copyWith(status: ArticleStatus.failure), ], ); blocTest<ArticleBloc, ArticleState>( 'calls ArticleRepository.resetArticleViews ' 'and ArticleRepository.incrementArticleViews ' 'and emits hasReachedArticleViewsLimit as false ' 'when the number of article views was never reset', setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(0, null)), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, hasMoreContent: true, uri: articleResponse.url, hasReachedArticleViewsLimit: false, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, ), ], verify: (bloc) { verify(articleRepository.resetArticleViews).called(1); verify(articleRepository.incrementArticleViews).called(1); verify( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), preview: false, ), ).called(1); }, ); blocTest<ArticleBloc, ArticleState>( 'calls ShareLauncher.share ' 'and emits nothing ' 'when share succeeds', setUp: () => when( () => shareLauncher.share(text: any(named: 'text')), ).thenAnswer((_) async {}), build: () => articleBloc, act: (bloc) => bloc.add(ShareRequested(uri: uri)), expect: () => <ArticleState>[], verify: (bloc) => verify(() => shareLauncher.share(text: uri.toString())).called(1), ); blocTest<ArticleBloc, ArticleState>( 'emits [shareFailure] ' 'when share throws', setUp: () => when( () => shareLauncher.share(text: any(named: 'text')), ).thenThrow(Exception()), build: () => articleBloc, act: (bloc) => bloc.add(ShareRequested(uri: uri)), expect: () => <ArticleState>[ ArticleState.initial().copyWith(status: ArticleStatus.shareFailure), ], ); test( 'calls ArticleRepository.resetArticleViews ' 'and ArticleRepository.incrementArticleViews ' 'and emits hasReachedArticleViewsLimit as false ' 'when the number of article views was last reset ' 'more than a day ago', () async { final resetAt = DateTime(2022, 6, 7); final now = DateTime(2022, 6, 8, 0, 0, 1); await withClock(Clock.fixed(now), () async { await testBloc<ArticleBloc, ArticleState>( setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(3, resetAt)), build: () => ArticleBloc( articleId: articleId, articleRepository: articleRepository, shareLauncher: shareLauncher, ), act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, uri: articleResponse.url, hasMoreContent: true, hasReachedArticleViewsLimit: false, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, ), ], verify: (bloc) { verify(articleRepository.resetArticleViews).called(1); verify(articleRepository.incrementArticleViews).called(1); verify( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), preview: false, ), ).called(1); }, ); }); }); test( 'calls ArticleRepository.incrementArticleViews ' 'and emits hasReachedArticleViewsLimit as false ' 'when the article views limit of 4 was not reached ' 'and the the number of article views was last reset ' 'less than a day ago', () async { final resetAt = DateTime(2022, 6, 7, 1, 0, 0); final now = DateTime(2022, 6, 7, 12, 0, 0); await withClock(Clock.fixed(now), () async { await testBloc<ArticleBloc, ArticleState>( setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(2, resetAt)), build: () => ArticleBloc( articleId: articleId, shareLauncher: shareLauncher, articleRepository: articleRepository, ), act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, uri: articleResponse.url, hasMoreContent: true, hasReachedArticleViewsLimit: false, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, ), ], verify: (bloc) { verify(articleRepository.incrementArticleViews).called(1); verify( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), preview: false, ), ).called(1); verifyNever(() => articleRepository.resetArticleViews()); }, ); }); }); test( 'does not call ArticleRepository.incrementArticleViews ' 'and emits hasReachedArticleViewsLimit as true ' 'when the article views limit of 4 was reached ' 'and the the number of article views was last reset ' 'less than a day ago', () async { final resetAt = DateTime(2022, 6, 7); final now = DateTime(2022, 6, 7, 12, 0, 0); withClock(Clock.fixed(now), () { testBloc<ArticleBloc, ArticleState>( seed: () => ArticleState(status: ArticleStatus.populated), setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(4, resetAt)), build: () => ArticleBloc( articleId: articleId, articleRepository: articleRepository, shareLauncher: shareLauncher, ), act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, uri: articleResponse.url, hasMoreContent: true, hasReachedArticleViewsLimit: true, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, ), ], verify: (bloc) { verifyNever(articleRepository.resetArticleViews); verifyNever(articleRepository.incrementArticleViews); verify( () => articleRepository.getArticle( id: articleId, offset: any(named: 'offset'), limit: any(named: 'limit'), preview: true, ), ).called(1); }, ); }); }); blocTest<ArticleBloc, ArticleState>( 'emits showInterstitialAd true ' 'when fetchTotalArticleViews returns 4 ', setUp: () { when(() => articleRepository.fetchTotalArticleViews()) .thenAnswer((_) async => 4); }, build: () => articleBloc, act: (bloc) => bloc.add(ArticleRequested()), expect: () => <ArticleState>[ ArticleState(status: ArticleStatus.loading), ArticleState(status: ArticleStatus.loading, showInterstitialAd: true), ArticleState( status: ArticleStatus.populated, title: articleResponse.title, content: articleResponse.content, contentTotalCount: articleResponse.totalCount, relatedArticles: [], uri: articleResponse.url, hasMoreContent: true, isPreview: articleResponse.isPreview, isPremium: articleResponse.isPremium, showInterstitialAd: true, ), ], ); }); group('on ArticleContentSeen', () { blocTest<ArticleBloc, ArticleState>( 'emits updated contentSeenCount ' 'when new count (contentIndex + 1) is higher than current', build: () => articleBloc, act: (bloc) => bloc.add(ArticleContentSeen(contentIndex: 15)), seed: () => articleStatePopulated.copyWith( contentSeenCount: 10, ), expect: () => <ArticleState>[ articleStatePopulated.copyWith( contentSeenCount: 16, ), ], ); blocTest<ArticleBloc, ArticleState>( 'does not emit updated contentSeenCount ' 'when new count (contentIndex + 1) is less than ' 'or equal to current', build: () => articleBloc, act: (bloc) => bloc.add(ArticleContentSeen(contentIndex: 9)), seed: () => articleStatePopulated.copyWith( contentSeenCount: 10, ), expect: () => <ArticleState>[], ); }); group('on ArticleRewardedAdWatched', () { setUp(() { when(articleRepository.decrementArticleViews).thenAnswer((_) async {}); }); blocTest<ArticleBloc, ArticleState>( 'calls ArticleRepository.decrementArticleViews ' 'and emits hasReachedArticleViewsLimit as false ' 'when the number of article views is less than ' 'the article views limit of 4', setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(3, null)), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRewardedAdWatched()), seed: () => articleStatePopulated.copyWith( hasReachedArticleViewsLimit: true, ), expect: () => <ArticleState>[ articleStatePopulated.copyWith( hasReachedArticleViewsLimit: false, ), ], verify: (bloc) => verify(articleRepository.decrementArticleViews).called(1), ); blocTest<ArticleBloc, ArticleState>( 'calls ArticleRepository.decrementArticleViews ' 'and emits hasReachedArticleViewsLimit as true ' 'when the number of article views is equal to ' 'the article views limit of 4', setUp: () => when(articleRepository.fetchArticleViews) .thenAnswer((_) async => ArticleViews(4, null)), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRewardedAdWatched()), seed: () => articleStatePopulated.copyWith( hasReachedArticleViewsLimit: false, ), expect: () => <ArticleState>[ articleStatePopulated.copyWith( hasReachedArticleViewsLimit: true, ), ], verify: (bloc) => verify(articleRepository.decrementArticleViews).called(1), ); blocTest<ArticleBloc, ArticleState>( 'emits [rewardedAdWatchedFailure] ' 'when decrementArticleViews throws', setUp: () => when(articleRepository.decrementArticleViews) .thenThrow(Exception()), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRewardedAdWatched()), expect: () => <ArticleState>[ ArticleState.initial() .copyWith(status: ArticleStatus.rewardedAdWatchedFailure), ], ); blocTest<ArticleBloc, ArticleState>( 'emits [rewardedAdWatchedFailure] ' 'when fetchArticleViews throws', setUp: () => when(articleRepository.fetchArticleViews).thenThrow(Exception()), build: () => articleBloc, act: (bloc) => bloc.add(ArticleRewardedAdWatched()), expect: () => <ArticleState>[ ArticleState.initial() .copyWith(status: ArticleStatus.rewardedAdWatchedFailure), ], ); }); group('on ArticleCommented', () { blocTest<ArticleBloc, ArticleState>( 'does not emit a new state', build: () => articleBloc, act: (bloc) => bloc.add(ArticleCommented(articleTitle: 'title')), expect: () => <ArticleState>[], ); }); }); }
news_toolkit/flutter_news_example/test/article/bloc/article_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/article/bloc/article_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 9213 }
988
@Tags(['presubmit-only']) library; import 'package:build_verify/build_verify.dart'; import 'package:test/test.dart'; void main() { test( 'ensure_build', () { expectBuildClean( customCommand: [ 'flutter', 'pub', 'run', 'build_runner', 'build', '--delete-conflicting-outputs' ], ); }, tags: ['presubmit-only'], ); }
news_toolkit/flutter_news_example/test/ensure_build_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/ensure_build_test.dart", "repo_id": "news_toolkit", "token_count": 223 }
989
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:form_inputs/form_inputs.dart'; import 'package:mocktail/mocktail.dart'; import 'package:user_repository/user_repository.dart'; class MockUserRepository extends Mock implements UserRepository {} class MockUser extends Mock implements User {} void main() { const invalidEmailString = 'invalid'; const invalidEmail = Email.dirty(invalidEmailString); const validEmailString = '[email protected]'; const validEmail = Email.dirty(validEmailString); group('LoginBloc', () { late UserRepository userRepository; setUp(() { userRepository = MockUserRepository(); when( () => userRepository.logInWithGoogle(), ).thenAnswer((_) => Future<void>.value()); when( () => userRepository.logInWithTwitter(), ).thenAnswer((_) => Future<void>.value()); when( () => userRepository.logInWithFacebook(), ).thenAnswer((_) => Future<void>.value()); when( () => userRepository.logInWithApple(), ).thenAnswer((_) => Future<void>.value()); when( () => userRepository.sendLoginEmailLink( email: any(named: 'email'), ), ).thenAnswer((_) => Future<void>.value()); }); test('initial state is LoginState', () { expect(LoginBloc(userRepository: userRepository).state, LoginState()); }); group('EmailChanged', () { blocTest<LoginBloc, LoginState>( 'emits [invalid] when email is invalid', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginEmailChanged(invalidEmailString)), expect: () => const <LoginState>[ LoginState(email: invalidEmail), ], ); blocTest<LoginBloc, LoginState>( 'emits [valid] when email is valid', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginEmailChanged(validEmailString)), expect: () => const <LoginState>[ LoginState(email: validEmail, valid: true), ], ); }); group('SendEmailLinkSubmitted', () { blocTest<LoginBloc, LoginState>( 'does nothing when status is not validated', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(SendEmailLinkSubmitted()), expect: () => const <LoginState>[], ); blocTest<LoginBloc, LoginState>( 'calls sendLoginEmailLink with correct email', build: () => LoginBloc(userRepository: userRepository), seed: () => LoginState(email: validEmail, valid: true), act: (bloc) => bloc.add(SendEmailLinkSubmitted()), verify: (_) { verify( () => userRepository.sendLoginEmailLink( email: validEmailString, ), ).called(1); }, ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when sendLoginEmailLink succeeds', build: () => LoginBloc(userRepository: userRepository), seed: () => LoginState(email: validEmail, valid: true), act: (bloc) => bloc.add(SendEmailLinkSubmitted()), expect: () => const <LoginState>[ LoginState( status: FormzSubmissionStatus.inProgress, email: validEmail, valid: true, ), LoginState( status: FormzSubmissionStatus.success, email: validEmail, valid: true, ) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when sendLoginEmailLink fails', setUp: () { when( () => userRepository.sendLoginEmailLink( email: any(named: 'email'), ), ).thenThrow(Exception('oops')); }, build: () => LoginBloc(userRepository: userRepository), seed: () => LoginState(email: validEmail, valid: true), act: (bloc) => bloc.add(SendEmailLinkSubmitted()), expect: () => const <LoginState>[ LoginState( status: FormzSubmissionStatus.inProgress, email: validEmail, valid: true, ), LoginState( status: FormzSubmissionStatus.failure, email: validEmail, valid: true, ) ], ); }); group('LoginGoogleSubmitted', () { blocTest<LoginBloc, LoginState>( 'calls logInWithGoogle', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginGoogleSubmitted()), verify: (_) { verify(() => userRepository.logInWithGoogle()).called(1); }, ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithGoogle succeeds', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginGoogleSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.success) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithGoogle fails', setUp: () { when( () => userRepository.logInWithGoogle(), ).thenThrow(Exception('oops')); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginGoogleSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.failure) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionCanceled] ' 'when logInWithGoogle is canceled', setUp: () { when( () => userRepository.logInWithGoogle(), ).thenThrow(LogInWithGoogleCanceled(Exception())); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginGoogleSubmitted()), expect: () => <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.canceled), ], ); }); group('LoginTwitterSubmitted', () { blocTest<LoginBloc, LoginState>( 'calls logInWithTwitter', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginTwitterSubmitted()), verify: (_) { verify(() => userRepository.logInWithTwitter()).called(1); }, ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithTwitter succeeds', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginTwitterSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.success) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithTwitter fails', setUp: () { when( () => userRepository.logInWithTwitter(), ).thenThrow(Exception('oops')); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginTwitterSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.failure) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionCanceled] ' 'when logInWithTwitter is canceled', setUp: () { when( () => userRepository.logInWithTwitter(), ).thenThrow( LogInWithTwitterCanceled(Exception()), ); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginTwitterSubmitted()), expect: () => <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.canceled), ], ); }); group('LoginFacebookSubmitted', () { blocTest<LoginBloc, LoginState>( 'calls logInWithFacebook', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginFacebookSubmitted()), verify: (_) { verify(() => userRepository.logInWithFacebook()).called(1); }, ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithFacebook succeeds', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginFacebookSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.success) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithFacebook fails', setUp: () { when( () => userRepository.logInWithFacebook(), ).thenThrow(Exception('oops')); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginFacebookSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.failure) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionCanceled] ' 'when logInWithFacebook is canceled', setUp: () { when( () => userRepository.logInWithFacebook(), ).thenThrow( LogInWithFacebookCanceled(Exception()), ); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginFacebookSubmitted()), expect: () => <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.canceled), ], ); }); group('LogInWithAppleSubmitted', () { blocTest<LoginBloc, LoginState>( 'calls logInWithApple', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginAppleSubmitted()), verify: (_) { verify(() => userRepository.logInWithApple()).called(1); }, ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionSuccess] ' 'when logInWithApple succeeds', build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginAppleSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.success) ], ); blocTest<LoginBloc, LoginState>( 'emits [submissionInProgress, submissionFailure] ' 'when logInWithApple fails', setUp: () { when( () => userRepository.logInWithApple(), ).thenThrow(Exception('oops')); }, build: () => LoginBloc(userRepository: userRepository), act: (bloc) => bloc.add(LoginAppleSubmitted()), expect: () => const <LoginState>[ LoginState(status: FormzSubmissionStatus.inProgress), LoginState(status: FormzSubmissionStatus.failure) ], ); }); }); }
news_toolkit/flutter_news_example/test/login/bloc/login_bloc_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/login/bloc/login_bloc_test.dart", "repo_id": "news_toolkit", "token_count": 5201 }
990
// ignore_for_file: prefer_const_constructors import 'package:app_ui/app_ui.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_news_example/categories/categories.dart'; import 'package:flutter_news_example/navigation/navigation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:news_repository/news_repository.dart'; import '../../helpers/helpers.dart'; class MockCategoriesBloc extends MockBloc<CategoriesEvent, CategoriesState> implements CategoriesBloc {} void main() { group('NavDrawerSections', () { late CategoriesBloc categoriesBloc; const categories = [Category.top, Category.health]; final selectedCategory = categories.first; setUp(() { categoriesBloc = MockCategoriesBloc(); when(() => categoriesBloc.state).thenReturn( CategoriesState.initial().copyWith( categories: categories, selectedCategory: selectedCategory, ), ); }); testWidgets('renders NavDrawerSectionsTitle', (tester) async { await tester.pumpApp( BlocProvider.value( value: categoriesBloc, child: NavDrawerSections(), ), ); expect(find.byType(NavDrawerSectionsTitle), findsOneWidget); }); testWidgets( 'renders NavDrawerSectionItem ' 'for each category', (tester) async { await tester.pumpApp( BlocProvider.value( value: categoriesBloc, child: NavDrawerSections(), ), ); for (final category in categories) { expect( find.byWidgetPredicate( (widget) => widget is NavDrawerSectionItem && widget.key == ValueKey(category) && widget.selected == (category == selectedCategory), ), findsOneWidget, ); } }); group('NavDrawerSectionItem', () { testWidgets('renders ListTile with title', (tester) async { const title = 'title'; await tester.pumpApp( NavDrawerSectionItem( title: title, ), ); expect(find.widgetWithText(ListTile, title), findsOneWidget); }); testWidgets('calls onTap when tapped', (tester) async { var tapped = false; await tester.pumpApp( NavDrawerSectionItem( title: 'title', onTap: () => tapped = true, ), ); await tester.tap(find.byType(NavDrawerSectionItem)); expect(tapped, isTrue); }); testWidgets('has correct selected color', (tester) async { await tester.pumpApp( NavDrawerSectionItem( title: 'title', selected: true, onTap: () {}, ), ); final tile = tester.widget<ListTile>(find.byType(ListTile)); expect( tile.selectedTileColor, equals(AppColors.white.withOpacity(0.08)), ); expect( (tile.title! as Text).style?.color, equals(AppColors.highEmphasisPrimary), ); }); }); }); }
news_toolkit/flutter_news_example/test/navigation/widgets/nav_drawer_sections_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/navigation/widgets/nav_drawer_sections_test.dart", "repo_id": "news_toolkit", "token_count": 1449 }
991
// ignore_for_file: prefer_const_constructors import 'dart:async'; 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/onboarding/onboarding.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {} class MockOnboardingBloc extends MockBloc<OnboardingEvent, OnboardingState> implements OnboardingBloc {} void main() { late AppBloc appBloc; late OnboardingBloc onboardingBloc; const onboardingViewTitleKey = Key('onboardingView_onboardingTitle'); const onboardingViewSubtitleKey = Key('onboardingView_onboardingSubtitle'); const onboardingViewPageTwoKey = Key('onboarding_pageTwo'); const onboardingViewPageOnePrimaryButtonKey = Key('onboardingItem_primaryButton_pageOne'); const onboardingViewPageOneSecondaryButtonKey = Key('onboardingItem_secondaryButton_pageOne'); const onboardingViewPageTwoPrimaryButtonKey = Key('onboardingItem_primaryButton_pageTwo'); const onboardingViewPageTwoSecondaryButtonKey = Key('onboardingItem_secondaryButton_pageTwo'); setUp(() { appBloc = MockAppBloc(); onboardingBloc = MockOnboardingBloc(); whenListen( onboardingBloc, Stream<OnboardingState>.empty(), initialState: OnboardingInitial(), ); }); group('renders', () { testWidgets('Onboarding title', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); expect(find.byKey(onboardingViewTitleKey), findsOneWidget); }); testWidgets('Onboarding subtitle', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); expect(find.byKey(onboardingViewSubtitleKey), findsOneWidget); }); testWidgets('Onboarding PageView', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); expect(find.byType(PageView), findsOneWidget); }); }); group('navigates', () { testWidgets('to onboarding page two when button page one is tapped', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); final button = find.byKey(onboardingViewPageOneSecondaryButtonKey); await tester.dragUntilVisible( button, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(button); await tester.pumpAndSettle(); expect(find.byKey(onboardingViewPageTwoKey), findsOneWidget); }); testWidgets( 'to onboarding page two ' 'when state is EnablingAdTrackingSucceeded', (tester) async { whenListen( onboardingBloc, Stream.fromIterable([ OnboardingInitial(), EnablingAdTrackingSucceeded(), ]), initialState: OnboardingInitial(), ); await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); await tester.pumpAndSettle(); expect(find.byKey(onboardingViewPageTwoKey), findsOneWidget); }); testWidgets( 'to onboarding page two ' 'when state is EnablingAdTrackingFailed', (tester) async { whenListen( onboardingBloc, Stream.fromIterable([ OnboardingInitial(), EnablingAdTrackingFailed(), ]), initialState: OnboardingInitial(), ); await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); await tester.pumpAndSettle(); expect(find.byKey(onboardingViewPageTwoKey), findsOneWidget); }); testWidgets('to home when onboarding is complete', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), appBloc: appBloc, ); final buttonOne = find.byKey(onboardingViewPageOneSecondaryButtonKey); await tester.dragUntilVisible( buttonOne, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(buttonOne); await tester.pumpAndSettle(); final buttonTwo = find.byKey(onboardingViewPageTwoSecondaryButtonKey); await tester.dragUntilVisible( buttonTwo, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(buttonTwo); verify(() => appBloc.add(AppOnboardingCompleted())).called(1); }); }); testWidgets( 'adds EnableNotificationsRequested to OnboardingBloc ' 'when subscribe to notifications now button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); final buttonOne = find.byKey(onboardingViewPageOneSecondaryButtonKey); await tester.dragUntilVisible( buttonOne, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(buttonOne); await tester.pumpAndSettle(); expect(find.byKey(onboardingViewPageTwoKey), findsOneWidget); final button = find.byKey(onboardingViewPageTwoPrimaryButtonKey); await tester.dragUntilVisible( button, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(button); await tester.pumpAndSettle(); expect( find.byKey(onboardingViewPageTwoPrimaryButtonKey), findsOneWidget, ); verify(() => onboardingBloc.add(EnableNotificationsRequested())).called(1); }); testWidgets( 'adds AppOnboardingCompleted to AppBloc ' 'when OnboardingState is EnablingNotificationsSucceeded', (tester) async { final onboardingStateController = StreamController<OnboardingState>(); whenListen( onboardingBloc, onboardingStateController.stream, initialState: OnboardingInitial(), ); await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), appBloc: appBloc, ); verifyNever(() => appBloc.add(AppOnboardingCompleted())); onboardingStateController.add(EnablingNotificationsSucceeded()); await tester.pump(); verify(() => appBloc.add(AppOnboardingCompleted())).called(1); }); group('does nothing', () { testWidgets('when personalized my ads button is pressed', (tester) async { await tester.pumpApp( BlocProvider.value( value: onboardingBloc, child: OnboardingView(), ), ); final button = find.byKey(onboardingViewPageOnePrimaryButtonKey); await tester.dragUntilVisible( button, find.byType(OnboardingView), Offset(0, -100), duration: Duration.zero, ); await tester.pumpAndSettle(); await tester.tap(button); await tester.pumpAndSettle(); expect( find.byKey(onboardingViewPageOnePrimaryButtonKey), findsOneWidget, ); }); }); }
news_toolkit/flutter_news_example/test/onboarding/view/onboarding_view_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/onboarding/view/onboarding_view_test.dart", "repo_id": "news_toolkit", "token_count": 3248 }
992
// 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/ads/ads.dart'; import 'package:flutter_news_example/analytics/analytics.dart'; import 'package:flutter_news_example/app/app.dart'; import 'package:flutter_news_example/article/article.dart'; import 'package:flutter_news_example/login/login.dart'; import 'package:flutter_news_example/subscriptions/subscriptions.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart' as ads; import 'package:in_app_purchase_repository/in_app_purchase_repository.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:user_repository/user_repository.dart'; import 'package:visibility_detector/visibility_detector.dart'; import '../../helpers/helpers.dart'; class MockAppBloc extends MockBloc<AppEvent, AppState> implements AppBloc {} class MockArticleBloc extends MockBloc<ArticleEvent, ArticleState> implements ArticleBloc {} class MockUser extends Mock implements User {} class MockAdWithoutView extends Mock implements ads.AdWithoutView {} class MockRewardItem extends Mock implements ads.RewardItem {} class MockAnalyticsBloc extends MockBloc<AnalyticsEvent, AnalyticsState> implements AnalyticsBloc {} class MockFullScreenAdsBloc extends MockBloc<FullScreenAdsEvent, FullScreenAdsState> implements FullScreenAdsBloc {} void main() { late AppBloc appBloc; late User user; late AnalyticsBloc analyticsBloc; late ArticleBloc articleBloc; const subscribeButtonKey = Key('subscribeWithArticleLimitModal_subscribeButton'); const logInButtonKey = Key('subscribeWithArticleLimitModal_logInButton'); const watchVideoButton = Key('subscribeWithArticleLimitModal_watchVideoButton'); setUp(() { user = MockUser(); appBloc = MockAppBloc(); analyticsBloc = MockAnalyticsBloc(); articleBloc = MockArticleBloc(); when(() => appBloc.state).thenReturn(AppState.unauthenticated()); when(() => articleBloc.state).thenReturn( ArticleState(status: ArticleStatus.initial, title: 'title'), ); VisibilityDetectorController.instance.updateInterval = Duration.zero; }); group('SubscribeWithArticleLimitModal', () { group('renders', () { testWidgets( 'subscribe and watch video buttons ' 'when user is authenticated', (tester) async { when(() => appBloc.state).thenReturn(AppState.authenticated(user)); await tester.pumpApp( analyticsBloc: analyticsBloc, appBloc: appBloc, BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), ); expect(find.byKey(subscribeButtonKey), findsOneWidget); expect(find.byKey(watchVideoButton), findsOneWidget); expect(find.byKey(logInButtonKey), findsNothing); }); testWidgets( 'subscribe log in and watch video buttons ' 'when user is unauthenticated', (tester) async { when(() => appBloc.state).thenReturn(AppState.unauthenticated()); await tester.pumpApp( analyticsBloc: analyticsBloc, appBloc: appBloc, BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), ); expect(find.byKey(subscribeButtonKey), findsOneWidget); expect(find.byKey(logInButtonKey), findsOneWidget); expect(find.byKey(watchVideoButton), findsOneWidget); }); }); group('opens PurchaseSubscriptionDialog', () { late InAppPurchaseRepository inAppPurchaseRepository; late AnalyticsBloc analyticsBloc; setUp(() { inAppPurchaseRepository = MockInAppPurchaseRepository(); analyticsBloc = MockAnalyticsBloc(); when(() => inAppPurchaseRepository.purchaseUpdate).thenAnswer( (_) => const Stream.empty(), ); when(inAppPurchaseRepository.fetchSubscriptions).thenAnswer( (_) async => [], ); when(() => articleBloc.state).thenReturn( ArticleState(status: ArticleStatus.initial, title: 'title'), ); }); testWidgets( 'when tapped on subscribe button ' 'adding PaywallPromptEvent.click to AnalyticsBloc', (tester) async { await tester.pumpApp( analyticsBloc: analyticsBloc, appBloc: appBloc, inAppPurchaseRepository: inAppPurchaseRepository, BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), ); await tester.tap(find.byKey(subscribeButtonKey)); await tester.pump(); expect(find.byType(PurchaseSubscriptionDialog), findsOneWidget); verify( () => analyticsBloc.add( TrackAnalyticsEvent( PaywallPromptEvent.click( articleTitle: 'title', ), ), ), ).called(1); }); }); testWidgets( 'shows LoginModal ' 'when tapped on log in button', (tester) async { whenListen( appBloc, Stream.value(AppState.unauthenticated()), initialState: AppState.unauthenticated(), ); await tester.pumpApp( analyticsBloc: analyticsBloc, appBloc: appBloc, BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), ); await tester.tap(find.byKey(logInButtonKey)); await tester.pumpAndSettle(); expect(find.byType(LoginModal), findsOneWidget); }); testWidgets( 'adds ShowRewardedAdRequested to FullScreenAdsBloc ' 'when tapped on watch video button', (tester) async { final fullScreenAdsBloc = MockFullScreenAdsBloc(); await tester.pumpApp( analyticsBloc: analyticsBloc, appBloc: appBloc, fullScreenAdsBloc: fullScreenAdsBloc, BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), ); await tester.tap(find.byKey(watchVideoButton)); await tester.pump(); verify(() => fullScreenAdsBloc.add(ShowRewardedAdRequested())).called(1); }); testWidgets( 'adds TrackAnalyticsEvent to AnalyticsBloc ' 'with PaywallPromptEvent.impression rewarded ' 'when shown', (tester) async { await tester.pumpApp( BlocProvider.value( value: articleBloc, child: SubscribeWithArticleLimitModal(), ), analyticsBloc: analyticsBloc, appBloc: appBloc, ); verify( () => analyticsBloc.add( TrackAnalyticsEvent( PaywallPromptEvent.impression( articleTitle: 'title', impression: PaywallPromptImpression.rewarded, ), ), ), ).called(1); }); }); }
news_toolkit/flutter_news_example/test/subscriptions/widgets/subscribe_with_article_limit_modal_test.dart/0
{ "file_path": "news_toolkit/flutter_news_example/test/subscriptions/widgets/subscribe_with_article_limit_modal_test.dart", "repo_id": "news_toolkit", "token_count": 2944 }
993
name: generator description: A template generator for Flutter News Example. publish_to: none environment: sdk: ">=2.18.0 <3.0.0" dependencies: path: ^1.8.2
news_toolkit/tool/generator/pubspec.yaml/0
{ "file_path": "news_toolkit/tool/generator/pubspec.yaml", "repo_id": "news_toolkit", "token_count": 62 }
994
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.all_packages"> <uses-permission android:name="android.permission.INTERNET"/> </manifest>
packages/.ci/legacy_project/all_packages/android/app/src/debug/AndroidManifest.xml/0
{ "file_path": "packages/.ci/legacy_project/all_packages/android/app/src/debug/AndroidManifest.xml", "repo_id": "packages", "token_count": 66 }
995
# Same as android_platform_tests.yaml with only packages currently requiring # Android 33 due to test failures caused by running on Android 34 AVDs. tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: download Dart and Android deps script: .ci/scripts/tool_runner.sh infra_step: true args: ["fetch-deps", "--android", "--supporting-target-platforms-only", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"] - name: build examples script: .ci/scripts/tool_runner.sh args: ["build-examples", "--apk", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"] - name: lint script: .ci/scripts/tool_runner.sh args: ["lint-android", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"] # Native unit and native integration are split into two steps to allow for # different exclusions. # TODO(stuartmorgan): Eliminate the native unit test exclusion, and combine # these steps. - name: native unit tests script: .ci/scripts/tool_runner.sh args: ["native-test", "--android", "--no-integration", "--exclude=script/configs/exclude_native_unit_android.yaml", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"] - name: native integration tests script: .ci/scripts/tool_runner.sh args: ["native-test", "--android", "--no-unit", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"] - name: drive examples script: .ci/scripts/tool_runner.sh args: ["drive-examples", "--android", "--exclude=script/configs/exclude_integration_android.yaml,script/configs/exclude_integration_android_emulator.yaml", "--filter-packages-to=script/configs/still_requires_api_33_avd.yaml"]
packages/.ci/targets/android_platform_tests_api_33_avd.yaml/0
{ "file_path": "packages/.ci/targets/android_platform_tests_api_33_avd.yaml", "repo_id": "packages", "token_count": 631 }
996
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: create all_packages app script: .ci/scripts/create_all_packages_app.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: build all_packages app for Windows debug script: .ci/scripts/build_all_packages_app.sh args: ["windows", "debug"] - name: build all_packages app for Windows release script: .ci/scripts/build_all_packages_app.sh args: ["windows", "release"]
packages/.ci/targets/windows_build_all_packages.yaml/0
{ "file_path": "packages/.ci/targets/windows_build_all_packages.yaml", "repo_id": "packages", "token_count": 194 }
997
#!/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. # This file is used by # https://github.com/flutter/tests/tree/master/registry/flutter_packages.test # to run the tests of certain packages in this repository as a presubmit # for the flutter/flutter repository. # Changes to this file (and any tests in this repository) are only honored # after the commit hash in the "flutter_packages.test" mentioned above has been # updated. # Remember to also update the Windows version (customer_testing.bat) when # changing this file. set -e # ANIMATIONS PACKAGE pushd packages/animations flutter analyze --no-fatal-infos flutter test popd # RFW PACKAGE pushd packages/rfw # Update the subpackages so that the analysis doesn't get confused. pushd example/remote; flutter packages get; popd pushd example/wasm; flutter packages get; popd pushd test_coverage; dart pub get; popd flutter analyze --no-fatal-infos if [[ "$OSTYPE" == "linux-gnu" ]]; then # We only run the full tests on Linux because golden files differ # from platform to platform. flutter test fi # The next script verifies that the coverage is not regressed; it does # not verify goldens. (It does run all the tests though, so it still # catches logic issues on other platforms, just not issue that only # affect golden files.) ./run_tests.sh popd
packages/customer_testing.sh/0
{ "file_path": "packages/customer_testing.sh", "repo_id": "packages", "token_count": 420 }
998
# camera\_android The Android implementation of [`camera`][1]. *Note*: [`camera_android_camerax`][3] will become the default implementation of `camera` on Android by May 2024, so **we strongly encourage you to opt into it** by using [these instructions][4]. If any [limitations][5] of `camera_android_camerax` prevent you from using it or if you run into any problems, please report these issues under [`flutter/flutter`][5] with `[camerax]` in the title. ## Usage This package is [endorsed][2], which means you can simply use `camera` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. [1]: https://pub.dev/packages/camera [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://pub.dev/packages/camera_android_camerax [4]: https://pub.dev/packages/camera_android_camerax#usage [5]: https://pub.dev/packages/camera_android_camerax#limitations
packages/packages/camera/camera_android/README.md/0
{ "file_path": "packages/packages/camera/camera_android/README.md", "repo_id": "packages", "token_count": 342 }
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. package io.flutter.plugins.camera; import android.media.Image; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; /** Saves a JPEG {@link Image} into the specified {@link File}. */ public class ImageSaver implements Runnable { /** The JPEG image */ private final Image image; /** The file we save the image into. */ private final File file; /** Used to report the status of the save action. */ private final Callback callback; /** * Creates an instance of the ImageSaver runnable * * @param image - The image to save * @param file - The file to save the image to * @param callback - The callback that is run on completion, or when an error is encountered. */ ImageSaver(@NonNull Image image, @NonNull File file, @NonNull Callback callback) { this.image = image; this.file = file; this.callback = callback; } @Override public void run() { ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); FileOutputStream output = null; try { output = FileOutputStreamFactory.create(file); output.write(bytes); callback.onComplete(file.getAbsolutePath()); } catch (IOException e) { callback.onError("IOError", "Failed saving image"); } finally { image.close(); if (null != output) { try { output.close(); } catch (IOException e) { callback.onError("cameraAccess", e.getMessage()); } } } } /** * The interface for the callback that is passed to ImageSaver, for detecting completion or * failure of the image saving task. */ public interface Callback { /** * Called when the image file has been saved successfully. * * @param absolutePath - The absolute path of the file that was saved. */ void onComplete(@NonNull String absolutePath); /** * Called when an error is encountered while saving the image file. * * @param errorCode - The error code. * @param errorMessage - The human readable error message. */ void onError(@NonNull String errorCode, @NonNull String errorMessage); } /** Factory class that assists in creating a {@link FileOutputStream} instance. */ static class FileOutputStreamFactory { /** * Creates a new instance of the {@link FileOutputStream} class. * * <p>This method is visible for testing purposes only and should never be used outside this * * class. * * @param file - The file to create the output stream for * @return new instance of the {@link FileOutputStream} class. * @throws FileNotFoundException when the supplied file could not be found. */ @VisibleForTesting public static FileOutputStream create(File file) throws FileNotFoundException { return new FileOutputStream(file); } } }
packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/ImageSaver.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/ImageSaver.java", "repo_id": "packages", "token_count": 1056 }
1,000
// 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 exposure_mode.dart public enum ExposureMode { auto("auto"), locked("locked"); private final String strValue; ExposureMode(String strValue) { this.strValue = strValue; } @Nullable public static ExposureMode getValueForString(@NonNull String modeStr) { for (ExposureMode 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/ExposureMode.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/ExposureMode.java", "repo_id": "packages", "token_count": 240 }
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. package io.flutter.plugins.camera; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.app.Activity; import android.hardware.camera2.CameraAccessException; import androidx.lifecycle.LifecycleObserver; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.camera.utils.TestUtils; import io.flutter.view.TextureRegistry; import org.junit.Before; import org.junit.Test; public class MethodCallHandlerImplTest { MethodChannel.MethodCallHandler handler; MethodChannel.Result mockResult; Camera mockCamera; @Before public void setUp() { handler = new MethodCallHandlerImpl( mock(Activity.class), mock(BinaryMessenger.class), mock(CameraPermissions.class), mock(CameraPermissions.PermissionsRegistry.class), mock(TextureRegistry.class)); mockResult = mock(MethodChannel.Result.class); mockCamera = mock(Camera.class); TestUtils.setPrivateField(handler, "camera", mockCamera); } @Test public void shouldNotImplementLifecycleObserverInterface() { Class<MethodCallHandlerImpl> methodCallHandlerClass = MethodCallHandlerImpl.class; assertFalse(LifecycleObserver.class.isAssignableFrom(methodCallHandlerClass)); } @Test public void onMethodCall_pausePreview_shouldPausePreviewAndSendSuccessResult() throws CameraAccessException { handler.onMethodCall(new MethodCall("pausePreview", null), mockResult); verify(mockCamera, times(1)).pausePreview(); verify(mockResult, times(1)).success(null); } @Test public void onMethodCall_pausePreview_shouldSendErrorResultOnCameraAccessException() throws CameraAccessException { doThrow(new CameraAccessException(0)).when(mockCamera).pausePreview(); handler.onMethodCall(new MethodCall("pausePreview", null), mockResult); verify(mockResult, times(1)).error("CameraAccess", null, null); } @Test public void onMethodCall_resumePreview_shouldResumePreviewAndSendSuccessResult() { handler.onMethodCall(new MethodCall("resumePreview", null), mockResult); verify(mockCamera, times(1)).resumePreview(); verify(mockResult, times(1)).success(null); } }
packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/MethodCallHandlerImplTest.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/MethodCallHandlerImplTest.java", "repo_id": "packages", "token_count": 845 }
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. package io.flutter.plugins.camera.features.zoomlevel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import android.graphics.Rect; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ZoomUtilsTest { @Test public void setZoomRect_whenSensorSizeEqualsZeroShouldReturnCropRegionOfZero() { final Rect sensorSize = new Rect(0, 0, 0, 0); final Rect computedZoom = ZoomUtils.computeZoomRect(18f, sensorSize, 1f, 20f); assertNotNull(computedZoom); assertEquals(computedZoom.left, 0); assertEquals(computedZoom.top, 0); assertEquals(computedZoom.right, 0); assertEquals(computedZoom.bottom, 0); } @Test public void setZoomRect_whenSensorSizeIsValidShouldReturnCropRegion() { final Rect sensorSize = new Rect(0, 0, 100, 100); final Rect computedZoom = ZoomUtils.computeZoomRect(18f, sensorSize, 1f, 20f); assertNotNull(computedZoom); assertEquals(computedZoom.left, 48); assertEquals(computedZoom.top, 48); assertEquals(computedZoom.right, 52); assertEquals(computedZoom.bottom, 52); } @Test public void setZoomRect_whenZoomIsGreaterThenMaxZoomClampToMaxZoom() { final Rect sensorSize = new Rect(0, 0, 100, 100); final Rect computedZoom = ZoomUtils.computeZoomRect(25f, sensorSize, 1f, 10f); assertNotNull(computedZoom); assertEquals(computedZoom.left, 45); assertEquals(computedZoom.top, 45); assertEquals(computedZoom.right, 55); assertEquals(computedZoom.bottom, 55); } @Test public void setZoomRect_whenZoomIsSmallerThenMinZoomClampToMinZoom() { final Rect sensorSize = new Rect(0, 0, 100, 100); final Rect computedZoom = ZoomUtils.computeZoomRect(0.5f, sensorSize, 1f, 10f); assertNotNull(computedZoom); assertEquals(computedZoom.left, 0); assertEquals(computedZoom.top, 0); assertEquals(computedZoom.right, 100); assertEquals(computedZoom.bottom, 100); } @Test public void setZoomRatio_whenNewZoomGreaterThanMaxZoomClampToMaxZoom() { final Float computedZoom = ZoomUtils.computeZoomRatio(21f, 1f, 20f); assertNotNull(computedZoom); assertEquals(computedZoom, 20f, 0.0f); } @Test public void setZoomRatio_whenNewZoomLesserThanMinZoomClampToMinZoom() { final Float computedZoom = ZoomUtils.computeZoomRatio(0.7f, 1f, 20f); assertNotNull(computedZoom); assertEquals(computedZoom, 1f, 0.0f); } @Test public void setZoomRatio_whenNewZoomValidReturnNewZoom() { final Float computedZoom = ZoomUtils.computeZoomRatio(2.0f, 1f, 20f); assertNotNull(computedZoom); assertEquals(computedZoom, 2.0f, 0.0f); } }
packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/zoomlevel/ZoomUtilsTest.java/0
{ "file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/zoomlevel/ZoomUtilsTest.java", "repo_id": "packages", "token_count": 1121 }
1,003
rootProject.name = 'camera_android_camerax'
packages/packages/camera/camera_android_camerax/android/settings.gradle/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/settings.gradle", "repo_id": "packages", "token_count": 15 }
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. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.CameraState; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateErrorFlutterApi; /** * Flutter API implementation for {@link CameraStateError}. * * <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 CameraStateErrorFlutterApiWrapper { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private CameraStateErrorFlutterApi cameraStateErrorFlutterApi; /** * Constructs a {@link CameraStateErrorFlutterApiWrapper}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public CameraStateErrorFlutterApiWrapper( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; cameraStateErrorFlutterApi = new CameraStateErrorFlutterApi(binaryMessenger); } /** * Stores the {@link CameraStateError} instance and notifies Dart to create and store a new {@link * CameraStateError} instance that is attached to this one. If {@code instance} has already been * added, this method does nothing. */ public void create( @NonNull CameraState.StateError instance, @NonNull Long code, @NonNull CameraStateErrorFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { cameraStateErrorFlutterApi.create( instanceManager.addHostCreatedInstance(instance), code, callback); } } /** Sets the Flutter API used to send messages to Dart. */ @VisibleForTesting void setApi(@NonNull CameraStateErrorFlutterApi api) { this.cameraStateErrorFlutterApi = api; } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java", "repo_id": "packages", "token_count": 656 }
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. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.camera.core.ImageProxy; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyHostApi; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Host API implementation for {@link ImageProxy}. * * <p>This class may handle instantiating and adding native object instances that are attached to a * Dart instance or handle method calls on the associated native class or an instance of the class. */ public class ImageProxyHostApiImpl implements ImageProxyHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; @VisibleForTesting @NonNull public CameraXProxy cameraXProxy = new CameraXProxy(); @VisibleForTesting @NonNull public PlaneProxyFlutterApiImpl planeProxyFlutterApiImpl; /** * Constructs a {@link ImageProxyHostApiImpl}. * * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public ImageProxyHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; planeProxyFlutterApiImpl = new PlaneProxyFlutterApiImpl(binaryMessenger, instanceManager); } /** * Returns the array of identifiers for planes of the {@link ImageProxy} instance with the * specified identifier. */ @Override @NonNull public List<Long> getPlanes(@NonNull Long identifier) { ImageProxy.PlaneProxy[] planes = getImageProxyInstance(identifier).getPlanes(); List<Long> planeIdentifiers = new ArrayList<Long>(); for (ImageProxy.PlaneProxy plane : planes) { ByteBuffer byteBuffer = plane.getBuffer(); byte[] bytes = cameraXProxy.getBytesFromBuffer(byteBuffer.remaining()); byteBuffer.get(bytes, 0, bytes.length); Long pixelStride = Long.valueOf(plane.getPixelStride()); Long rowStride = Long.valueOf(plane.getRowStride()); planeProxyFlutterApiImpl.create(plane, bytes, pixelStride, rowStride, reply -> {}); planeIdentifiers.add(instanceManager.getIdentifierForStrongReference(plane)); } return planeIdentifiers; } /** * Closes the {@link androidx.camera.core.Image} instance associated with the {@link ImageProxy} * instance with the specified identifier. */ @Override public void close(@NonNull Long identifier) { getImageProxyInstance(identifier).close(); } /** * Retrieives the {@link ImageProxy} instance associated with the specified {@code identifier}. */ private ImageProxy getImageProxyInstance(@NonNull Long identifier) { return Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java", "repo_id": "packages", "token_count": 909 }
1,006
// 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.camera.video.Recorder; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecorderFlutterApi; public class RecorderFlutterApiImpl extends RecorderFlutterApi { private final InstanceManager instanceManager; public RecorderFlutterApiImpl( @Nullable BinaryMessenger binaryMessenger, @Nullable InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } void create( @NonNull Recorder recorder, @Nullable Long aspectRatio, @Nullable Long bitRate, @Nullable Reply<Void> reply) { create(instanceManager.addHostCreatedInstance(recorder), aspectRatio, bitRate, reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java", "repo_id": "packages", "token_count": 316 }
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 io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraState; import androidx.camera.core.ExposureState; import androidx.camera.core.ZoomState; import androidx.lifecycle.LiveData; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class CameraInfoTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public CameraInfo mockCameraInfo; @Mock public BinaryMessenger mockBinaryMessenger; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { testInstanceManager.stopFinalizationListener(); } @Test public void getSensorRotationDegrees_makesCallToRetrieveSensorRotationDegrees() { final CameraInfoHostApiImpl cameraInfoHostApi = new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); testInstanceManager.addDartCreatedInstance(mockCameraInfo, 1); when(mockCameraInfo.getSensorRotationDegrees()).thenReturn(90); assertEquals((long) cameraInfoHostApi.getSensorRotationDegrees(1L), 90L); verify(mockCameraInfo).getSensorRotationDegrees(); } @Test public void getCameraState_makesCallToRetrieveLiveCameraState() { final CameraInfoHostApiImpl cameraInfoHostApiImpl = new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); final LiveDataFlutterApiWrapper mockLiveDataFlutterApiWrapper = mock(LiveDataFlutterApiWrapper.class); final Long mockCameraInfoIdentifier = 27L; @SuppressWarnings("unchecked") final LiveData<CameraState> mockLiveCameraState = (LiveData<CameraState>) mock(LiveData.class); testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); cameraInfoHostApiImpl.liveDataFlutterApiWrapper = mockLiveDataFlutterApiWrapper; when(mockCameraInfo.getCameraState()).thenReturn(mockLiveCameraState); final Long liveCameraStateIdentifier = cameraInfoHostApiImpl.getCameraState(mockCameraInfoIdentifier); verify(mockLiveDataFlutterApiWrapper) .create(eq(mockLiveCameraState), eq(LiveDataSupportedType.CAMERA_STATE), any()); assertEquals( liveCameraStateIdentifier, testInstanceManager.getIdentifierForStrongReference(mockLiveCameraState)); } @Test public void getExposureState_retrievesExpectedExposureState() { final CameraInfoHostApiImpl cameraInfoHostApiImpl = new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); final ExposureState mockExposureState = mock(ExposureState.class); final Long mockCameraInfoIdentifier = 27L; final Long mockExposureStateIdentifier = 47L; testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); testInstanceManager.addDartCreatedInstance(mockExposureState, mockExposureStateIdentifier); when(mockCameraInfo.getExposureState()).thenReturn(mockExposureState); assertEquals( cameraInfoHostApiImpl.getExposureState(mockCameraInfoIdentifier), mockExposureStateIdentifier); verify(mockCameraInfo).getExposureState(); } @Test @SuppressWarnings("unchecked") public void getZoomState_retrievesExpectedZoomState() { final CameraInfoHostApiImpl cameraInfoHostApiImpl = new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); final LiveData<ZoomState> mockLiveZoomState = (LiveData<ZoomState>) mock(LiveData.class); final ZoomState mockZoomState = mock(ZoomState.class); final Long mockCameraInfoIdentifier = 20L; final Long mockLiveZoomStateIdentifier = 74L; testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); testInstanceManager.addDartCreatedInstance(mockLiveZoomState, mockLiveZoomStateIdentifier); when(mockCameraInfo.getZoomState()).thenReturn(mockLiveZoomState); assertEquals( cameraInfoHostApiImpl.getZoomState(mockCameraInfoIdentifier), mockLiveZoomStateIdentifier); verify(mockCameraInfo).getZoomState(); } @Test public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { final CameraInfoFlutterApiImpl spyFlutterApi = spy(new CameraInfoFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); spyFlutterApi.create(mockCameraInfo, reply -> {}); final long identifier = Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockCameraInfo)); verify(spyFlutterApi).create(eq(identifier), any()); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java", "repo_id": "packages", "token_count": 1775 }
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 io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; public class InstanceManagerTest { @Test public void addDartCreatedInstance() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); final Object object = new Object(); instanceManager.addDartCreatedInstance(object, 0); assertEquals(object, instanceManager.getInstance(0)); assertEquals((Long) 0L, instanceManager.getIdentifierForStrongReference(object)); assertTrue(instanceManager.containsInstance(object)); instanceManager.stopFinalizationListener(); } @Test public void addHostCreatedInstance() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); final Object object = new Object(); long identifier = instanceManager.addHostCreatedInstance(object); assertNotNull(instanceManager.getInstance(identifier)); assertEquals(object, instanceManager.getInstance(identifier)); assertTrue(instanceManager.containsInstance(object)); instanceManager.stopFinalizationListener(); } @Test public void removeReturnsRemovedObjectAndClearsIdentifier() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); Object object = new Object(); instanceManager.addDartCreatedInstance(object, 0); assertEquals(object, instanceManager.remove(0)); // To allow for object to be garbage collected. //noinspection UnusedAssignment object = null; Runtime.getRuntime().gc(); assertNull(instanceManager.getInstance(0)); instanceManager.stopFinalizationListener(); } @Test public void clear() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); final Object instance = new Object(); instanceManager.addDartCreatedInstance(instance, 0); assertTrue(instanceManager.containsInstance(instance)); instanceManager.clear(); assertFalse(instanceManager.containsInstance(instance)); instanceManager.stopFinalizationListener(); } @Test public void canAddSameObjectWithAddDartCreatedInstance() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); final Object instance = new Object(); instanceManager.addDartCreatedInstance(instance, 0); instanceManager.addDartCreatedInstance(instance, 1); assertTrue(instanceManager.containsInstance(instance)); assertEquals(instanceManager.getInstance(0), instance); assertEquals(instanceManager.getInstance(1), instance); instanceManager.stopFinalizationListener(); } @Test(expected = IllegalArgumentException.class) public void cannotAddSameObjectsWithAddHostCreatedInstance() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); final Object instance = new Object(); instanceManager.addHostCreatedInstance(instance); instanceManager.addHostCreatedInstance(instance); instanceManager.stopFinalizationListener(); } @Test(expected = IllegalArgumentException.class) public void cannotUseIdentifierLessThanZero() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); instanceManager.addDartCreatedInstance(new Object(), -1); instanceManager.stopFinalizationListener(); } @Test(expected = IllegalArgumentException.class) public void identifiersMustBeUnique() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); instanceManager.addDartCreatedInstance(new Object(), 0); instanceManager.addDartCreatedInstance(new Object(), 0); instanceManager.stopFinalizationListener(); } @Test public void managerIsUsableWhileListenerHasStopped() { final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); instanceManager.stopFinalizationListener(); final Object instance = new Object(); final long identifier = 0; instanceManager.addDartCreatedInstance(instance, identifier); assertEquals(instanceManager.getInstance(identifier), instance); assertEquals(instanceManager.getIdentifierForStrongReference(instance), (Long) identifier); assertTrue(instanceManager.containsInstance(instance)); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java", "repo_id": "packages", "token_count": 1291 }
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 io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import android.view.Surface; import androidx.camera.video.Recorder; import androidx.camera.video.VideoCapture; import io.flutter.plugin.common.BinaryMessenger; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class VideoCaptureTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public BinaryMessenger mockBinaryMessenger; @Mock public Recorder mockRecorder; @Mock public VideoCaptureFlutterApiImpl mockVideoCaptureFlutterApi; @Mock public VideoCapture<Recorder> mockVideoCapture; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = spy(InstanceManager.create(identifier -> {})); } @After public void tearDown() { testInstanceManager.stopFinalizationListener(); } @Test public void getOutput_returnsAssociatedRecorder() { final Long recorderId = 5L; final Long videoCaptureId = 6L; VideoCapture<Recorder> videoCapture = VideoCapture.withOutput(mockRecorder); testInstanceManager.addDartCreatedInstance(mockRecorder, recorderId); testInstanceManager.addDartCreatedInstance(videoCapture, videoCaptureId); VideoCaptureHostApiImpl videoCaptureHostApi = new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); assertEquals(videoCaptureHostApi.getOutput(videoCaptureId), recorderId); testInstanceManager.remove(recorderId); testInstanceManager.remove(videoCaptureId); } @Test @SuppressWarnings("unchecked") public void withOutput_returnsNewVideoCaptureWithAssociatedRecorder() { final Long recorderId = 5L; testInstanceManager.addDartCreatedInstance(mockRecorder, recorderId); VideoCaptureHostApiImpl videoCaptureHostApi = new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); VideoCaptureHostApiImpl spyVideoCaptureApi = spy(videoCaptureHostApi); final Long videoCaptureId = videoCaptureHostApi.withOutput(recorderId); VideoCapture<Recorder> videoCapture = testInstanceManager.getInstance(videoCaptureId); assertEquals(videoCapture.getOutput(), mockRecorder); testInstanceManager.remove(recorderId); testInstanceManager.remove(videoCaptureId); } @Test public void setTargetRotation_makesCallToSetTargetRotation() { final VideoCaptureHostApiImpl hostApi = new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); final long instanceIdentifier = 62; final int targetRotation = Surface.ROTATION_270; testInstanceManager.addDartCreatedInstance(mockVideoCapture, instanceIdentifier); hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); verify(mockVideoCapture).setTargetRotation(targetRotation); } @Test public void flutterApiCreateTest() { final VideoCaptureFlutterApiImpl spyVideoCaptureFlutterApi = spy(new VideoCaptureFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); spyVideoCaptureFlutterApi.create(mockVideoCapture, reply -> {}); final long identifier = Objects.requireNonNull( testInstanceManager.getIdentifierForStrongReference(mockVideoCapture)); verify(spyVideoCaptureFlutterApi).create(eq(identifier), any()); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java", "repo_id": "packages", "token_count": 1252 }
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. import 'dart:async'; import 'package:camera_platform_interface/camera_platform_interface.dart' show DeviceOrientationChangedEvent; import 'package:flutter/services.dart'; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camerax_library.g.dart'; // Ignoring lint indicating this class only contains static members // as this class is a wrapper for various Android system services. // ignore_for_file: avoid_classes_with_only_static_members /// Utility class that offers access to Android system services needed for /// camera usage and other informational streams. class DeviceOrientationManager { /// Stream that emits the device orientation whenever it is changed. /// /// Values may start being added to the stream once /// `startListeningForDeviceOrientationChange(...)` is called. static final StreamController<DeviceOrientationChangedEvent> deviceOrientationChangedStreamController = StreamController<DeviceOrientationChangedEvent>.broadcast(); /// Requests that [deviceOrientationChangedStreamController] start /// emitting values for any change in device orientation. static void startListeningForDeviceOrientationChange( bool isFrontFacing, int sensorOrientation, {BinaryMessenger? binaryMessenger}) { AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); final DeviceOrientationManagerHostApi api = DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); api.startListeningForDeviceOrientationChange( isFrontFacing, sensorOrientation); } /// Stops the [deviceOrientationChangedStreamController] from emitting values /// for changes in device orientation. static void stopListeningForDeviceOrientationChange( {BinaryMessenger? binaryMessenger}) { final DeviceOrientationManagerHostApi api = DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); api.stopListeningForDeviceOrientationChange(); } /// Retrieves the default rotation that CameraX uses for [UseCase]s in terms /// of one of the [Surface] rotation constants. /// /// The default rotation that CameraX uses is the rotation of the default /// display at the time of binding a particular [UseCase], but the default /// display does not change in the plugin, so this default value is /// display-agnostic. /// /// [startListeningForDeviceOrientationChange] must be called before calling /// this method. static Future<int> getDefaultDisplayRotation( {BinaryMessenger? binaryMessenger}) async { final DeviceOrientationManagerHostApi api = DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); return api.getDefaultDisplayRotation(); } /// Serializes [DeviceOrientation] into a [String]. static String serializeDeviceOrientation(DeviceOrientation orientation) { switch (orientation) { case DeviceOrientation.landscapeLeft: return 'LANDSCAPE_LEFT'; case DeviceOrientation.landscapeRight: return 'LANDSCAPE_RIGHT'; case DeviceOrientation.portraitDown: return 'PORTRAIT_DOWN'; case DeviceOrientation.portraitUp: return 'PORTRAIT_UP'; } } } /// Flutter API implementation of [DeviceOrientationManager]. class DeviceOrientationManagerFlutterApiImpl implements DeviceOrientationManagerFlutterApi { /// Constructs an [DeviceOrientationManagerFlutterApiImpl]. DeviceOrientationManagerFlutterApiImpl(); /// Callback method for any changes in device orientation. /// /// Will only be called if /// `DeviceOrientationManager.startListeningForDeviceOrientationChange(...)` was called /// to start listening for device orientation updates. @override void onDeviceOrientationChanged(String orientation) { final DeviceOrientation deviceOrientation = deserializeDeviceOrientation(orientation); DeviceOrientationManager.deviceOrientationChangedStreamController .add(DeviceOrientationChangedEvent(deviceOrientation)); } /// Deserializes device orientation in [String] format into a /// [DeviceOrientation]. DeviceOrientation deserializeDeviceOrientation(String orientation) { switch (orientation) { case 'LANDSCAPE_LEFT': return DeviceOrientation.landscapeLeft; case 'LANDSCAPE_RIGHT': return DeviceOrientation.landscapeRight; case 'PORTRAIT_DOWN': return DeviceOrientation.portraitDown; case 'PORTRAIT_UP': return DeviceOrientation.portraitUp; default: throw ArgumentError( '"$orientation" is not a valid DeviceOrientation value'); } } }
packages/packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart", "repo_id": "packages", "token_count": 1464 }
1,011
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:meta/meta.dart' show immutable; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camera.dart'; import 'camera_info.dart'; import 'camera_selector.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'use_case.dart'; /// Provides an object to manage the camera. /// /// See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider. @immutable class ProcessCameraProvider extends JavaObject { /// Creates a detached [ProcessCameraProvider]. ProcessCameraProvider.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = ProcessCameraProviderHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } late final ProcessCameraProviderHostApiImpl _api; /// Gets an instance of [ProcessCameraProvider]. static Future<ProcessCameraProvider> getInstance( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) { AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); final ProcessCameraProviderHostApiImpl api = ProcessCameraProviderHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); return api.getInstancefromInstances(); } /// Retrieves the cameras available to the device. Future<List<CameraInfo>> getAvailableCameraInfos() { return _api.getAvailableCameraInfosFromInstances(this); } /// Binds the specified [UseCase]s to the lifecycle of the camera that it /// returns. Future<Camera> bindToLifecycle( CameraSelector cameraSelector, List<UseCase> useCases) { return _api.bindToLifecycleFromInstances(this, cameraSelector, useCases); } /// Returns whether or not the specified [UseCase] has been bound to the /// lifecycle of the camera that this instance tracks. Future<bool> isBound(UseCase useCase) { return _api.isBoundFromInstances(this, useCase); } /// Unbinds specified [UseCase]s from the lifecycle of the camera that this /// instance tracks. void unbind(List<UseCase> useCases) { _api.unbindFromInstances(this, useCases); } /// Unbinds all previously bound [UseCase]s from the lifecycle of the camera /// that this tracks. void unbindAll() { _api.unbindAllFromInstances(this); } } /// Host API implementation of [ProcessCameraProvider]. class ProcessCameraProviderHostApiImpl extends ProcessCameraProviderHostApi { /// Constructs an [ProcessCameraProviderHostApiImpl]. /// /// 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]. ProcessCameraProviderHostApiImpl( {this.binaryMessenger, InstanceManager? instanceManager}) : super(binaryMessenger: binaryMessenger) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Retrieves an instance of a ProcessCameraProvider from the context of /// the FlutterActivity. Future<ProcessCameraProvider> getInstancefromInstances() async { return instanceManager.getInstanceWithWeakReference<ProcessCameraProvider>( await getInstance())!; } /// Gets identifier that the [instanceManager] has set for /// the [ProcessCameraProvider] instance. int getProcessCameraProviderIdentifier(ProcessCameraProvider instance) { final int? identifier = instanceManager.getIdentifier(instance); return identifier!; } /// Retrives the list of CameraInfos corresponding to the available cameras. Future<List<CameraInfo>> getAvailableCameraInfosFromInstances( ProcessCameraProvider instance) async { final int identifier = getProcessCameraProviderIdentifier(instance); final List<int?> cameraInfos = await getAvailableCameraInfos(identifier); return cameraInfos .map<CameraInfo>((int? id) => instanceManager.getInstanceWithWeakReference<CameraInfo>(id!)!) .toList(); } /// Binds the specified [UseCase]s to the lifecycle of the camera which /// the provided [ProcessCameraProvider] instance tracks. /// /// The instance of the camera whose lifecycle the [UseCase]s are bound to /// is returned. Future<Camera> bindToLifecycleFromInstances( ProcessCameraProvider instance, CameraSelector cameraSelector, List<UseCase> useCases, ) async { final int identifier = getProcessCameraProviderIdentifier(instance); final List<int> useCaseIds = useCases .map<int>((UseCase useCase) => instanceManager.getIdentifier(useCase)!) .toList(); final int cameraIdentifier = await bindToLifecycle( identifier, instanceManager.getIdentifier(cameraSelector)!, useCaseIds, ); return instanceManager .getInstanceWithWeakReference<Camera>(cameraIdentifier)!; } /// Returns whether or not the specified [UseCase] has been bound to the /// lifecycle of the camera that this instance tracks. Future<bool> isBoundFromInstances( ProcessCameraProvider instance, UseCase useCase, ) async { final int identifier = getProcessCameraProviderIdentifier(instance); final int? useCaseId = instanceManager.getIdentifier(useCase); assert(useCaseId != null, 'UseCase must have been created in order for this check to be valid.'); final bool useCaseIsBound = await isBound(identifier, useCaseId!); return useCaseIsBound; } /// Unbinds specified [UseCase]s from the lifecycle of the camera which the /// provided [ProcessCameraProvider] instance tracks. void unbindFromInstances( ProcessCameraProvider instance, List<UseCase> useCases, ) { final int identifier = getProcessCameraProviderIdentifier(instance); final List<int> useCaseIds = useCases .map<int>((UseCase useCase) => instanceManager.getIdentifier(useCase)!) .toList(); unbind(identifier, useCaseIds); } /// Unbinds all previously bound [UseCase]s from the lifecycle of the camera /// which the provided [ProcessCameraProvider] instance tracks. void unbindAllFromInstances(ProcessCameraProvider instance) { final int identifier = getProcessCameraProviderIdentifier(instance); unbindAll(identifier); } } /// Flutter API Implementation of [ProcessCameraProvider]. class ProcessCameraProviderFlutterApiImpl implements ProcessCameraProviderFlutterApi { /// Constructs an [ProcessCameraProviderFlutterApiImpl]. /// /// 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]. ProcessCameraProviderFlutterApiImpl({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? _binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager _instanceManager; @override void create(int identifier) { _instanceManager.addHostCreatedInstance( ProcessCameraProvider.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), identifier, onCopy: (ProcessCameraProvider original) { return ProcessCameraProvider.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager); }, ); } }
packages/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart", "repo_id": "packages", "token_count": 2554 }
1,012
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/android_camera_camerax_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i16; import 'dart:typed_data' as _i31; import 'package:camera_android_camerax/src/analyzer.dart' as _i15; import 'package:camera_android_camerax/src/camera.dart' as _i9; import 'package:camera_android_camerax/src/camera2_camera_control.dart' as _i22; import 'package:camera_android_camerax/src/camera_control.dart' as _i3; import 'package:camera_android_camerax/src/camera_info.dart' as _i2; import 'package:camera_android_camerax/src/camera_selector.dart' as _i24; import 'package:camera_android_camerax/src/camera_state.dart' as _i18; import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i7; import 'package:camera_android_camerax/src/capture_request_options.dart' as _i23; import 'package:camera_android_camerax/src/exposure_state.dart' as _i5; import 'package:camera_android_camerax/src/fallback_strategy.dart' as _i25; import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i21; import 'package:camera_android_camerax/src/focus_metering_result.dart' as _i20; import 'package:camera_android_camerax/src/image_analysis.dart' as _i26; import 'package:camera_android_camerax/src/image_capture.dart' as _i27; import 'package:camera_android_camerax/src/image_proxy.dart' as _i17; import 'package:camera_android_camerax/src/live_data.dart' as _i4; import 'package:camera_android_camerax/src/observer.dart' as _i30; import 'package:camera_android_camerax/src/pending_recording.dart' as _i10; import 'package:camera_android_camerax/src/plane_proxy.dart' as _i29; import 'package:camera_android_camerax/src/preview.dart' as _i32; import 'package:camera_android_camerax/src/process_camera_provider.dart' as _i33; import 'package:camera_android_camerax/src/quality_selector.dart' as _i35; import 'package:camera_android_camerax/src/recorder.dart' as _i11; import 'package:camera_android_camerax/src/recording.dart' as _i8; import 'package:camera_android_camerax/src/resolution_selector.dart' as _i36; import 'package:camera_android_camerax/src/resolution_strategy.dart' as _i37; import 'package:camera_android_camerax/src/use_case.dart' as _i34; import 'package:camera_android_camerax/src/video_capture.dart' as _i38; import 'package:camera_android_camerax/src/zoom_state.dart' as _i19; import 'package:camera_platform_interface/camera_platform_interface.dart' as _i6; import 'package:flutter/foundation.dart' as _i14; import 'package:flutter/services.dart' as _i13; import 'package:flutter/widgets.dart' as _i12; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i28; import 'test_camerax_library.g.dart' as _i39; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeCameraInfo_0 extends _i1.SmartFake implements _i2.CameraInfo { _FakeCameraInfo_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCameraControl_1 extends _i1.SmartFake implements _i3.CameraControl { _FakeCameraControl_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeLiveData_2<T extends Object> extends _i1.SmartFake implements _i4.LiveData<T> { _FakeLiveData_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeExposureState_3 extends _i1.SmartFake implements _i5.ExposureState { _FakeExposureState_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCameraImageFormat_4 extends _i1.SmartFake implements _i6.CameraImageFormat { _FakeCameraImageFormat_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeExposureCompensationRange_5 extends _i1.SmartFake implements _i7.ExposureCompensationRange { _FakeExposureCompensationRange_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRecording_6 extends _i1.SmartFake implements _i8.Recording { _FakeRecording_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeResolutionInfo_7 extends _i1.SmartFake implements _i7.ResolutionInfo { _FakeResolutionInfo_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCamera_8 extends _i1.SmartFake implements _i9.Camera { _FakeCamera_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePendingRecording_9 extends _i1.SmartFake implements _i10.PendingRecording { _FakePendingRecording_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRecorder_10 extends _i1.SmartFake implements _i11.Recorder { _FakeRecorder_10( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWidget_11 extends _i1.SmartFake implements _i12.Widget { _FakeWidget_11( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString( {_i13.DiagnosticLevel? minLevel = _i13.DiagnosticLevel.info}) => super.toString(); } class _FakeInheritedWidget_12 extends _i1.SmartFake implements _i12.InheritedWidget { _FakeInheritedWidget_12( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString( {_i13.DiagnosticLevel? minLevel = _i13.DiagnosticLevel.info}) => super.toString(); } class _FakeDiagnosticsNode_13 extends _i1.SmartFake implements _i14.DiagnosticsNode { _FakeDiagnosticsNode_13( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({ _i14.TextTreeConfiguration? parentConfiguration, _i13.DiagnosticLevel? minLevel = _i13.DiagnosticLevel.info, }) => super.toString(); } /// A class which mocks [Analyzer]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockAnalyzer extends _i1.Mock implements _i15.Analyzer { @override _i16.Future<void> Function(_i17.ImageProxy) get analyze => (super.noSuchMethod( Invocation.getter(#analyze), returnValue: (_i17.ImageProxy imageProxy) => _i16.Future<void>.value(), returnValueForMissingStub: (_i17.ImageProxy imageProxy) => _i16.Future<void>.value(), ) as _i16.Future<void> Function(_i17.ImageProxy)); } /// A class which mocks [Camera]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCamera extends _i1.Mock implements _i9.Camera { @override _i16.Future<_i2.CameraInfo> getCameraInfo() => (super.noSuchMethod( Invocation.method( #getCameraInfo, [], ), returnValue: _i16.Future<_i2.CameraInfo>.value(_FakeCameraInfo_0( this, Invocation.method( #getCameraInfo, [], ), )), returnValueForMissingStub: _i16.Future<_i2.CameraInfo>.value(_FakeCameraInfo_0( this, Invocation.method( #getCameraInfo, [], ), )), ) as _i16.Future<_i2.CameraInfo>); @override _i16.Future<_i3.CameraControl> getCameraControl() => (super.noSuchMethod( Invocation.method( #getCameraControl, [], ), returnValue: _i16.Future<_i3.CameraControl>.value(_FakeCameraControl_1( this, Invocation.method( #getCameraControl, [], ), )), returnValueForMissingStub: _i16.Future<_i3.CameraControl>.value(_FakeCameraControl_1( this, Invocation.method( #getCameraControl, [], ), )), ) as _i16.Future<_i3.CameraControl>); } /// A class which mocks [CameraInfo]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCameraInfo extends _i1.Mock implements _i2.CameraInfo { @override _i16.Future<int> getSensorRotationDegrees() => (super.noSuchMethod( Invocation.method( #getSensorRotationDegrees, [], ), returnValue: _i16.Future<int>.value(0), returnValueForMissingStub: _i16.Future<int>.value(0), ) as _i16.Future<int>); @override _i16.Future<_i4.LiveData<_i18.CameraState>> getCameraState() => (super.noSuchMethod( Invocation.method( #getCameraState, [], ), returnValue: _i16.Future<_i4.LiveData<_i18.CameraState>>.value( _FakeLiveData_2<_i18.CameraState>( this, Invocation.method( #getCameraState, [], ), )), returnValueForMissingStub: _i16.Future<_i4.LiveData<_i18.CameraState>>.value( _FakeLiveData_2<_i18.CameraState>( this, Invocation.method( #getCameraState, [], ), )), ) as _i16.Future<_i4.LiveData<_i18.CameraState>>); @override _i16.Future<_i5.ExposureState> getExposureState() => (super.noSuchMethod( Invocation.method( #getExposureState, [], ), returnValue: _i16.Future<_i5.ExposureState>.value(_FakeExposureState_3( this, Invocation.method( #getExposureState, [], ), )), returnValueForMissingStub: _i16.Future<_i5.ExposureState>.value(_FakeExposureState_3( this, Invocation.method( #getExposureState, [], ), )), ) as _i16.Future<_i5.ExposureState>); @override _i16.Future<_i4.LiveData<_i19.ZoomState>> getZoomState() => (super.noSuchMethod( Invocation.method( #getZoomState, [], ), returnValue: _i16.Future<_i4.LiveData<_i19.ZoomState>>.value( _FakeLiveData_2<_i19.ZoomState>( this, Invocation.method( #getZoomState, [], ), )), returnValueForMissingStub: _i16.Future<_i4.LiveData<_i19.ZoomState>>.value( _FakeLiveData_2<_i19.ZoomState>( this, Invocation.method( #getZoomState, [], ), )), ) as _i16.Future<_i4.LiveData<_i19.ZoomState>>); } /// A class which mocks [CameraControl]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCameraControl extends _i1.Mock implements _i3.CameraControl { @override _i16.Future<void> enableTorch(bool? torch) => (super.noSuchMethod( Invocation.method( #enableTorch, [torch], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> setZoomRatio(double? ratio) => (super.noSuchMethod( Invocation.method( #setZoomRatio, [ratio], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<_i20.FocusMeteringResult?> startFocusAndMetering( _i21.FocusMeteringAction? action) => (super.noSuchMethod( Invocation.method( #startFocusAndMetering, [action], ), returnValue: _i16.Future<_i20.FocusMeteringResult?>.value(), returnValueForMissingStub: _i16.Future<_i20.FocusMeteringResult?>.value(), ) as _i16.Future<_i20.FocusMeteringResult?>); @override _i16.Future<void> cancelFocusAndMetering() => (super.noSuchMethod( Invocation.method( #cancelFocusAndMetering, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<int?> setExposureCompensationIndex(int? index) => (super.noSuchMethod( Invocation.method( #setExposureCompensationIndex, [index], ), returnValue: _i16.Future<int?>.value(), returnValueForMissingStub: _i16.Future<int?>.value(), ) as _i16.Future<int?>); } /// A class which mocks [Camera2CameraControl]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCamera2CameraControl extends _i1.Mock implements _i22.Camera2CameraControl { @override _i3.CameraControl get cameraControl => (super.noSuchMethod( Invocation.getter(#cameraControl), returnValue: _FakeCameraControl_1( this, Invocation.getter(#cameraControl), ), returnValueForMissingStub: _FakeCameraControl_1( this, Invocation.getter(#cameraControl), ), ) as _i3.CameraControl); @override _i16.Future<void> addCaptureRequestOptions( _i23.CaptureRequestOptions? captureRequestOptions) => (super.noSuchMethod( Invocation.method( #addCaptureRequestOptions, [captureRequestOptions], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); } /// A class which mocks [CameraImageData]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCameraImageData extends _i1.Mock implements _i6.CameraImageData { @override _i6.CameraImageFormat get format => (super.noSuchMethod( Invocation.getter(#format), returnValue: _FakeCameraImageFormat_4( this, Invocation.getter(#format), ), returnValueForMissingStub: _FakeCameraImageFormat_4( this, Invocation.getter(#format), ), ) as _i6.CameraImageFormat); @override int get height => (super.noSuchMethod( Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override int get width => (super.noSuchMethod( Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override List<_i6.CameraImagePlane> get planes => (super.noSuchMethod( Invocation.getter(#planes), returnValue: <_i6.CameraImagePlane>[], returnValueForMissingStub: <_i6.CameraImagePlane>[], ) as List<_i6.CameraImagePlane>); } /// A class which mocks [CameraSelector]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockCameraSelector extends _i1.Mock implements _i24.CameraSelector { @override _i16.Future<List<_i2.CameraInfo>> filter(List<_i2.CameraInfo>? cameraInfos) => (super.noSuchMethod( Invocation.method( #filter, [cameraInfos], ), returnValue: _i16.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]), returnValueForMissingStub: _i16.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]), ) as _i16.Future<List<_i2.CameraInfo>>); } /// A class which mocks [ExposureState]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockExposureState extends _i1.Mock implements _i5.ExposureState { @override _i7.ExposureCompensationRange get exposureCompensationRange => (super.noSuchMethod( Invocation.getter(#exposureCompensationRange), returnValue: _FakeExposureCompensationRange_5( this, Invocation.getter(#exposureCompensationRange), ), returnValueForMissingStub: _FakeExposureCompensationRange_5( this, Invocation.getter(#exposureCompensationRange), ), ) as _i7.ExposureCompensationRange); @override double get exposureCompensationStep => (super.noSuchMethod( Invocation.getter(#exposureCompensationStep), returnValue: 0.0, returnValueForMissingStub: 0.0, ) as double); } /// A class which mocks [FallbackStrategy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockFallbackStrategy extends _i1.Mock implements _i25.FallbackStrategy { @override _i7.VideoQuality get quality => (super.noSuchMethod( Invocation.getter(#quality), returnValue: _i7.VideoQuality.SD, returnValueForMissingStub: _i7.VideoQuality.SD, ) as _i7.VideoQuality); @override _i7.VideoResolutionFallbackRule get fallbackRule => (super.noSuchMethod( Invocation.getter(#fallbackRule), returnValue: _i7.VideoResolutionFallbackRule.higherQualityOrLowerThan, returnValueForMissingStub: _i7.VideoResolutionFallbackRule.higherQualityOrLowerThan, ) as _i7.VideoResolutionFallbackRule); } /// A class which mocks [FocusMeteringResult]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockFocusMeteringResult extends _i1.Mock implements _i20.FocusMeteringResult { @override _i16.Future<bool> isFocusSuccessful() => (super.noSuchMethod( Invocation.method( #isFocusSuccessful, [], ), returnValue: _i16.Future<bool>.value(false), returnValueForMissingStub: _i16.Future<bool>.value(false), ) as _i16.Future<bool>); } /// A class which mocks [ImageAnalysis]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockImageAnalysis extends _i1.Mock implements _i26.ImageAnalysis { @override _i16.Future<void> setTargetRotation(int? rotation) => (super.noSuchMethod( Invocation.method( #setTargetRotation, [rotation], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> setAnalyzer(_i15.Analyzer? analyzer) => (super.noSuchMethod( Invocation.method( #setAnalyzer, [analyzer], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> clearAnalyzer() => (super.noSuchMethod( Invocation.method( #clearAnalyzer, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); } /// A class which mocks [ImageCapture]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockImageCapture extends _i1.Mock implements _i27.ImageCapture { @override _i16.Future<void> setTargetRotation(int? rotation) => (super.noSuchMethod( Invocation.method( #setTargetRotation, [rotation], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> setFlashMode(int? newFlashMode) => (super.noSuchMethod( Invocation.method( #setFlashMode, [newFlashMode], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<String> takePicture() => (super.noSuchMethod( Invocation.method( #takePicture, [], ), returnValue: _i16.Future<String>.value(_i28.dummyValue<String>( this, Invocation.method( #takePicture, [], ), )), returnValueForMissingStub: _i16.Future<String>.value(_i28.dummyValue<String>( this, Invocation.method( #takePicture, [], ), )), ) as _i16.Future<String>); } /// A class which mocks [ImageProxy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockImageProxy extends _i1.Mock implements _i17.ImageProxy { @override int get format => (super.noSuchMethod( Invocation.getter(#format), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override int get height => (super.noSuchMethod( Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override int get width => (super.noSuchMethod( Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override _i16.Future<List<_i29.PlaneProxy>> getPlanes() => (super.noSuchMethod( Invocation.method( #getPlanes, [], ), returnValue: _i16.Future<List<_i29.PlaneProxy>>.value(<_i29.PlaneProxy>[]), returnValueForMissingStub: _i16.Future<List<_i29.PlaneProxy>>.value(<_i29.PlaneProxy>[]), ) as _i16.Future<List<_i29.PlaneProxy>>); @override _i16.Future<void> close() => (super.noSuchMethod( Invocation.method( #close, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); } /// A class which mocks [Observer]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockObserver extends _i1.Mock implements _i30.Observer<_i18.CameraState> { @override void Function(Object) get onChanged => (super.noSuchMethod( Invocation.getter(#onChanged), returnValue: (Object value) {}, returnValueForMissingStub: (Object value) {}, ) as void Function(Object)); @override set onChanged(void Function(Object)? _onChanged) => super.noSuchMethod( Invocation.setter( #onChanged, _onChanged, ), returnValueForMissingStub: null, ); } /// A class which mocks [PendingRecording]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockPendingRecording extends _i1.Mock implements _i10.PendingRecording { @override _i16.Future<_i8.Recording> start() => (super.noSuchMethod( Invocation.method( #start, [], ), returnValue: _i16.Future<_i8.Recording>.value(_FakeRecording_6( this, Invocation.method( #start, [], ), )), returnValueForMissingStub: _i16.Future<_i8.Recording>.value(_FakeRecording_6( this, Invocation.method( #start, [], ), )), ) as _i16.Future<_i8.Recording>); } /// A class which mocks [PlaneProxy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockPlaneProxy extends _i1.Mock implements _i29.PlaneProxy { @override _i31.Uint8List get buffer => (super.noSuchMethod( Invocation.getter(#buffer), returnValue: _i31.Uint8List(0), returnValueForMissingStub: _i31.Uint8List(0), ) as _i31.Uint8List); @override int get pixelStride => (super.noSuchMethod( Invocation.getter(#pixelStride), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override int get rowStride => (super.noSuchMethod( Invocation.getter(#rowStride), returnValue: 0, returnValueForMissingStub: 0, ) as int); } /// A class which mocks [Preview]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockPreview extends _i1.Mock implements _i32.Preview { @override _i16.Future<void> setTargetRotation(int? rotation) => (super.noSuchMethod( Invocation.method( #setTargetRotation, [rotation], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<int> setSurfaceProvider() => (super.noSuchMethod( Invocation.method( #setSurfaceProvider, [], ), returnValue: _i16.Future<int>.value(0), returnValueForMissingStub: _i16.Future<int>.value(0), ) as _i16.Future<int>); @override void releaseFlutterSurfaceTexture() => super.noSuchMethod( Invocation.method( #releaseFlutterSurfaceTexture, [], ), returnValueForMissingStub: null, ); @override _i16.Future<_i7.ResolutionInfo> getResolutionInfo() => (super.noSuchMethod( Invocation.method( #getResolutionInfo, [], ), returnValue: _i16.Future<_i7.ResolutionInfo>.value(_FakeResolutionInfo_7( this, Invocation.method( #getResolutionInfo, [], ), )), returnValueForMissingStub: _i16.Future<_i7.ResolutionInfo>.value(_FakeResolutionInfo_7( this, Invocation.method( #getResolutionInfo, [], ), )), ) as _i16.Future<_i7.ResolutionInfo>); } /// A class which mocks [ProcessCameraProvider]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockProcessCameraProvider extends _i1.Mock implements _i33.ProcessCameraProvider { @override _i16.Future<List<_i2.CameraInfo>> getAvailableCameraInfos() => (super.noSuchMethod( Invocation.method( #getAvailableCameraInfos, [], ), returnValue: _i16.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]), returnValueForMissingStub: _i16.Future<List<_i2.CameraInfo>>.value(<_i2.CameraInfo>[]), ) as _i16.Future<List<_i2.CameraInfo>>); @override _i16.Future<_i9.Camera> bindToLifecycle( _i24.CameraSelector? cameraSelector, List<_i34.UseCase>? useCases, ) => (super.noSuchMethod( Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), returnValue: _i16.Future<_i9.Camera>.value(_FakeCamera_8( this, Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), )), returnValueForMissingStub: _i16.Future<_i9.Camera>.value(_FakeCamera_8( this, Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), )), ) as _i16.Future<_i9.Camera>); @override _i16.Future<bool> isBound(_i34.UseCase? useCase) => (super.noSuchMethod( Invocation.method( #isBound, [useCase], ), returnValue: _i16.Future<bool>.value(false), returnValueForMissingStub: _i16.Future<bool>.value(false), ) as _i16.Future<bool>); @override void unbind(List<_i34.UseCase>? useCases) => super.noSuchMethod( Invocation.method( #unbind, [useCases], ), returnValueForMissingStub: null, ); @override void unbindAll() => super.noSuchMethod( Invocation.method( #unbindAll, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [QualitySelector]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockQualitySelector extends _i1.Mock implements _i35.QualitySelector { @override List<_i7.VideoQualityData> get qualityList => (super.noSuchMethod( Invocation.getter(#qualityList), returnValue: <_i7.VideoQualityData>[], returnValueForMissingStub: <_i7.VideoQualityData>[], ) as List<_i7.VideoQualityData>); } /// A class which mocks [Recorder]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockRecorder extends _i1.Mock implements _i11.Recorder { @override _i16.Future<_i10.PendingRecording> prepareRecording(String? path) => (super.noSuchMethod( Invocation.method( #prepareRecording, [path], ), returnValue: _i16.Future<_i10.PendingRecording>.value(_FakePendingRecording_9( this, Invocation.method( #prepareRecording, [path], ), )), returnValueForMissingStub: _i16.Future<_i10.PendingRecording>.value(_FakePendingRecording_9( this, Invocation.method( #prepareRecording, [path], ), )), ) as _i16.Future<_i10.PendingRecording>); } /// A class which mocks [ResolutionSelector]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockResolutionSelector extends _i1.Mock implements _i36.ResolutionSelector {} /// A class which mocks [ResolutionStrategy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockResolutionStrategy extends _i1.Mock implements _i37.ResolutionStrategy {} /// A class which mocks [Recording]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockRecording extends _i1.Mock implements _i8.Recording { @override _i16.Future<void> close() => (super.noSuchMethod( Invocation.method( #close, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> pause() => (super.noSuchMethod( Invocation.method( #pause, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> resume() => (super.noSuchMethod( Invocation.method( #resume, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> stop() => (super.noSuchMethod( Invocation.method( #stop, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); } /// A class which mocks [VideoCapture]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockVideoCapture extends _i1.Mock implements _i38.VideoCapture { @override _i16.Future<void> setTargetRotation(int? rotation) => (super.noSuchMethod( Invocation.method( #setTargetRotation, [rotation], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<_i11.Recorder> getOutput() => (super.noSuchMethod( Invocation.method( #getOutput, [], ), returnValue: _i16.Future<_i11.Recorder>.value(_FakeRecorder_10( this, Invocation.method( #getOutput, [], ), )), returnValueForMissingStub: _i16.Future<_i11.Recorder>.value(_FakeRecorder_10( this, Invocation.method( #getOutput, [], ), )), ) as _i16.Future<_i11.Recorder>); } /// A class which mocks [BuildContext]. /// /// See the documentation for Mockito's code generation for more information. class MockBuildContext extends _i1.Mock implements _i12.BuildContext { @override _i12.Widget get widget => (super.noSuchMethod( Invocation.getter(#widget), returnValue: _FakeWidget_11( this, Invocation.getter(#widget), ), returnValueForMissingStub: _FakeWidget_11( this, Invocation.getter(#widget), ), ) as _i12.Widget); @override bool get mounted => (super.noSuchMethod( Invocation.getter(#mounted), returnValue: false, returnValueForMissingStub: false, ) as bool); @override bool get debugDoingBuild => (super.noSuchMethod( Invocation.getter(#debugDoingBuild), returnValue: false, returnValueForMissingStub: false, ) as bool); @override _i12.InheritedWidget dependOnInheritedElement( _i12.InheritedElement? ancestor, { Object? aspect, }) => (super.noSuchMethod( Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), returnValue: _FakeInheritedWidget_12( this, Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), ), returnValueForMissingStub: _FakeInheritedWidget_12( this, Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), ), ) as _i12.InheritedWidget); @override void visitAncestorElements(_i12.ConditionalElementVisitor? visitor) => super.noSuchMethod( Invocation.method( #visitAncestorElements, [visitor], ), returnValueForMissingStub: null, ); @override void visitChildElements(_i12.ElementVisitor? visitor) => super.noSuchMethod( Invocation.method( #visitChildElements, [visitor], ), returnValueForMissingStub: null, ); @override void dispatchNotification(_i12.Notification? notification) => super.noSuchMethod( Invocation.method( #dispatchNotification, [notification], ), returnValueForMissingStub: null, ); @override _i14.DiagnosticsNode describeElement( String? name, { _i14.DiagnosticsTreeStyle? style = _i14.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeElement, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_13( this, Invocation.method( #describeElement, [name], {#style: style}, ), ), returnValueForMissingStub: _FakeDiagnosticsNode_13( this, Invocation.method( #describeElement, [name], {#style: style}, ), ), ) as _i14.DiagnosticsNode); @override _i14.DiagnosticsNode describeWidget( String? name, { _i14.DiagnosticsTreeStyle? style = _i14.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeWidget, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_13( this, Invocation.method( #describeWidget, [name], {#style: style}, ), ), returnValueForMissingStub: _FakeDiagnosticsNode_13( this, Invocation.method( #describeWidget, [name], {#style: style}, ), ), ) as _i14.DiagnosticsNode); @override List<_i14.DiagnosticsNode> describeMissingAncestor( {required Type? expectedAncestorType}) => (super.noSuchMethod( Invocation.method( #describeMissingAncestor, [], {#expectedAncestorType: expectedAncestorType}, ), returnValue: <_i14.DiagnosticsNode>[], returnValueForMissingStub: <_i14.DiagnosticsNode>[], ) as List<_i14.DiagnosticsNode>); @override _i14.DiagnosticsNode describeOwnershipChain(String? name) => (super.noSuchMethod( Invocation.method( #describeOwnershipChain, [name], ), returnValue: _FakeDiagnosticsNode_13( this, Invocation.method( #describeOwnershipChain, [name], ), ), returnValueForMissingStub: _FakeDiagnosticsNode_13( this, Invocation.method( #describeOwnershipChain, [name], ), ), ) as _i14.DiagnosticsNode); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i39.TestInstanceManagerHostApi { @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestSystemServicesHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestSystemServicesHostApi extends _i1.Mock implements _i39.TestSystemServicesHostApi { @override _i16.Future<_i7.CameraPermissionsErrorData?> requestCameraPermissions( bool? enableAudio) => (super.noSuchMethod( Invocation.method( #requestCameraPermissions, [enableAudio], ), returnValue: _i16.Future<_i7.CameraPermissionsErrorData?>.value(), returnValueForMissingStub: _i16.Future<_i7.CameraPermissionsErrorData?>.value(), ) as _i16.Future<_i7.CameraPermissionsErrorData?>); @override String getTempFilePath( String? prefix, String? suffix, ) => (super.noSuchMethod( Invocation.method( #getTempFilePath, [ prefix, suffix, ], ), returnValue: _i28.dummyValue<String>( this, Invocation.method( #getTempFilePath, [ prefix, suffix, ], ), ), returnValueForMissingStub: _i28.dummyValue<String>( this, Invocation.method( #getTempFilePath, [ prefix, suffix, ], ), ), ) as String); } /// A class which mocks [ZoomState]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockZoomState extends _i1.Mock implements _i19.ZoomState { @override double get minZoomRatio => (super.noSuchMethod( Invocation.getter(#minZoomRatio), returnValue: 0.0, returnValueForMissingStub: 0.0, ) as double); @override double get maxZoomRatio => (super.noSuchMethod( Invocation.getter(#maxZoomRatio), returnValue: 0.0, returnValueForMissingStub: 0.0, ) as double); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockLiveCameraState extends _i1.Mock implements _i4.LiveData<_i18.CameraState> { MockLiveCameraState() { _i1.throwOnMissingStub(this); } @override _i16.Future<void> observe(_i30.Observer<_i18.CameraState>? observer) => (super.noSuchMethod( Invocation.method( #observe, [observer], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> removeObservers() => (super.noSuchMethod( Invocation.method( #removeObservers, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockLiveZoomState extends _i1.Mock implements _i4.LiveData<_i19.ZoomState> { MockLiveZoomState() { _i1.throwOnMissingStub(this); } @override _i16.Future<void> observe(_i30.Observer<_i19.ZoomState>? observer) => (super.noSuchMethod( Invocation.method( #observe, [observer], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); @override _i16.Future<void> removeObservers() => (super.noSuchMethod( Invocation.method( #removeObservers, [], ), returnValue: _i16.Future<void>.value(), returnValueForMissingStub: _i16.Future<void>.value(), ) as _i16.Future<void>); }
packages/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart", "repo_id": "packages", "token_count": 19189 }
1,013
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/camera_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestCameraHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestCameraHostApi extends _i1.Mock implements _i2.TestCameraHostApi { MockTestCameraHostApi() { _i1.throwOnMissingStub(this); } @override int getCameraInfo(int? identifier) => (super.noSuchMethod( Invocation.method( #getCameraInfo, [identifier], ), returnValue: 0, ) as int); @override int getCameraControl(int? identifier) => (super.noSuchMethod( Invocation.method( #getCameraControl, [identifier], ), returnValue: 0, ) as int); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/camera/camera_android_camerax/test/camera_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/camera_test.mocks.dart", "repo_id": "packages", "token_count": 760 }
1,014
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/image_capture_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:camera_android_camerax/src/resolution_selector.dart' as _i5; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i4; 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 [TestImageCaptureHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestImageCaptureHostApi extends _i1.Mock implements _i2.TestImageCaptureHostApi { MockTestImageCaptureHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, int? targetRotation, int? flashMode, int? resolutionSelectorId, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, targetRotation, flashMode, resolutionSelectorId, ], ), returnValueForMissingStub: null, ); @override void setFlashMode( int? identifier, int? flashMode, ) => super.noSuchMethod( Invocation.method( #setFlashMode, [ identifier, flashMode, ], ), returnValueForMissingStub: null, ); @override _i3.Future<String> takePicture(int? identifier) => (super.noSuchMethod( Invocation.method( #takePicture, [identifier], ), returnValue: _i3.Future<String>.value(_i4.dummyValue<String>( this, Invocation.method( #takePicture, [identifier], ), )), ) as _i3.Future<String>); @override void setTargetRotation( int? identifier, int? rotation, ) => super.noSuchMethod( Invocation.method( #setTargetRotation, [ identifier, rotation, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [ResolutionSelector]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockResolutionSelector extends _i1.Mock implements _i5.ResolutionSelector { MockResolutionSelector() { _i1.throwOnMissingStub(this); } }
packages/packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart", "repo_id": "packages", "token_count": 1467 }
1,015
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_android_camerax/src/camera.dart'; import 'package:camera_android_camerax/src/camera_info.dart'; import 'package:camera_android_camerax/src/camera_selector.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/process_camera_provider.dart'; import 'package:camera_android_camerax/src/use_case.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'process_camera_provider_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks( <Type>[TestInstanceManagerHostApi, TestProcessCameraProviderHostApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('ProcessCameraProvider', () { tearDown(() => TestProcessCameraProviderHostApi.setup(null)); test('getInstanceTest', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); when(mockApi.getInstance()).thenAnswer((_) async => 0); expect( await ProcessCameraProvider.getInstance( instanceManager: instanceManager), equals(processCameraProvider)); verify(mockApi.getInstance()); }); test('getAvailableCameraInfosTest', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); final CameraInfo fakeAvailableCameraInfo = CameraInfo.detached(instanceManager: instanceManager); instanceManager.addHostCreatedInstance( fakeAvailableCameraInfo, 1, onCopy: (_) => CameraInfo.detached(), ); when(mockApi.getAvailableCameraInfos(0)).thenReturn(<int>[1]); expect(await processCameraProvider.getAvailableCameraInfos(), equals(<CameraInfo>[fakeAvailableCameraInfo])); verify(mockApi.getAvailableCameraInfos(0)); }); test('bindToLifecycleTest', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); final CameraSelector fakeCameraSelector = CameraSelector.detached(instanceManager: instanceManager); final UseCase fakeUseCase = UseCase.detached(instanceManager: instanceManager); final Camera fakeCamera = Camera.detached(instanceManager: instanceManager); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); instanceManager.addHostCreatedInstance( fakeCameraSelector, 1, onCopy: (_) => CameraSelector.detached(), ); instanceManager.addHostCreatedInstance( fakeUseCase, 2, onCopy: (_) => UseCase.detached(), ); instanceManager.addHostCreatedInstance( fakeCamera, 3, onCopy: (_) => Camera.detached(), ); when(mockApi.bindToLifecycle(0, 1, <int>[2])).thenReturn(3); expect( await processCameraProvider .bindToLifecycle(fakeCameraSelector, <UseCase>[fakeUseCase]), equals(fakeCamera)); verify(mockApi.bindToLifecycle(0, 1, <int>[2])); }); test('isBoundTest', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); final UseCase fakeUseCase = UseCase.detached(instanceManager: instanceManager); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); instanceManager.addHostCreatedInstance( fakeUseCase, 27, onCopy: (_) => UseCase.detached(), ); when(mockApi.isBound(0, 27)).thenReturn(true); expect(await processCameraProvider.isBound(fakeUseCase), isTrue); verify(mockApi.isBound(0, 27)); }); test('unbindTest', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); final UseCase fakeUseCase = UseCase.detached(instanceManager: instanceManager); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); instanceManager.addHostCreatedInstance( fakeUseCase, 1, onCopy: (_) => UseCase.detached(), ); processCameraProvider.unbind(<UseCase>[fakeUseCase]); verify(mockApi.unbind(0, <int>[1])); }); test('unbindAll unbinds UseCases', () async { final MockTestProcessCameraProviderHostApi mockApi = MockTestProcessCameraProviderHostApi(); TestProcessCameraProviderHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProvider processCameraProvider = ProcessCameraProvider.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( processCameraProvider, 0, onCopy: (_) => ProcessCameraProvider.detached(), ); processCameraProvider.unbindAll(); verify(mockApi.unbindAll(0)); }); test('flutterApiCreateTest', () { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ProcessCameraProviderFlutterApiImpl flutterApi = ProcessCameraProviderFlutterApiImpl( instanceManager: instanceManager, ); flutterApi.create(0); expect(instanceManager.getInstanceWithWeakReference(0), isA<ProcessCameraProvider>()); }); }); }
packages/packages/camera/camera_android_camerax/test/process_camera_provider_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/process_camera_provider_test.dart", "repo_id": "packages", "token_count": 3037 }
1,016
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/video_capture_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; import 'package:camera_android_camerax/src/pending_recording.dart' as _i2; import 'package:camera_android_camerax/src/recorder.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i3; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakePendingRecording_0 extends _i1.SmartFake implements _i2.PendingRecording { _FakePendingRecording_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [TestVideoCaptureHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestVideoCaptureHostApi extends _i1.Mock implements _i3.TestVideoCaptureHostApi { MockTestVideoCaptureHostApi() { _i1.throwOnMissingStub(this); } @override int withOutput(int? videoOutputId) => (super.noSuchMethod( Invocation.method( #withOutput, [videoOutputId], ), returnValue: 0, ) as int); @override int getOutput(int? identifier) => (super.noSuchMethod( Invocation.method( #getOutput, [identifier], ), returnValue: 0, ) as int); @override void setTargetRotation( int? identifier, int? rotation, ) => super.noSuchMethod( Invocation.method( #setTargetRotation, [ identifier, rotation, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i3.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [Recorder]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockRecorder extends _i1.Mock implements _i4.Recorder { MockRecorder() { _i1.throwOnMissingStub(this); } @override _i5.Future<_i2.PendingRecording> prepareRecording(String? path) => (super.noSuchMethod( Invocation.method( #prepareRecording, [path], ), returnValue: _i5.Future<_i2.PendingRecording>.value(_FakePendingRecording_0( this, Invocation.method( #prepareRecording, [path], ), )), ) as _i5.Future<_i2.PendingRecording>); }
packages/packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart", "repo_id": "packages", "token_count": 1435 }
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 camera_avfoundation; @import XCTest; #import <OCMock/OCMock.h> @interface ThreadSafeEventChannelTests : XCTestCase @end @implementation ThreadSafeEventChannelTests - (void)testSetStreamHandler_shouldStayOnMainThreadIfCalledFromMainThread { FlutterEventChannel *mockEventChannel = OCMClassMock([FlutterEventChannel class]); FLTThreadSafeEventChannel *threadSafeEventChannel = [[FLTThreadSafeEventChannel alloc] initWithEventChannel:mockEventChannel]; XCTestExpectation *mainThreadExpectation = [self expectationWithDescription:@"setStreamHandler must be called on the main thread"]; XCTestExpectation *mainThreadCompletionExpectation = [self expectationWithDescription: @"setStreamHandler's completion block must be called on the main thread"]; OCMStub([mockEventChannel setStreamHandler:[OCMArg any]]).andDo(^(NSInvocation *invocation) { if (NSThread.isMainThread) { [mainThreadExpectation fulfill]; } }); [threadSafeEventChannel setStreamHandler:nil completion:^{ if (NSThread.isMainThread) { [mainThreadCompletionExpectation fulfill]; } }]; [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testSetStreamHandler_shouldDispatchToMainThreadIfCalledFromBackgroundThread { FlutterEventChannel *mockEventChannel = OCMClassMock([FlutterEventChannel class]); FLTThreadSafeEventChannel *threadSafeEventChannel = [[FLTThreadSafeEventChannel alloc] initWithEventChannel:mockEventChannel]; XCTestExpectation *mainThreadExpectation = [self expectationWithDescription:@"setStreamHandler must be called on the main thread"]; XCTestExpectation *mainThreadCompletionExpectation = [self expectationWithDescription: @"setStreamHandler's completion block must be called on the main thread"]; OCMStub([mockEventChannel setStreamHandler:[OCMArg any]]).andDo(^(NSInvocation *invocation) { if (NSThread.isMainThread) { [mainThreadExpectation fulfill]; } }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [threadSafeEventChannel setStreamHandler:nil completion:^{ if (NSThread.isMainThread) { [mainThreadCompletionExpectation fulfill]; } }]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testEventChannel_shouldBeKeptAliveWhenDispatchingBackToMainThread { XCTestExpectation *expectation = [self expectationWithDescription:@"Completion should be called."]; dispatch_async(dispatch_queue_create("test", NULL), ^{ FLTThreadSafeEventChannel *channel = [[FLTThreadSafeEventChannel alloc] initWithEventChannel:OCMClassMock([FlutterEventChannel class])]; [channel setStreamHandler:OCMOCK_ANY completion:^{ [expectation fulfill]; }]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } @end
packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeEventChannelTests.m/0
{ "file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeEventChannelTests.m", "repo_id": "packages", "token_count": 1355 }
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. @import AVFoundation; @import Foundation; NS_ASSUME_NONNULL_BEGIN #pragma mark - flash mode /// Represents camera's flash mode. Mirrors `FlashMode` enum in flash_mode.dart. typedef NS_ENUM(NSInteger, FLTFlashMode) { FLTFlashModeOff, FLTFlashModeAuto, FLTFlashModeAlways, FLTFlashModeTorch, // This should never occur; it indicates an unknown value was received over // the platform channel. FLTFlashModeInvalid, }; /// Gets FLTFlashMode from its string representation. /// @param mode a string representation of the FLTFlashMode. extern FLTFlashMode FLTGetFLTFlashModeForString(NSString *mode); /// Gets AVCaptureFlashMode from FLTFlashMode. /// @param mode flash mode. extern AVCaptureFlashMode FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashMode mode); #pragma mark - exposure mode /// Represents camera's exposure mode. Mirrors ExposureMode in camera.dart. typedef NS_ENUM(NSInteger, FLTExposureMode) { FLTExposureModeAuto, FLTExposureModeLocked, // This should never occur; it indicates an unknown value was received over // the platform channel. FLTExposureModeInvalid, }; /// Gets a string representation of exposure mode. /// @param mode exposure mode extern NSString *FLTGetStringForFLTExposureMode(FLTExposureMode mode); /// Gets FLTExposureMode from its string representation. /// @param mode a string representation of the FLTExposureMode. extern FLTExposureMode FLTGetFLTExposureModeForString(NSString *mode); #pragma mark - focus mode /// Represents camera's focus mode. Mirrors FocusMode in camera.dart. typedef NS_ENUM(NSInteger, FLTFocusMode) { FLTFocusModeAuto, FLTFocusModeLocked, // This should never occur; it indicates an unknown value was received over // the platform channel. FLTFocusModeInvalid, }; /// Gets a string representation from FLTFocusMode. /// @param mode focus mode extern NSString *FLTGetStringForFLTFocusMode(FLTFocusMode mode); /// Gets FLTFocusMode from its string representation. /// @param mode a string representation of focus mode. extern FLTFocusMode FLTGetFLTFocusModeForString(NSString *mode); #pragma mark - device orientation /// Gets UIDeviceOrientation from its string representation. extern UIDeviceOrientation FLTGetUIDeviceOrientationForString(NSString *orientation); /// Gets a string representation of UIDeviceOrientation. extern NSString *FLTGetStringForUIDeviceOrientation(UIDeviceOrientation orientation); #pragma mark - resolution preset /// Represents camera's resolution present. Mirrors ResolutionPreset in camera.dart. typedef NS_ENUM(NSInteger, FLTResolutionPreset) { FLTResolutionPresetVeryLow, FLTResolutionPresetLow, FLTResolutionPresetMedium, FLTResolutionPresetHigh, FLTResolutionPresetVeryHigh, FLTResolutionPresetUltraHigh, FLTResolutionPresetMax, // This should never occur; it indicates an unknown value was received over // the platform channel. FLTResolutionPresetInvalid, }; /// Gets FLTResolutionPreset from its string representation. /// @param preset a string representation of FLTResolutionPreset. extern FLTResolutionPreset FLTGetFLTResolutionPresetForString(NSString *preset); #pragma mark - video format /// Gets VideoFormat from its string representation. extern OSType FLTGetVideoFormatFromString(NSString *videoFormatString); /// Represents image format. Mirrors ImageFileFormat in camera.dart. typedef NS_ENUM(NSInteger, FCPFileFormat) { FCPFileFormatJPEG, FCPFileFormatHEIF, FCPFileFormatInvalid, }; #pragma mark - image extension /// Gets a string representation of ImageFileFormat. extern FCPFileFormat FCPGetFileFormatFromString(NSString *fileFormatString); NS_ASSUME_NONNULL_END
packages/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.h/0
{ "file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.h", "repo_id": "packages", "token_count": 1142 }
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. #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /// Queue-specific context data to be associated with the capture session queue. extern const char* FLTCaptureSessionQueueSpecific; /// Ensures the given block to be run on the main queue. /// If caller site is already on the main queue, the block will be run /// synchronously. Otherwise, the block will be dispatched asynchronously to the /// main queue. /// @param block the block to be run on the main queue. extern void FLTEnsureToRunOnMainQueue(dispatch_block_t block); NS_ASSUME_NONNULL_END
packages/packages/camera/camera_avfoundation/ios/Classes/QueueUtils.h/0
{ "file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/QueueUtils.h", "repo_id": "packages", "token_count": 203 }
1,020
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_equals_and_hash_code_on_mutable_classes import 'resolution_preset.dart'; /// Recording media settings. /// /// Used in [CameraPlatform.createCameraWithSettings]. /// Allows to tune recorded video parameters, such as resolution, frame rate, bitrate. /// If [fps], [videoBitrate] or [audioBitrate] are passed, they must be greater than zero. class MediaSettings { /// Creates a [MediaSettings]. const MediaSettings({ this.resolutionPreset, this.fps, this.videoBitrate, this.audioBitrate, this.enableAudio = false, }) : assert(fps == null || fps > 0, 'fps must be null or greater than zero'), assert(videoBitrate == null || videoBitrate > 0, 'videoBitrate must be null or greater than zero'), assert(audioBitrate == null || audioBitrate > 0, 'audioBitrate must be null or greater than zero'); /// [ResolutionPreset] affect the quality of video recording and image capture. final ResolutionPreset? resolutionPreset; /// Rate at which frames should be captured by the camera in frames per second. final int? fps; /// The video encoding bit rate for recording. final int? videoBitrate; /// The audio encoding bit rate for recording. final int? audioBitrate; /// Controls audio presence in recorded video. final bool enableAudio; @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is MediaSettings && resolutionPreset == other.resolutionPreset && fps == other.fps && videoBitrate == other.videoBitrate && audioBitrate == other.audioBitrate && enableAudio == other.enableAudio; } @override int get hashCode => Object.hash( resolutionPreset, fps, videoBitrate, audioBitrate, enableAudio, ); @override String toString() { return 'MediaSettings{' 'resolutionPreset: $resolutionPreset, ' 'fps: $fps, ' 'videoBitrate: $videoBitrate, ' 'audioBitrate: $audioBitrate, ' 'enableAudio: $enableAudio}'; } }
packages/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart/0
{ "file_path": "packages/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart", "repo_id": "packages", "token_count": 811 }
1,021
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_platform_interface/src/types/focus_mode.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('FocusMode should contain 2 options', () { const List<FocusMode> values = FocusMode.values; expect(values.length, 2); }); test('FocusMode enum should have items in correct index', () { const List<FocusMode> values = FocusMode.values; expect(values[0], FocusMode.auto); expect(values[1], FocusMode.locked); }); test('serializeFocusMode() should serialize correctly', () { expect(serializeFocusMode(FocusMode.auto), 'auto'); expect(serializeFocusMode(FocusMode.locked), 'locked'); }); test('deserializeFocusMode() should deserialize correctly', () { expect(deserializeFocusMode('auto'), FocusMode.auto); expect(deserializeFocusMode('locked'), FocusMode.locked); }); }
packages/packages/camera/camera_platform_interface/test/types/focus_mode_test.dart/0
{ "file_path": "packages/packages/camera/camera_platform_interface/test/types/focus_mode_test.dart", "repo_id": "packages", "token_count": 317 }
1,022
// 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_web/src/types/types.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('CameraWebException', () { testWidgets('sets all properties', (WidgetTester tester) async { const int cameraId = 1; const CameraErrorCode code = CameraErrorCode.notFound; const String description = 'The camera is not found.'; final CameraWebException exception = CameraWebException(cameraId, code, description); expect(exception.cameraId, equals(cameraId)); expect(exception.code, equals(code)); expect(exception.description, equals(description)); }); testWidgets('toString includes all properties', (WidgetTester tester) async { const int cameraId = 2; const CameraErrorCode code = CameraErrorCode.notReadable; const String description = 'The camera is not readable.'; final CameraWebException exception = CameraWebException(cameraId, code, description); expect( exception.toString(), equals('CameraWebException($cameraId, $code, $description)'), ); }); }); }
packages/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart/0
{ "file_path": "packages/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart", "repo_id": "packages", "token_count": 469 }
1,023
// 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'; /// Metadata used along the camera description /// to store additional web-specific camera details. @immutable class CameraMetadata { /// Creates a new instance of [CameraMetadata] /// with the given [deviceId] and [facingMode]. const CameraMetadata({required this.deviceId, required this.facingMode}); /// Uniquely identifies the camera device. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/deviceId final String deviceId; /// Describes the direction the camera is facing towards. /// May be `user`, `environment`, `left`, `right` /// or null if the facing mode is not available. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings/facingMode final String? facingMode; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is CameraMetadata && other.deviceId == deviceId && other.facingMode == facingMode; } @override int get hashCode => Object.hash(deviceId.hashCode, facingMode.hashCode); }
packages/packages/camera/camera_web/lib/src/types/camera_metadata.dart/0
{ "file_path": "packages/packages/camera/camera_web/lib/src/types/camera_metadata.dart", "repo_id": "packages", "token_count": 389 }
1,024
// 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_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_ #include <flutter/flutter_view.h> #include <flutter/method_channel.h> #include <flutter/plugin_registrar_windows.h> #include <flutter/standard_method_codec.h> #include <functional> #include "camera.h" #include "capture_controller.h" #include "capture_controller_listener.h" namespace camera_windows { using flutter::MethodResult; namespace test { namespace { // Forward declaration of test class. class MockCameraPlugin; } // namespace } // namespace test class CameraPlugin : public flutter::Plugin, public VideoCaptureDeviceEnumerator { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); CameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger); // Creates a plugin instance with the given CameraFactory instance. // Exists for unit testing with mock implementations. CameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, std::unique_ptr<CameraFactory> camera_factory); virtual ~CameraPlugin(); // Disallow copy and move. CameraPlugin(const CameraPlugin&) = delete; CameraPlugin& operator=(const CameraPlugin&) = delete; // Called when a method is called on plugin channel. void HandleMethodCall(const flutter::MethodCall<>& method_call, std::unique_ptr<MethodResult<>> result); private: // Loops through cameras and returns camera // with matching device_id or nullptr. Camera* GetCameraByDeviceId(std::string& device_id); // Loops through cameras and returns camera // with matching camera_id or nullptr. Camera* GetCameraByCameraId(int64_t camera_id); // Disposes camera by camera id. void DisposeCameraByCameraId(int64_t camera_id); // Enumerates video capture devices. bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count) override; // Handles availableCameras method calls. // Enumerates video capture devices and // returns list of available camera devices. void AvailableCamerasMethodHandler( std::unique_ptr<flutter::MethodResult<>> result); // Handles create method calls. // Creates camera and initializes capture controller for requested device. // Stores result object to be handled after request is processed. void CreateMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles initialize method calls. // Requests existing camera controller to start preview. // Stores result object to be handled after request is processed. void InitializeMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles takePicture method calls. // Requests existing camera controller to take photo. // Stores result object to be handled after request is processed. void TakePictureMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles startVideoRecording method calls. // Requests existing camera controller to start recording. // Stores result object to be handled after request is processed. void StartVideoRecordingMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles stopVideoRecording method calls. // Requests existing camera controller to stop recording. // Stores result object to be handled after request is processed. void StopVideoRecordingMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles pausePreview method calls. // Requests existing camera controller to pause recording. // Stores result object to be handled after request is processed. void PausePreviewMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles resumePreview method calls. // Requests existing camera controller to resume preview. // Stores result object to be handled after request is processed. void ResumePreviewMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles dsipose method calls. // Disposes camera if exists. void DisposeMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); std::unique_ptr<CameraFactory> camera_factory_; flutter::TextureRegistrar* texture_registrar_; flutter::BinaryMessenger* messenger_; std::vector<std::unique_ptr<Camera>> cameras_; friend class camera_windows::test::MockCameraPlugin; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_
packages/packages/camera/camera_windows/windows/camera_plugin.h/0
{ "file_path": "packages/packages/camera/camera_windows/windows/camera_plugin.h", "repo_id": "packages", "token_count": 1720 }
1,025
// 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_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_ #include <mfapi.h> #include <mfcaptureengine.h> #include <wrl/client.h> #include <memory> #include <string> namespace camera_windows { using Microsoft::WRL::ComPtr; enum class RecordingType { // Camera is not recording. kNone, // Recording continues until it is stopped with a separate stop command. kContinuous, // Recording stops automatically after requested record time is passed. kTimed }; // States that the record handler can be in. // // When created, the handler starts in |kNotStarted| state and transtions in // sequential order through the states. enum class RecordState { kNotStarted, kStarting, kRunning, kStopping }; // Handler for video recording via the camera. // // Handles record sink initialization and manages the state of video recording. class RecordHandler { public: RecordHandler(bool record_audio) : record_audio_(record_audio) {} virtual ~RecordHandler() = default; // Prevent copying. RecordHandler(RecordHandler const&) = delete; RecordHandler& operator=(RecordHandler const&) = delete; // Initializes record sink and requests capture engine to start recording. // // Sets record state to: starting. // // file_path: A string that hold file path for video capture. // max_duration: A int64 value of maximun recording duration. // If value is -1 video recording is considered as // a continuous recording. // capture_engine: A pointer to capture engine instance. Used to start // the actual recording. // base_media_type: A pointer to base media type used as a base // for the actual video capture media type. HRESULT StartRecord(const std::string& file_path, int64_t max_duration, IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); // Stops existing recording. // // capture_engine: A pointer to capture engine instance. Used to stop // the ongoing recording. HRESULT StopRecord(IMFCaptureEngine* capture_engine); // Set the record handler recording state to: running. void OnRecordStarted(); // Resets the record handler state and // sets recording state to: not started. void OnRecordStopped(); // Returns true if recording type is continuous recording. bool IsContinuousRecording() const { return type_ == RecordingType::kContinuous; } // Returns true if recording type is timed recording. bool IsTimedRecording() const { return type_ == RecordingType::kTimed; } // Returns true if new recording can be started. bool CanStart() const { return recording_state_ == RecordState::kNotStarted; } // Returns true if recording can be stopped. bool CanStop() const { return recording_state_ == RecordState::kRunning; } // Returns the filesystem path of the video recording. std::string GetRecordPath() const { return file_path_; } // Returns the duration of the video recording in microseconds. uint64_t GetRecordedDuration() const { return recording_duration_us_; } // Calculates new recording time from capture timestamp. void UpdateRecordingTime(uint64_t timestamp); // Returns true if recording time has exceeded the maximum duration for timed // recordings. bool ShouldStopTimedRecording() const; private: // Initializes record sink for video file capture. HRESULT InitRecordSink(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); bool record_audio_ = false; int64_t max_video_duration_ms_ = -1; int64_t recording_start_timestamp_us_ = -1; uint64_t recording_duration_us_ = 0; std::string file_path_; RecordState recording_state_ = RecordState::kNotStarted; RecordingType type_ = RecordingType::kNone; ComPtr<IMFCaptureRecordSink> record_sink_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_
packages/packages/camera/camera_windows/windows/record_handler.h/0
{ "file_path": "packages/packages/camera/camera_windows/windows/record_handler.h", "repo_id": "packages", "token_count": 1315 }
1,026
name: cross_file_example description: Demonstrates how to use cross files. publish_to: none environment: sdk: ^3.1.0 dependencies: cross_file: # When depending on this package from a real application you should use: # cross_file: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ dev_dependencies: test: ^1.24.0
packages/packages/cross_file/example/pubspec.yaml/0
{ "file_path": "packages/packages/cross_file/example/pubspec.yaml", "repo_id": "packages", "token_count": 174 }
1,027
# e2e (deprecated) This package has been moved to [`integration_test` in the Flutter SDK](https://github.com/flutter/flutter/tree/master/packages/integration_test).
packages/packages/e2e/README.md/0
{ "file_path": "packages/packages/e2e/README.md", "repo_id": "packages", "token_count": 53 }
1,028
// 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 android.view.View; import androidx.test.espresso.UiController; 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.gson.annotations.Expose; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * An action that scrolls the Scrollable ancestor of the widget until the widget is completely * visible. */ public final class FlutterScrollToAction implements WidgetAction { @Override public Future<Void> perform( @Nullable WidgetMatcher targetWidget, @Nonnull View flutterView, @Nonnull FlutterTestingProtocol flutterTestingProtocol, @Nonnull UiController androidUiController) { return flutterTestingProtocol.perform(targetWidget, new ScrollIntoViewAction()); } @Override public String toString() { return "scrollTo"; } static class ScrollIntoViewAction extends SyntheticAction { @Expose private final double alignment; public ScrollIntoViewAction() { this(0.0); } public ScrollIntoViewAction(double alignment) { super("scrollIntoView"); this.alignment = alignment; } } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterScrollToAction.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterScrollToAction.java", "repo_id": "packages", "token_count": 488 }
1,029
// 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.common; import static com.google.common.base.Preconditions.checkNotNull; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * A simple implementation of a time duration, supposed to be used within the Espresso-Flutter * library. * * <p>This class is immutable. */ public final class Duration { private final long quantity; private final TimeUnit unit; /** * Initializes a Duration instance. * * @param quantity the amount of time in the given unit. * @param unit the time unit. Cannot be null. */ public Duration(long quantity, TimeUnit unit) { this.quantity = quantity; this.unit = checkNotNull(unit, "Time unit cannot be null."); } /** Returns the amount of time. */ public long getQuantity() { return quantity; } /** Returns the time unit. */ public TimeUnit getUnit() { return unit; } /** Returns the amount of time in milliseconds. */ public long toMillis() { return TimeUnit.MILLISECONDS.convert(quantity, unit); } /** * Returns a new Duration instance that adds this instance to the given {@code duration}. If the * given {@code duration} is null, this method simply returns this instance. */ public Duration plus(@Nullable Duration duration) { if (duration == null) { return this; } long add = unit.convert(duration.quantity, duration.unit); long newQuantity = quantity + add; return new Duration(newQuantity, unit); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/common/Duration.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/common/Duration.java", "repo_id": "packages", "token_count": 508 }
1,030
// 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 static com.google.common.base.Preconditions.checkNotNull; import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcResponse; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.annotations.Expose; import java.util.List; import java.util.Objects; /** * Represents a response of a <a * href="https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#getvm">getVM()</a> * request. */ public class GetVmResponse { private static final Gson gson = new Gson(); @Expose private List<Isolate> isolates; private GetVmResponse() {} /** * Builds the {@code GetVmResponse} out of the JSON-RPC response. * * @param jsonRpcResponse the JSON-RPC response. Cannot be {@code null}. * @return a {@code GetVmResponse} instance that's parsed out from the JSON-RPC response. */ public static GetVmResponse fromJsonRpcResponse(JsonRpcResponse jsonRpcResponse) { checkNotNull(jsonRpcResponse, "The JSON-RPC response cannot be null."); if (jsonRpcResponse.getResult() == null) { throw new FlutterProtocolException( String.format( "Error occurred during retrieving Dart VM info. Response received: %s.", jsonRpcResponse)); } try { return gson.fromJson(jsonRpcResponse.getResult(), GetVmResponse.class); } catch (JsonSyntaxException e) { throw new FlutterProtocolException( String.format( "Error occurred during retrieving Dart VM info. Response received: %s.", jsonRpcResponse), e); } } /** Returns the number of isolates living in the Dart VM. */ public int getIsolateNum() { return isolates == null ? 0 : isolates.size(); } /** Returns the Dart isolate listed at the given index. */ public Isolate getIsolate(int index) { if (isolates == null) { return null; } else if (index < 0 || index >= isolates.size()) { throw new IllegalArgumentException( String.format( "Illegal Dart isolate index: %d. Should be in the range [%d, %d]", index, 0, isolates.size() - 1)); } else { return isolates.get(index); } } @Override public String toString() { return gson.toJson(this); } /** Represents a Dart isolate. */ static class Isolate { @Expose private String id; @Expose private boolean runnable; @Expose private List<String> extensionRpcList; Isolate() {} Isolate(String id, boolean runnable) { this.id = id; this.runnable = runnable; } /** Gets the Dart isolate ID. */ public String getId() { return id; } /** * Checks whether the Dart isolate is in a runnable state. True if it's runnable, false * otherwise. */ public boolean isRunnable() { return runnable; } /** Gets the list of extension RPCs registered at this Dart isolate. Could be {@code null}. */ public List<String> getExtensionRpcList() { return extensionRpcList; } @Override public boolean equals(Object obj) { if (obj instanceof Isolate) { Isolate isolate = (Isolate) obj; return Objects.equals(isolate.id, this.id) && Objects.equals(isolate.runnable, this.runnable) && Objects.equals(isolate.extensionRpcList, this.extensionRpcList); } else { return false; } } @Override public int hashCode() { return Objects.hash(id, runnable, extensionRpcList); } } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java", "repo_id": "packages", "token_count": 1426 }
1,031
// 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 com.google.common.annotations.Beta; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Represents a Flutter widget, containing all the properties that are accessible in Espresso. * * <p>Note, this class should typically be decoded from the Flutter testing protocol. Users of * Espresso testing framework should rarely have the needs to build their own {@link WidgetInfo} * instance. * * <p>Also, the current implementation is hard-coded and potentially only works with a limited set * of {@code WidgetMatchers}. Later, we might consider codegen of representations for Flutter * widgets for extensibility. */ @Beta public class WidgetInfo { /** A String representation of a Flutter widget's ValueKey. */ @Nullable private final String valueKey; /** A String representation of the runtime type of the widget. */ private final String runtimeType; /** The widget's text property. */ @Nullable private final String text; /** The widget's tooltip property. */ @Nullable private final String tooltip; WidgetInfo( @Nullable String valueKey, String runtimeType, @Nullable String text, @Nullable String tooltip) { this.valueKey = valueKey; this.runtimeType = checkNotNull(runtimeType, "RuntimeType cannot be null."); this.text = text; this.tooltip = tooltip; } /** Returns a String representation of the Flutter widget's ValueKey. Could be null. */ @Nullable public String getValueKey() { return valueKey; } /** Returns a String representation of the runtime type of the Flutter widget. */ @Nonnull public String getType() { return runtimeType; } /** Returns the widget's 'text' property. Will be null for widgets without a 'text' property. */ @Nullable public String getText() { return text; } /** * Returns the widget's 'tooltip' property. Will be null for widgets without a 'tooltip' property. */ @Nullable public String getTooltip() { return tooltip; } @Override public boolean equals(Object obj) { if (obj instanceof WidgetInfo) { WidgetInfo widget = (WidgetInfo) obj; return Objects.equals(widget.valueKey, this.valueKey) && Objects.equals(widget.runtimeType, this.runtimeType) && Objects.equals(widget.text, this.text) && Objects.equals(widget.tooltip, this.tooltip); } else { return false; } } @Override public int hashCode() { return Objects.hash(valueKey, runtimeType, text, tooltip); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Widget ["); sb.append("runtimeType=").append(runtimeType).append(","); if (valueKey != null) { sb.append("valueKey=").append(valueKey).append(","); } if (text != null) { sb.append("text=").append(text).append(","); } if (tooltip != null) { sb.append("tooltip=").append(tooltip).append(","); } sb.append("]"); return sb.toString(); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java", "repo_id": "packages", "token_count": 1070 }
1,032
name: example description: Example for file_selector_ios implementation. publish_to: 'none' version: 1.0.0 environment: sdk: ^3.2.3 flutter: ">=3.16.6" dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 file_selector_ios: # When depending on this package from a real application you should use: # file_selector_ios: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: .. file_selector_platform_interface: ^2.2.0 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/file_selector/file_selector_ios/example/pubspec.yaml/0
{ "file_path": "packages/packages/file_selector/file_selector_ios/example/pubspec.yaml", "repo_id": "packages", "token_count": 314 }
1,033
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', objcHeaderOut: 'ios/Classes/messages.g.h', objcSourceOut: 'ios/Classes/messages.g.m', objcOptions: ObjcOptions( prefix: 'FFS', ), copyrightHeader: 'pigeons/copyright.txt', )) class FileSelectorConfig { FileSelectorConfig( {this.utis = const <String?>[], this.allowMultiSelection = false}); List<String?> utis; bool allowMultiSelection; } @HostApi(dartHostTestHandler: 'TestFileSelectorApi') abstract class FileSelectorApi { @async @ObjCSelector('openFileSelectorWithConfig:') List<String> openFile(FileSelectorConfig config); }
packages/packages/file_selector/file_selector_ios/pigeons/messages.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_ios/pigeons/messages.dart", "repo_id": "packages", "token_count": 318 }
1,034
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'get_directory_page.dart'; import 'get_multiple_directories_page.dart'; import 'home_page.dart'; import 'open_image_page.dart'; import 'open_multiple_images_page.dart'; import 'open_text_page.dart'; import 'save_text_page.dart'; void main() { runApp(const MyApp()); } /// MyApp is the Main Application. class MyApp extends StatelessWidget { /// Default Constructor const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'File Selector Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: const HomePage(), routes: <String, WidgetBuilder>{ '/open/image': (BuildContext context) => const OpenImagePage(), '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), '/multi-directories': (BuildContext context) => const GetMultipleDirectoriesPage() }, ); } }
packages/packages/file_selector/file_selector_linux/example/lib/main.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/example/lib/main.dart", "repo_id": "packages", "token_count": 503 }
1,035
// 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 "include/file_selector_linux/file_selector_plugin.h" #include <flutter_linux/flutter_linux.h> #include <gtk/gtk.h> #include "file_selector_plugin_private.h" // From file_selector_linux.dart const char kChannelName[] = "plugins.flutter.dev/file_selector_linux"; const char kOpenFileMethod[] = "openFile"; const char kGetSavePathMethod[] = "getSavePath"; const char kGetDirectoryPathMethod[] = "getDirectoryPath"; const char kAcceptedTypeGroupsKey[] = "acceptedTypeGroups"; const char kConfirmButtonTextKey[] = "confirmButtonText"; const char kInitialDirectoryKey[] = "initialDirectory"; const char kMultipleKey[] = "multiple"; const char kSuggestedNameKey[] = "suggestedName"; const char kTypeGroupLabelKey[] = "label"; const char kTypeGroupExtensionsKey[] = "extensions"; const char kTypeGroupMimeTypesKey[] = "mimeTypes"; // Errors const char kBadArgumentsError[] = "Bad Arguments"; const char kNoScreenError[] = "No Screen"; struct _FlFileSelectorPlugin { GObject parent_instance; FlPluginRegistrar* registrar; // Connection to Flutter engine. FlMethodChannel* channel; }; G_DEFINE_TYPE(FlFileSelectorPlugin, fl_file_selector_plugin, G_TYPE_OBJECT) // Converts a type group received from Flutter into a GTK file filter. static GtkFileFilter* type_group_to_filter(FlValue* value) { g_autoptr(GtkFileFilter) filter = gtk_file_filter_new(); FlValue* label = fl_value_lookup_string(value, kTypeGroupLabelKey); if (label != nullptr && fl_value_get_type(label) == FL_VALUE_TYPE_STRING) { gtk_file_filter_set_name(filter, fl_value_get_string(label)); } FlValue* extensions = fl_value_lookup_string(value, kTypeGroupExtensionsKey); if (extensions != nullptr && fl_value_get_type(extensions) == FL_VALUE_TYPE_LIST) { for (size_t i = 0; i < fl_value_get_length(extensions); i++) { FlValue* v = fl_value_get_list_value(extensions, i); const gchar* pattern = fl_value_get_string(v); gtk_file_filter_add_pattern(filter, pattern); } } FlValue* mime_types = fl_value_lookup_string(value, kTypeGroupMimeTypesKey); if (mime_types != nullptr && fl_value_get_type(mime_types) == FL_VALUE_TYPE_LIST) { for (size_t i = 0; i < fl_value_get_length(mime_types); i++) { FlValue* v = fl_value_get_list_value(mime_types, i); const gchar* pattern = fl_value_get_string(v); gtk_file_filter_add_mime_type(filter, pattern); } } return GTK_FILE_FILTER(g_object_ref(filter)); } // Creates a GtkFileChooserNative for the given method call details. static GtkFileChooserNative* create_dialog( GtkWindow* window, GtkFileChooserAction action, const gchar* title, const gchar* default_confirm_button_text, FlValue* properties) { const gchar* confirm_button_text = default_confirm_button_text; FlValue* value = fl_value_lookup_string(properties, kConfirmButtonTextKey); if (value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_STRING) confirm_button_text = fl_value_get_string(value); g_autoptr(GtkFileChooserNative) dialog = GTK_FILE_CHOOSER_NATIVE(gtk_file_chooser_native_new( title, window, action, confirm_button_text, "_Cancel")); value = fl_value_lookup_string(properties, kMultipleKey); if (value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_BOOL) { gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), fl_value_get_bool(value)); } value = fl_value_lookup_string(properties, kInitialDirectoryKey); if (value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_STRING) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), fl_value_get_string(value)); } value = fl_value_lookup_string(properties, kSuggestedNameKey); if (value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_STRING) { gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), fl_value_get_string(value)); } value = fl_value_lookup_string(properties, kAcceptedTypeGroupsKey); if (value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_LIST) { for (size_t i = 0; i < fl_value_get_length(value); i++) { FlValue* type_group = fl_value_get_list_value(value, i); GtkFileFilter* filter = type_group_to_filter(type_group); if (filter == nullptr) { return nullptr; } gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); } } return GTK_FILE_CHOOSER_NATIVE(g_object_ref(dialog)); } // TODO(stuartmorgan): Move this logic back into method_call_cb once // https://github.com/flutter/flutter/issues/88724 is fixed, and test // through the public API instead. This only exists to move as much // logic as possible behind the private entry point used by unit tests. GtkFileChooserNative* create_dialog_for_method(GtkWindow* window, const gchar* method, FlValue* properties) { if (strcmp(method, kOpenFileMethod) == 0) { return create_dialog(window, GTK_FILE_CHOOSER_ACTION_OPEN, "Open File", "_Open", properties); } else if (strcmp(method, kGetDirectoryPathMethod) == 0) { return create_dialog(window, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "Choose Directory", "_Open", properties); } else if (strcmp(method, kGetSavePathMethod) == 0) { return create_dialog(window, GTK_FILE_CHOOSER_ACTION_SAVE, "Save File", "_Save", properties); } return nullptr; } // Shows the requested dialog type. static FlMethodResponse* show_dialog(FlFileSelectorPlugin* self, const gchar* method, FlValue* properties, bool return_list) { if (fl_value_get_type(properties) != FL_VALUE_TYPE_MAP) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Argument map missing or malformed", nullptr)); } FlView* view = fl_plugin_registrar_get_view(self->registrar); if (view == nullptr) { return FL_METHOD_RESPONSE( fl_method_error_response_new(kNoScreenError, nullptr, nullptr)); } GtkWindow* window = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(view))); g_autoptr(GtkFileChooserNative) dialog = create_dialog_for_method(window, method, properties); if (dialog == nullptr) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Unable to create dialog from arguments", nullptr)); } gint response = gtk_native_dialog_run(GTK_NATIVE_DIALOG(dialog)); g_autoptr(FlValue) result = nullptr; if (response == GTK_RESPONSE_ACCEPT) { if (return_list) { result = fl_value_new_list(); g_autoptr(GSList) filenames = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); for (GSList* link = filenames; link != nullptr; link = link->next) { g_autofree gchar* filename = static_cast<gchar*>(link->data); fl_value_append_take(result, fl_value_new_string(filename)); } } else { g_autofree gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); result = fl_value_new_string(filename); } } return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } // Called when a method call is received from Flutter. static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlFileSelectorPlugin* self = FL_FILE_SELECTOR_PLUGIN(user_data); const gchar* method = fl_method_call_get_name(method_call); FlValue* args = fl_method_call_get_args(method_call); g_autoptr(FlMethodResponse) response = nullptr; if (strcmp(method, kOpenFileMethod) == 0 || strcmp(method, kGetDirectoryPathMethod) == 0) { response = show_dialog(self, method, args, true); } else if (strcmp(method, kGetSavePathMethod) == 0) { response = show_dialog(self, method, args, false); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } g_autoptr(GError) error = nullptr; if (!fl_method_call_respond(method_call, response, &error)) g_warning("Failed to send method call response: %s", error->message); } static void fl_file_selector_plugin_dispose(GObject* object) { FlFileSelectorPlugin* self = FL_FILE_SELECTOR_PLUGIN(object); g_clear_object(&self->registrar); g_clear_object(&self->channel); G_OBJECT_CLASS(fl_file_selector_plugin_parent_class)->dispose(object); } static void fl_file_selector_plugin_class_init( FlFileSelectorPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_file_selector_plugin_dispose; } static void fl_file_selector_plugin_init(FlFileSelectorPlugin* self) {} FlFileSelectorPlugin* fl_file_selector_plugin_new( FlPluginRegistrar* registrar) { FlFileSelectorPlugin* self = FL_FILE_SELECTOR_PLUGIN( g_object_new(fl_file_selector_plugin_get_type(), nullptr)); self->registrar = FL_PLUGIN_REGISTRAR(g_object_ref(registrar)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); self->channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), kChannelName, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(self->channel, method_call_cb, g_object_ref(self), g_object_unref); return self; } void file_selector_plugin_register_with_registrar( FlPluginRegistrar* registrar) { FlFileSelectorPlugin* plugin = fl_file_selector_plugin_new(registrar); g_object_unref(plugin); }
packages/packages/file_selector/file_selector_linux/linux/file_selector_plugin.cc/0
{ "file_path": "packages/packages/file_selector/file_selector_linux/linux/file_selector_plugin.cc", "repo_id": "packages", "token_count": 3960 }
1,036
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select a directory using `getDirectoryPath`, /// then displays the selected directory in a dialog. class GetDirectoryPage extends StatelessWidget { /// Default Constructor const GetDirectoryPage({super.key}); Future<void> _getDirectoryPath(BuildContext context) async { const String confirmButtonText = 'Choose'; final String? directoryPath = await FileSelectorPlatform.instance.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, ), child: const Text('Press to ask user to choose a directory'), onPressed: () => _getDirectoryPath(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog. class TextDisplay extends StatelessWidget { /// Creates a `TextDisplay`. const TextDisplay(this.directoryPath, {super.key}); /// The path selected in the dialog. 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_macos/example/lib/get_directory_page.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart", "repo_id": "packages", "token_count": 907 }
1,037
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.3), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:file_selector_macos/src/messages.g.dart'; class _TestFileSelectorApiCodec extends StandardMessageCodec { const _TestFileSelectorApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is AllowedTypes) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is OpenPanelOptions) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is SavePanelOptions) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return AllowedTypes.decode(readValue(buffer)!); case 129: return OpenPanelOptions.decode(readValue(buffer)!); case 130: return SavePanelOptions.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestFileSelectorApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestFileSelectorApiCodec(); /// Shows an open panel with the given [options], returning the list of /// selected paths. /// /// An empty list corresponds to a cancelled selection. Future<List<String?>> displayOpenPanel(OpenPanelOptions options); /// Shows a save panel with the given [options], returning the selected path. /// /// A null return corresponds to a cancelled save. Future<String?> displaySavePanel(SavePanelOptions options); static void setup(TestFileSelectorApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FileSelectorApi.displayOpenPanel', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.FileSelectorApi.displayOpenPanel was null.'); final List<Object?> args = (message as List<Object?>?)!; final OpenPanelOptions? arg_options = (args[0] as OpenPanelOptions?); assert(arg_options != null, 'Argument for dev.flutter.pigeon.FileSelectorApi.displayOpenPanel was null, expected non-null OpenPanelOptions.'); final List<String?> output = await api.displayOpenPanel(arg_options!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FileSelectorApi.displaySavePanel', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.FileSelectorApi.displaySavePanel was null.'); final List<Object?> args = (message as List<Object?>?)!; final SavePanelOptions? arg_options = (args[0] as SavePanelOptions?); assert(arg_options != null, 'Argument for dev.flutter.pigeon.FileSelectorApi.displaySavePanel was null, expected non-null SavePanelOptions.'); final String? output = await api.displaySavePanel(arg_options!); return <Object?>[output]; }); } } } }
packages/packages/file_selector/file_selector_macos/test/messages_test.g.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_macos/test/messages_test.g.dart", "repo_id": "packages", "token_count": 1783 }
1,038