text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
## 13.2.1
- Updates minimum supported SDK version to Flutter 3.16/Dart 3.2.
- Fixes memory leaks.
## 13.2.0
- Exposes full `Uri` on `GoRouterState` in `GoRouterRedirect`
## 13.1.0
- Adds `topRoute` to `GoRouterState`
- Adds `lastOrNull` to `RouteMatchList`
## 13.0.1
* Fixes new lint warnings.
## 13.0.0
- Refactors `RouteMatchList` and imperative APIs.
- **BREAKING CHANGE**:
- RouteMatchList structure changed.
- Matching logic updated.
## 12.1.3
* Fixes a typo in `navigation.md`.
## 12.1.2
* Fixes an incorrect use of `extends` for Dart 3 compatibility.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 12.1.1
- Retains query parameters during refresh and first redirect.
## 12.1.0
- Adds an ability to add a custom codec for serializing/deserializing extra.
## 12.0.3
- Fixes crashes when dynamically updates routing tables with named routes.
## 12.0.2
- Fixes the problem that pathParameters is null in redirect when the Router is recreated.
## 12.0.1
- Fixes deep-link with no path on cold start.
## 12.0.0
- Adds ability to dynamically update routing table.
- **BREAKING CHANGE**:
- The function signature of constructor of `RouteConfiguration` is updated.
- Adds a required `matchedPath` named parameter to `RouteMatch.match`.
## 11.1.4
- Fixes missing parameters in the type-safe routes topic documentation.
## 11.1.3
- Fixes missing state.extra in onException().
## 11.1.2
- Fixes a bug where the known routes and initial route were logged even when `debugLogDiagnostics` was set to `false`.
## 11.1.1
- Fixes a missing `{@end-tool}` doc directive tag for `GoRoute.name`.
## 11.1.0
- Adds optional parameter `overridePlatformDefaultLocation` to override initial route set by platform.
## 11.0.1
- Fixes the Android back button ignores top level route's onExit.
## 11.0.0
- Fixes the GoRouter.goBranch so that it doesn't reset extra to null if extra is not serializable.
- **BREAKING CHANGE**:
- Updates the function signature of `GoRouteInformationProvider.restore`.
- Adds `NavigationType.restore` to `NavigationType` enum.
## 10.2.0
- Adds `onExit` to GoRoute.
## 10.1.4
- Fixes RouteInformationParser that does not restore full RouteMatchList if
the optionURLReflectsImperativeAPIs is set.
## 10.1.3
- Fixes an issue in the documentation that was using `state.queryParameters` instead of `state.uri.queryParameters`.
## 10.1.2
* Adds pub topics to package metadata.
## 10.1.1
- Fixes mapping from `Page` to `RouteMatch`s.
- Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 10.1.0
- Supports setting `requestFocus`.
## 10.0.0
- **BREAKING CHANGE**:
- Replaces location, queryParameters, and queryParametersAll in GoRouterState with Uri.
- See [Migrating to 10.0.0](https://flutter.dev/go/go-router-v10-breaking-changes) or
run `dart fix --apply` to fix the breakages.
## 9.1.1
- Fixes a link in error handling documentation.
## 9.1.0
- Adds the parentNavigatorKey parameter to ShellRouteData and StatefulShellRouteData.
- Fixes a typo in docs for `StatefulShellRoute.indexedStack(...)`.
- Cleans some typos in the documentation and asserts.
## 9.0.3
- Adds helpers for go_router_builder for StatefulShellRoute support
## 9.0.2
- Exposes package-level privates.
## 9.0.1
- Allows redirect only GoRoute to be part of RouteMatchList.
## 9.0.0
- **BREAKING CHANGE**:
- Removes GoRouter.location. Use GoRouterState.of().location instead.
- GoRouter does not `extends` ChangeNotifier.
- [Migration guide](https://flutter.dev/go/go-router-v9-breaking-changes)
- Reduces excessive rebuilds due to inherited look up.
## 8.2.0
- Adds onException to GoRouter constructor.
## 8.1.0
- Adds parent navigator key to ShellRoute and StatefulShellRoute.
## 8.0.5
- Fixes a bug that GoRouterState in top level redirect doesn't contain complete data.
## 8.0.4
- Updates documentations around `GoRouter.of`, `GoRouter.maybeOf`, and `BuildContext` extension.
## 8.0.3
- Makes namedLocation and route name related APIs case sensitive.
## 8.0.2
- Fixes a bug in `debugLogDiagnostics` to support StatefulShellRoute.
## 8.0.1
- Fixes a link for an example in `path` documentation.
documentation.
## 8.0.0
- **BREAKING CHANGE**:
- Imperatively pushed GoRoute no longer change URL.
- Browser backward and forward button respects imperative route operations.
- Refactors the route parsing pipeline.
## 7.1.1
- Removes obsolete null checks on non-nullable values.
## 7.1.0
- Introduces `StatefulShellRoute` to support using separate navigators for child routes as well as preserving state in each navigation tree (flutter/flutter#99124).
- Updates documentation for `pageBuilder` and `builder` fields of `ShellRoute`, to more correctly
describe the meaning of the child argument in the builder functions.
- Adds support for restorationId to ShellRoute (and StatefulShellRoute).
## 7.0.2
- Fixes `BuildContext` extension method `replaceNamed` to correctly pass `pathParameters` and `queryParameters`.
## 7.0.1
- Adds a workaround for the `dart fix --apply` issue, https://github.com/dart-lang/sdk/issues/52233.
## 7.0.0
- **BREAKING CHANGE**:
- For the below changes, run `dart fix --apply` to automatically migrate your code.
- `GoRouteState.subloc` has been renamed to `GoRouteState.matchedLocation`.
- `GoRouteState.params` has been renamed to `GoRouteState.pathParameters`.
- `GoRouteState.fullpath` has been renamed to `GoRouteState.fullPath`.
- `GoRouteState.queryParams` has been renamed to `GoRouteState.queryParameters`.
- `params` and `queryParams` in `GoRouteState.namedLocation` have been renamed to `pathParameters` and `queryParameters`.
- `params` and `queryParams` in `GoRouter`'s `namedLocation`, `pushNamed`, `pushReplacementNamed`
`replaceNamed` have been renamed to `pathParameters` and `queryParameters`.
- For the below changes, please follow the [migration guide](https://docs.google.com/document/d/10Xbpifbs4E-zh6YE5akIO8raJq_m3FIXs6nUGdOspOg).
- `params` and `queryParams` in `BuildContext`'s `namedLocation`, `pushNamed`, `pushReplacementNamed`
`replaceNamed` have been renamed to `pathParameters` and `queryParameters`.
- Cleans up API and makes RouteMatchList immutable.
## 6.5.9
- Removes navigator keys from `GoRouteData` and `ShellRouteData`.
## 6.5.8
- Adds name parameter to `TypedGoRoute`
## 6.5.7
- Fixes a bug that go_router would crash if `GoRoute.pageBuilder` depends on `InheritedWidget`s.
## 6.5.6
- Fixes an issue where ShellRoute routes were not logged when debugLogDiagnostic was enabled.
## 6.5.5
- Fixes an issue when popping pageless route would accidentally complete imperative page.
## 6.5.4
- Removes navigator keys from `TypedGoRoute` and `TypedShellRoute`.
## 6.5.3
- Fixes redirect being called with an empty location for unknown routes.
## 6.5.2
- NoTransitionPage now has an instant reverse transition.
## 6.5.1
- Fixes an issue where the params are removed after popping.
## 6.5.0
- Supports returning values on pop.
## 6.4.1
- Adds `initialExtra` to **GoRouter** to pass extra data alongside `initialRoute`.
## 6.4.0
- Adds `replace` method to that replaces the current route with a new one and keeps the same page key. This is useful for when you want to update the query params without changing the page key ([#115902](https://github.com/flutter/flutter/issues/115902)).
## 6.3.0
- Aligns Dart and Flutter SDK constraints.
- Updates compileSdkVersion to 33.
- Updates example app to iOS 11.
- Adds `navigatorKey` to `TypedShellRoute`
- Adds `parentNavigatorKey` to `TypedGoRoute`
- Updates documentation in matching methods.
## 6.2.0
- Exports supertypes in route_data.dart library.
## 6.1.0
- Adds `GoRouter.maybeOf` to get the closest `GoRouter` from the context, if there is any.
## 6.0.10
- Adds helpers for go_router_builder for ShellRoute support
## 6.0.9
- Fixes deprecation message for `GoRouterState.namedLocation`
## 6.0.8
- Adds support for Iterables, Lists and Sets in query params for TypedGoRoute. [#108437](https://github.com/flutter/flutter/issues/108437).
## 6.0.7
- Add observers parameter to the ShellRoute that will be passed to the nested Navigator.
- Use `HeroControllerScope` for nested Navigator that fixes Hero Widgets not animating in Nested Navigator.
## 6.0.6
- Adds `reverseTransitionDuration` to `CustomTransitionPage`
## 6.0.5
- Fixes [unnecessary_null_comparison](https://dart.dev/lints/unnecessary_null_checks) lint warnings.
## 6.0.4
- Fixes redirection info log.
## 6.0.3
- Makes `CustomTransitionPage.barrierDismissible` work
## 6.0.2
- Fixes missing result on pop in go_router extension.
## 6.0.1
- Fixes crashes when popping navigators manually.
- Fixes trailing slashes after pops.
## 6.0.0
- **BREAKING CHANGE**
- `GoRouteData`'s `redirect` now takes 2 parameters `BuildContext context, GoRouterState state`.
- `GoRouteData`'s `build` now takes 2 parameters `BuildContext context, GoRouterState state`.
- `GoRouteData`'s `buildPageWithState` has been removed and replaced by `buildPage` with now takes 2 parameters `BuildContext context, GoRouterState state`.
- `replace` from `GoRouter`, `GoRouterDelegate` and `GoRouterHelper` has been renamed into `pushReplacement`.
- `replaceNamed` from `GoRouter`, `GoRouterDelegate` and `GoRouterHelper` has been renamed into `pushReplacementNamed`.
- [go_router v6 migration guide](https://flutter.dev/go/go-router-v6-breaking-changes)
## 5.2.4
- Fixes crashes when using async redirect.
## 5.2.3
- Fixes link for router configuration and sub-routes
## 5.2.2
- Fixes `pop` and `push` to update urls correctly.
## 5.2.1
- Refactors `GoRouter.pop` to be able to pop individual pageless route with result.
## 5.2.0
- Fixes `GoRouterState.location` and `GoRouterState.param` to return correct value.
- Cleans up `RouteMatch` and `RouteMatchList` API.
## 5.1.10
- Fixes link of ShellRoute in README.
## 5.1.9
- Fixes broken links in documentation.
## 5.1.8
- Fixes a bug with `replace` where it was not generated a new `pageKey`.
## 5.1.7
- Adds documentation using dartdoc topics.
## 5.1.6
- Fixes crashes when multiple `GoRoute`s use the same `parentNavigatorKey` in a route subtree.
## 5.1.5
- Adds migration guide for 5.1.2 to readme.
## 5.1.4
- Fixes the documentation by removing the `ShellRoute`'s non-existing `path` parameter from it.
## 5.1.3
- Allows redirection to return same location.
## 5.1.2
- Adds GoRouterState to context.
- Fixes GoRouter notification.
- Updates README.
- Removes dynamic calls in examples.
- **BREAKING CHANGE**
- Remove NavigatorObserver mixin from GoRouter
## 5.1.1
- Removes DebugGoRouteInformation.
## 5.1.0
- Removes urlPathStrategy completely, which should have been done in v5.0.0 but some code remained mistakenly.
## 5.0.5
- Fixes issue where asserts in popRoute were preventing the app from
exiting on Android.
## 5.0.4
- Fixes a bug in ShellRoute example where NavigationBar might lose current index in a nested routes.
## 5.0.3
- Changes examples to use the routerConfig API
## 5.0.2
- Fixes missing code example in ShellRoute documentation.
## 5.0.1
- Allows ShellRoute to have child ShellRoutes (flutter/flutter#111981)
## 5.0.0
- Fixes a bug where intermediate route redirect methods are not called.
- GoRouter implements the RouterConfig interface, allowing you to call
MaterialApp.router(routerConfig: _myGoRouter) instead of passing
the RouterDelegate, RouteInformationParser, and RouteInformationProvider
fields.
- **BREAKING CHANGE**
- Redesigns redirection API, adds asynchronous feature, and adds build context to redirect.
- Removes GoRouterRefreshStream
- Removes navigatorBuilder
- Removes urlPathStrategy
- [go_router v5 migration guide](https://flutter.dev/go/go-router-v5-breaking-changes)
## 4.5.1
- Fixes an issue where GoRoutes with only a redirect were disallowed
(flutter/flutter#111763)
## 4.5.0
- Adds ShellRoute for nested navigation support (flutter/flutter#99126)
- Adds `parentNavigatorKey` to GoRoute, which specifies the Navigator to place that
route's Page onto.
## 4.4.1
- Fix an issue where disabling logging clears the root logger's listeners
## 4.4.0
- Adds `buildPageWithState` to `GoRouteData`.
- `GoRouteData.buildPage` is now deprecated in favor of `GoRouteData.buildPageWithState`.
## 4.3.0
- Allows `Map<String, dynamic>` maps as `queryParams` of `goNamed`, `replacedName`, `pushNamed` and `namedLocation`.
## 4.2.9
- Updates text theme parameters to avoid deprecation issues.
- Fixes lint warnings.
## 4.2.8
- Fixes namedLocation to return URIs without trailing question marks if there are no query parameters.
- Cleans up examples.
## 4.2.7
- Updates README.
## 4.2.6
- Fixes rendering issues in the README.
## 4.2.5
- Fixes a bug where calling extra parameter is always null in route level redirect callback
## 4.2.4
- Rewrites Readme and examples.
## 4.2.3
- Fixes a bug where the ValueKey to be the same when a page was pushed multiple times.
## 4.2.2
- Fixes a bug where go_router_builder wasn't detecting annotations.
## 4.2.1
- Refactors internal classes and methods
## 4.2.0
- Adds `void replace()` and `replaceNamed` to `GoRouterDelegate`, `GoRouter` and `GoRouterHelper`.
## 4.1.1
- Fixes a bug where calling namedLocation does not support case-insensitive way.
## 4.1.0
- Adds `bool canPop()` to `GoRouterDelegate`, `GoRouter` and `GoRouterHelper`.
## 4.0.3
- Adds missed popping log.
## 4.0.2
- Fixes a bug where initialLocation took precedence over deep-links
## 4.0.1
- Fixes a bug where calling setLogging(false) does not clear listeners.
## 4.0.0
- Refactors go_router and introduces `GoRouteInformationProvider`. [Migration Doc](https://flutter.dev/go/go-router-v4-breaking-changes)
- Fixes a bug where top-level routes are skipped if another contains child routes.
## 3.1.1
- Uses first match if there are more than one route to match. [ [#99833](https://github.com/flutter/flutter/issues/99833)
## 3.1.0
- Adds `GoRouteData` and `TypedGoRoute` to support `package:go_router_builder`.
## 3.0.7
- Refactors runtime checks to assertions.
## 3.0.6
- Exports inherited_go_router.dart file.
## 3.0.5
- Add `dispatchNotification` method to `DummyBuildContext` in tests. (This
should be revisited when Flutter `2.11.0` becomes stable.)
- Improves code coverage.
- `GoRoute` now warns about requiring either `pageBuilder`, `builder` or `redirect` at instantiation.
## 3.0.4
- Updates code for stricter analysis options.
## 3.0.3
- Fixes a bug where params disappear when pushing a nested route.
## 3.0.2
- Moves source to flutter/packages.
- Removes all_lint_rules_community and path_to_regexp dependencies.
## 3.0.1
- pass along the error to the `navigatorBuilder` to allow for different
implementations based on the presence of an error
## 3.0.0
- breaking change: added `GoRouterState` to `navigatorBuilder` function
- breaking change: removed `BuildContext` from `GoRouter.pop()` to remove the
need to use `context` parameter when calling the `GoRouter` API; this changes
the behavior of `GoRouter.pop()` to only pop what's on the `GoRouter` page
stack and no longer calls `Navigator.pop()`
- new [Migrating to 3.0 section](https://gorouter.dev/migrating-to-30) in the
docs to describe the details of the breaking changes and how to update your
code
- added a new [shared
scaffold](https://github.com/csells/go_router/blob/main/go_router/example/lib/shared_scaffold.dart)
sample to show how to use the `navigatorBuilder` function to build a custom
shared scaffold outside of the animations provided by go_router
## 2.5.7
- [PR 262](https://github.com/csells/go_router/pull/262): add support for
`Router.neglect`; thanks to [nullrocket](https://github.com/nullrocket)!
- [PR 265](https://github.com/csells/go_router/pull/265): add Japanese
translation of the docs; thanks to
[toshi-kuji](https://github.com/toshi-kuji)! Unfortunately I don't yet know
how to properly display them via docs.page, but [I'm working on
it](https://github.com/csells/go_router/issues/266)
- updated the examples using the `from` query parameter to be completely
self-contained in the `redirect` function, simplifying usage
- updated the async data example to be simpler
- added a new example to show how to implement a loading page
- renamed the navigator_integration example to user_input and added an example
of `WillPopScope` for go_router apps
## 2.5.6
- [PR 259](https://github.com/csells/go_router/pull/259): remove a hack for
notifying the router of a route change that was no longer needed; thanks to
[nullrocket](https://github.com/nullrocket)!
- improved async example to handle the case that the data has been returned but
the page is no longer there by checking the `mounted` property of the screen
## 2.5.5
- updated implementation to use logging package for debug diagnostics; thanks
to [johnpryan](https://github.com/johnpryan)
## 2.5.4
- fixed up the `GoRouterRefreshStream` implementation with an export, an example
and some docs
## 2.5.3
- added `GoRouterRefreshStream` from
[jopmiddelkamp](https://github.com/jopmiddelkamp) to easily map from a
`Stream` to a `Listenable` for use with `refreshListenable`; very useful when
combined with stream-based state management like
[flutter_bloc](https://pub.dev/packages/flutter_bloc)
- dartdocs fixups from [mehade369](https://github.com/mehade369)
- example link fixes from [ben-milanko](https://github.com/ben-milanko)
## 2.5.2
- pass additional information to the `NavigatorObserver` via default args to
`MaterialPage`, etc.
## 2.5.1
- [fix 205](https://github.com/csells/go_router/issues/205): hack around a
failed assertion in Flutter when using `Duration.zero` in the
`NoTransitionPage`
## 2.5.0
- provide default implementation of `GoRoute.pageBuilder` to provide a simpler
way to build pages via the `GoRouter.build` method
- provide default implementation of `GoRouter.errorPageBuilder` to provide a
simpler way to build error pages via the `GoRouter.errorBuilder` method
- provide default implementation of `GoRouter.errorBuilder` to provide an error
page without the need to implement a custom error page builder
- new [Migrating to 2.5 section](https://gorouter.dev/migrating-to-25) in
the docs to show how to take advantage of the new `builder` and default error
page builder
- removed `launch.json` as VSCode-centric and unnecessary for discovery or easy
launching
- added a [new custom error screen
sample](https://github.com/csells/go_router/blob/master/example/lib/error_screen.dart)
- added a [new WidgetsApp
sample](https://github.com/csells/go_router/blob/master/example/lib/widgets_app.dart)
- added a new `NoTransitionPage` class
- updated docs to explain why the browser's Back button doesn't work
with the `extra` param
- updated README to point to new docs site: [gorouter.dev](https://gorouter.dev)
## 2.3.1
- [fix 191](https://github.com/csells/go_router/issues/191): handle several
kinds of trailing / in the location, e.g. `/foo/` should be the same as `/foo`
## 2.3.0
- fix a misleading error message when using redirect functions with sub-routes
## 2.2.9
- [fix 182](https://github.com/csells/go_router/issues/182): fixes a regression
in the nested navigation caused by the fix for
[#163](https://github.com/csells/go_router/issues/163); thanks to
[lulupointu](https://github.com/lulupointu) for the fix!
## 2.2.8
- reformatted CHANGELOG file; lets see if pub.dev is still ok with it...
- staged an in-progress doc site at https://docs.page/csells/go_router
- tightened up a test that was silently failing
- fixed a bug that dropped parent params in sub-route redirects
## 2.2.7
- [fix 163](https://github.com/csells/go_router/issues/163): avoids unnecessary
page rebuilds
- [fix 139](https://github.com/csells/go_router/issues/139): avoids unnecessary
page flashes on deep linking
- [fix 158](https://github.com/csells/go_router/issues/158): shows exception
info in the debug output even during a top-level redirect coded w/ an
anonymous function, i.e. what the samples all use
- [fix 151](https://github.com/csells/go_router/issues/151): exposes
`Navigator.pop()` via `GoRouter.pop()` to make it easy to find
## 2.2.6
- [fix 127](https://github.com/csells/go_router/issues/127): updated the docs
to add a video overview of the project for people that prefer that media style
over long-form text when approaching a new topic
- [fix 108](https://github.com/csells/go_router/issues/108): updated the
description of the `state` parameter to clarfy that not all properties will be
set at every usage
## 2.2.5
- [fix 120 again](https://github.com/csells/go_router/issues/120): found the bug
in my tests that was masking the real bug; changed two characters to implement
the actual fix (sigh)
## 2.2.4
- [fix 116](https://github.com/csells/go_router/issues/116): work-around for
auto-import of the `context.go` family of extension methods
## 2.2.3
- [fix 132](https://github.com/csells/go_router/issues/132): route names are
stored as case insensitive and are now matched in a case insensitive manner
## 2.2.2
- [fix 120](https://github.com/csells/go_router/issues/120): encoding and
decoding of params and query params
## 2.2.1
- [fix 114](https://github.com/csells/go_router/issues/114): give a better error
message when the `GoRouter` isn't found in the widget tree via
`GoRouter.of(context)`; thanks [aoatmon](https://github.com/aoatmon) for the
[excellent bug report](https://github.com/csells/go_router/issues/114)!
## 2.2.0
- added a new [`navigatorBuilder`](https://gorouter.dev/navigator-builder) argument to the
`GoRouter` constructor; thanks to [andyduke](https://github.com/andyduke)!
- also from [andyduke](https://github.com/andyduke) is an update to
improve state restoration
- refactor from [kevmoo](https://github.com/kevmoo) for easier maintenance
- added a new [Navigator Integration section of the
docs](https://gorouter.dev/navigator-integration)
## 2.1.2
- [fix 61 again](https://github.com/csells/go_router/issues/61): enable images
and file links to work on pub.dev/documentation
- [fix 62](https://github.com/csells/go_router/issues/62) re-tested; fixed w/
earlier Android system Back button fix (using navigation key)
- [fix 91](https://github.com/csells/go_router/issues/91): fix a regression w/
the `errorPageBuilder`
- [fix 92](https://github.com/csells/go_router/issues/92): fix an edge case w/
named sub-routes
- [fix 89](https://github.com/csells/go_router/issues/89): enable queryParams
and extra object param w/ `push`
- refactored tests for greater coverage and fewer methods `@visibleForTesting`
## 2.1.1
- [fix 86](https://github.com/csells/go_router/issues/86): add `name` to
`GoRouterState` to complete support for URI-free navigation knowledge in your
code
- [fix 83](https://github.com/csells/go_router/issues/83): fix for `null`
`extra` object
## 2.1.0
- [fix 80](https://github.com/csells/go_router/issues/80): adding a redirect
limit to catch too many redirects error
- [fix 81](https://github.com/csells/go_router/issues/81): allow an `extra`
object to pass through for navigation
## 2.0.1
- add badges to the README and codecov to the GitHub commit action; thanks to
[rydmike](https://github.com/rydmike) for both
## 2.0.0
- BREAKING CHANGE and [fix #50](https://github.com/csells/go_router/issues/50):
split `params` into `params` and `queryParams`; see the [Migrating to 2.0
section of the docs](https://gorouter.dev/migrating-to-20)
for instructions on how to migrate your code from 1.x to 2.0
- [fix 69](https://github.com/csells/go_router/issues/69): exposed named
location lookup for redirection
- [fix 57](https://github.com/csells/go_router/issues/57): enable the Android
system Back button to behave exactly like the `AppBar` Back button; thanks to
[SunlightBro](https://github.com/SunlightBro) for the one-line fix that I had
no idea about until he pointed it out
- [fix 59](https://github.com/csells/go_router/issues/59): add query params to
top-level redirect
- [fix 44](https://github.com/csells/go_router/issues/44): show how to use the
`AutomaticKeepAliveClientMixin` with nested navigation to keep widget state
between navigations; thanks to [rydmike](https://github.com/rydmike) for this
update
## 1.1.3
- enable case-insensitive path matching while still preserving path and query
parameter cases
- change a lifetime of habit to sort constructors first as per
[sort_constructors_first](https://dart.dev/lints/sort_constructors_first).
Thanks for the PR, [Abhishek01039](https://github.com/Abhishek01039)!
- set the initial transition example route to `/none` to make pushing the 'fade
transition' button on the first run through more fun
- fixed an error in the async data example
## 1.1.2
- Thanks, Mikes!
- updated dartdocs from [rydmike](https://github.com/rydmike)
- also shoutout to [https://github.com/Salakar](https://github.com/Salakar)
for the CI action on GitHub
- this is turning into a real community effort...
## 1.1.1
- now showing routing exceptions in the debug log
- updated the docs to make it clear that it will be called until it returns
`null`
## 1.1.0
- added support `NavigatorObserver` objects to receive change notifications
## 1.0.1
- docs updates based on user feedback for clarity
- fix for setting URL path strategy in `main()`
- fix for `push()` disables `AppBar` Back button
## 1.0.0
- updated version for initial release
- some renaming for clarify and consistency with transitions
- `GoRoute.builder` => `GoRoute.pageBuilder`
- `GoRoute.error` => `GoRoute.errorPageBuilder`
- added diagnostic logging for `push` and `pushNamed`
## 0.9.6
- added support for `push` as well as `go`
- added 'none' to transitions example app
- updated animation example to use no transition and added an animated gif to
the docs
## 0.9.5
- added support for custom transitions between routes
## 0.9.4
- updated API docs
- updated docs for `GoRouterState`
## 0.9.3
- updated API docs
## 0.9.2
- updated named route lookup to O(1)
- updated diagnostics output to show known named routes
## 0.9.1
- updated diagnostics output to show named route lookup
- docs updates
## 0.9.0
- added support for named routes
## 0.8.8
- fix to make `GoRouter` notify on pop
## 0.8.7
- made `GoRouter` a `ChangeNotifier` so you can listen for `location` changes
## 0.8.6
- books sample bug fix
## 0.8.5
- added Cupertino sample
- added example of async data lookup
## 0.8.4
- added state restoration sample
## 0.8.3
- changed `debugOutputFullPaths` to `debugLogDiagnostics` and added add'l
debugging logging
- parameterized redirect
## 0.8.2
- updated docs for `Link` widget support
## 0.8.1
- added Books sample; fixed some issues it revealed
## 0.8.0
- breaking build to refactor the API for simplicity and capability
- move to fixed routing from conditional routing; simplies API, allows for
redirection at the route level and there scenario was sketchy anyway
- add redirection at the route level
- replace guard objects w/ redirect functions
- add `refresh` method and `refreshListener`
- removed `.builder` ctor from `GoRouter` (not reasonable to implement)
- add Dynamic linking section to the docs
- replaced Books sample with Nested Navigation sample
- add ability to dump the known full paths to your routes to debug output
## 0.7.1
- update to pageKey to take sub-routes into account
## 0.7.0
- BREAK: rename `pattern` to `path` for consistency w/ other routers in the
world
- added the `GoRouterLoginGuard` for the common redirect-to-login-page pattern
## 0.6.2
- fixed issue showing home page for a second before redirecting (if needed)
## 0.6.1
- added `GoRouterState.pageKey`
- removed `cupertino_icons` from main `pubspec.yaml`
## 0.6.0
- refactor to support sub-routes to build a stack of pages instead of matching
multiple routes
- added unit tests for building the stack of pages
- some renaming of the types, e.g. `Four04Page` and `FamiliesPage` to
`ErrorPage` and `HomePage` respectively
- fix a redirection error shown in the debug output
## 0.5.2
- add `urlPathStrategy` argument to `GoRouter` ctor
## 0.5.1
- docs and description updates
## 0.5.0
- moved redirect to top-level instead of per route for simplicity
## 0.4.1
- fixed CHANGELOG formatting
## 0.4.0
- bundled various useful route handling variables into the `GoRouterState` for
use when building pages and error pages
- updated URL Strategy section of docs to reference `flutter run`
## 0.3.2
- formatting update to appease the pub.dev gods...
## 0.3.1
- updated the CHANGELOG
## 0.3.0
- moved redirection into a `GoRoute` ctor arg
- forgot to update the CHANGELOG
## 0.2.3
- move outstanding issues to [issue
tracker](https://github.com/csells/go_router/issues)
- added explanation of Deep Linking to docs
- reformatting to meet pub.dev scoring guidelines
## 0.2.2
- docs updates
## 0.2.1
- messing with the CHANGELOG formatting
## 0.2.0
- initial useful release
- added support for declarative routes via `GoRoute` instances
- added support for imperative routing via `GoRoute.builder`
- added support for setting the URL path strategy
- added support for conditional routing
- added support for redirection
- added support for optional query parameters as well as positional parameters
in route names
## 0.1.0
- squatting on the package name (I'm not too proud to admit it)
| packages/packages/go_router/CHANGELOG.md/0 | {
"file_path": "packages/packages/go_router/CHANGELOG.md",
"repo_id": "packages",
"token_count": 9486
} | 1,012 |
// 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/widgets.dart';
/// A mock authentication service.
class BookstoreAuth extends ChangeNotifier {
bool _signedIn = false;
/// Whether user has signed in.
bool get signedIn => _signedIn;
/// Signs out the current user.
Future<void> signOut() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign out.
_signedIn = false;
notifyListeners();
}
/// Signs in a user.
Future<bool> signIn(String username, String password) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign in. Allow any password.
_signedIn = true;
notifyListeners();
return _signedIn;
}
}
/// An inherited notifier to host [BookstoreAuth] for the subtree.
class BookstoreAuthScope extends InheritedNotifier<BookstoreAuth> {
/// Creates a [BookstoreAuthScope].
const BookstoreAuthScope({
required BookstoreAuth super.notifier,
required super.child,
super.key,
});
/// Gets the [BookstoreAuth] above the context.
static BookstoreAuth of(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()!
.notifier!;
}
| packages/packages/go_router/example/lib/books/src/auth.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/books/src/auth.dart",
"repo_id": "packages",
"token_count": 418
} | 1,013 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
/// This sample app shows an app with two screens.
///
/// The first route '/' is mapped to [HomeScreen], and the second route
/// '/details' is mapped to [DetailsScreen].
///
/// The buttons use context.go() to navigate to each destination. On mobile
/// devices, each destination is deep-linkable and on the web, can be navigated
/// to using the address bar.
void main() => runApp(const MyApp());
/// The route configuration.
final GoRouter _router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) {
return const HomeScreen();
},
routes: <RouteBase>[
GoRoute(
path: 'details',
builder: (BuildContext context, GoRouterState state) {
return const DetailsScreen();
},
),
],
),
],
);
/// The main app.
class MyApp extends StatelessWidget {
/// Constructs a [MyApp]
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}
/// The home screen
class HomeScreen extends StatelessWidget {
/// Constructs a [HomeScreen]
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home Screen')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/details'),
child: const Text('Go to the Details screen'),
),
),
);
}
}
/// The details screen
class DetailsScreen extends StatelessWidget {
/// Constructs a [DetailsScreen]
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/'),
child: const Text('Go back to the Home screen'),
),
),
);
}
}
| packages/packages/go_router/example/lib/main.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/main.dart",
"repo_id": "packages",
"token_count": 814
} | 1,014 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
/// This app shows how to dynamically add more route into routing config
void main() => runApp(const MyApp());
/// The main app.
class MyApp extends StatefulWidget {
/// Constructs a [MyApp]
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isNewRouteAdded = false;
late final ValueNotifier<RoutingConfig> myConfig =
ValueNotifier<RoutingConfig>(_generateRoutingConfig());
late final GoRouter router = GoRouter.routingConfig(
routingConfig: myConfig,
errorBuilder: (_, GoRouterState state) => Scaffold(
appBar: AppBar(title: const Text('Page not found')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('${state.uri} does not exist'),
ElevatedButton(
onPressed: () => router.go('/'),
child: const Text('Go to home')),
],
)),
));
RoutingConfig _generateRoutingConfig() {
return RoutingConfig(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (_, __) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: isNewRouteAdded
? null
: () {
setState(() {
isNewRouteAdded = true;
// Modify the routing config.
myConfig.value = _generateRoutingConfig();
});
},
child: isNewRouteAdded
? const Text('A route has been added')
: const Text('Add a new route'),
),
ElevatedButton(
onPressed: () {
router.go('/new-route');
},
child: const Text('Try going to /new-route'),
)
],
),
),
);
},
),
if (isNewRouteAdded)
GoRoute(
path: '/new-route',
builder: (_, __) {
return Scaffold(
appBar: AppBar(title: const Text('A new Route')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => router.go('/'),
child: const Text('Go to home')),
],
)),
);
},
),
],
);
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: router,
);
}
}
| packages/packages/go_router/example/lib/routing_config.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/routing_config.dart",
"repo_id": "packages",
"token_count": 1889
} | 1,015 |
name: go_router_examples
description: go_router examples
version: 3.0.1
publish_to: none
environment:
sdk: ^3.2.0
flutter: ">=3.16.0"
dependencies:
adaptive_navigation: ^0.0.4
collection: ^1.15.0
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
go_router:
path: ..
logging: ^1.0.0
provider: 6.0.5
shared_preferences: ^2.0.11
url_launcher: ^6.0.7
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/go_router/example/pubspec.yaml/0 | {
"file_path": "packages/packages/go_router/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 215
} | 1,016 |
# Copyright 2014 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.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md
# file for instructions on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes
version: 1
transforms:
- title: "Replaces 'location' in 'GoRouterState' with `uri.toString()`"
date: 2023-07-06
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'location'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'uri.toString()'
- title: "Replaces 'queryParameters' in 'GoRouterState' with `uri.queryParameters`"
date: 2023-07-06
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'queryParameters'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'uri.queryParameters'
- title: "Replaces 'queryParametersAll' in 'GoRouterState' with `uri.queryParametersAll`"
date: 2023-07-06
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'queryParametersAll'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'uri.queryParametersAll'
- title: "Replaces 'params' and 'queryParams' in 'GoRouter.replaceNamed' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'replaceNamed'
inClass: 'GoRouter'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'params' and 'queryParams' in 'GoRouter.pushReplacementNamed' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'pushReplacementNamed'
inClass: 'GoRouter'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'params' and 'queryParams' in 'GoRouter.pushNamed' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'pushNamed'
inClass: 'GoRouter'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'params' and 'queryParams' in 'GoRouter.goNamed' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'goNamed'
inClass: 'GoRouter'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'params' and 'queryParams' in 'GoRouter.namedLocation' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'namedLocation'
inClass: 'GoRouter'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'params' and 'queryParams' in 'GoRouterState.namedLocation' with `pathParameters` and `queryParameters`"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
method: 'namedLocation'
inClass: 'GoRouterState'
changes:
- kind: 'renameParameter'
oldName: 'params'
newName: 'pathParameters'
- kind: 'renameParameter'
oldName: 'queryParams'
newName: 'queryParameters'
- title: "Replaces 'GoRouterState.queryParams' with 'GoRouterState.queryParameters'"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'queryParams'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'queryParameters'
- title: "Replaces 'GoRouterState.fullpath' with 'GoRouterState.fullPath'"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'fullpath'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'fullPath'
- title: "Replaces 'GoRouterState.params' with 'GoRouterState.pathParameters'"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'params'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'pathParameters'
- title: "Replaces 'GoRouterState.subloc' with 'GoRouterState.matchedLocation'"
date: 2023-04-24
bulkApply: true
element:
# TODO(ahmednfwela): Workaround for https://github.com/dart-lang/sdk/issues/52233
uris: [ 'go_router.dart', 'package:go_router/go_router.dart' ]
field: 'subloc'
inClass: 'GoRouterState'
changes:
- kind: 'rename'
newName: 'matchedLocation'
| packages/packages/go_router/lib/fix_data.yaml/0 | {
"file_path": "packages/packages/go_router/lib/fix_data.yaml",
"repo_id": "packages",
"token_count": 3065
} | 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 'misc/errors.dart';
import 'route.dart';
final RegExp _parameterRegExp = RegExp(r':(\w+)(\((?:\\.|[^\\()])+\))?');
/// Converts a [pattern] such as `/user/:id` into [RegExp].
///
/// The path parameters can be specified by prefixing them with `:`. The
/// `parameters` are used for storing path parameter names.
///
///
/// For example:
///
/// `pattern` = `/user/:id/book/:bookId`
///
/// The `parameters` would contain `['id', 'bookId']` as a result of calling
/// this method.
///
/// To extract the path parameter values from a [RegExpMatch], pass the
/// [RegExpMatch] into [extractPathParameters] with the `parameters` that are
/// used for generating the [RegExp].
RegExp patternToRegExp(String pattern, List<String> parameters) {
final StringBuffer buffer = StringBuffer('^');
int start = 0;
for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) {
if (match.start > start) {
buffer.write(RegExp.escape(pattern.substring(start, match.start)));
}
final String name = match[1]!;
final String? optionalPattern = match[2];
final String regex = optionalPattern != null
? _escapeGroup(optionalPattern, name)
: '(?<$name>[^/]+)';
buffer.write(regex);
parameters.add(name);
start = match.end;
}
if (start < pattern.length) {
buffer.write(RegExp.escape(pattern.substring(start)));
}
if (!pattern.endsWith('/')) {
buffer.write(r'(?=/|$)');
}
return RegExp(buffer.toString(), caseSensitive: false);
}
String _escapeGroup(String group, [String? name]) {
final String escapedGroup = group.replaceFirstMapped(
RegExp(r'[:=!]'), (Match match) => '\\${match[0]}');
if (name != null) {
return '(?<$name>$escapedGroup)';
}
return escapedGroup;
}
/// Reconstructs the full path from a [pattern] and path parameters.
///
/// This is useful for restoring the original path from a [RegExpMatch].
///
/// For example, A path matched a [RegExp] returned from [patternToRegExp] and
/// produced a [RegExpMatch]. To reconstruct the path from the match, one
/// can follow these steps:
///
/// 1. Get the `pathParameters` by calling [extractPathParameters] with the
/// [RegExpMatch] and the parameters used for generating the [RegExp].
/// 2. Call [patternToPath] with the `pathParameters` from the first step and
/// the original `pattern` used for generating the [RegExp].
String patternToPath(String pattern, Map<String, String> pathParameters) {
final StringBuffer buffer = StringBuffer();
int start = 0;
for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) {
if (match.start > start) {
buffer.write(pattern.substring(start, match.start));
}
final String name = match[1]!;
buffer.write(pathParameters[name]);
start = match.end;
}
if (start < pattern.length) {
buffer.write(pattern.substring(start));
}
return buffer.toString();
}
/// Extracts arguments from the `match` and maps them by parameter name.
///
/// The [parameters] should originate from the call to [patternToRegExp] that
/// creates the [RegExp].
Map<String, String> extractPathParameters(
List<String> parameters, RegExpMatch match) {
return <String, String>{
for (int i = 0; i < parameters.length; ++i)
parameters[i]: match.namedGroup(parameters[i])!
};
}
/// Concatenates two paths.
///
/// e.g: pathA = /a, pathB = c/d, concatenatePaths(pathA, pathB) = /a/c/d.
String concatenatePaths(String parentPath, String childPath) {
// at the root, just return the path
if (parentPath.isEmpty) {
assert(childPath.startsWith('/'));
assert(childPath == '/' || !childPath.endsWith('/'));
return childPath;
}
// not at the root, so append the parent path
assert(childPath.isNotEmpty);
assert(!childPath.startsWith('/'));
assert(!childPath.endsWith('/'));
return '${parentPath == '/' ? '' : parentPath}/$childPath';
}
/// Normalizes the location string.
String canonicalUri(String loc) {
if (loc.isEmpty) {
throw GoException('Location cannot be empty.');
}
String canon = Uri.parse(loc).toString();
canon = canon.endsWith('?') ? canon.substring(0, canon.length - 1) : canon;
// remove trailing slash except for when you shouldn't, e.g.
// /profile/ => /profile
// / => /
// /login?from=/ => login?from=/
canon = canon.endsWith('/') && canon != '/' && !canon.contains('?')
? canon.substring(0, canon.length - 1)
: canon;
// replace '/?', except for first occurrence, from path only
// /login/?from=/ => /login?from=/
// /?from=/ => /?from=/
final Uri uri = Uri.parse(canon);
final int pathStartIndex = uri.host.isNotEmpty
? uri.toString().indexOf(uri.host) + uri.host.length
: uri.hasScheme
? uri.toString().indexOf(uri.scheme) + uri.scheme.length
: 0;
if (pathStartIndex < canon.length) {
canon = canon.replaceFirst('/?', '?', pathStartIndex + 1);
}
return canon;
}
/// Builds an absolute path for the provided route.
String? fullPathForRoute(
RouteBase targetRoute, String parentFullpath, List<RouteBase> routes) {
for (final RouteBase route in routes) {
final String fullPath = (route is GoRoute)
? concatenatePaths(parentFullpath, route.path)
: parentFullpath;
if (route == targetRoute) {
return fullPath;
} else {
final String? subRoutePath =
fullPathForRoute(targetRoute, fullPath, route.routes);
if (subRoutePath != null) {
return subRoutePath;
}
}
}
return null;
}
| packages/packages/go_router/lib/src/path_utils.dart/0 | {
"file_path": "packages/packages/go_router/lib/src/path_utils.dart",
"repo_id": "packages",
"token_count": 1969
} | 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 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
void main() {
test('throws when a builder is not set', () {
expect(() => GoRoute(path: '/'), throwsA(isAssertionError));
});
test('throws when a path is empty', () {
expect(() => GoRoute(path: ''), throwsA(isAssertionError));
});
test('does not throw when only redirect is provided', () {
GoRoute(path: '/', redirect: (_, __) => '/a');
});
testWidgets('ShellRoute can use parent navigator key',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shellNavigatorKey =
GlobalKey<NavigatorState>();
final List<RouteBase> routes = <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKey,
builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: Column(
children: <Widget>[
const Text('Screen A'),
Expanded(child: child),
],
),
);
},
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen B'),
);
},
routes: <RouteBase>[
ShellRoute(
parentNavigatorKey: rootNavigatorKey,
builder:
(BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: Column(
children: <Widget>[
const Text('Screen D'),
Expanded(child: child),
],
),
);
},
routes: <RouteBase>[
GoRoute(
path: 'c',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen C'),
);
},
),
],
),
],
),
],
),
];
await createRouter(routes, tester,
initialLocation: '/b/c', navigatorKey: rootNavigatorKey);
expect(find.text('Screen A'), findsNothing);
expect(find.text('Screen B'), findsNothing);
expect(find.text('Screen D'), findsOneWidget);
expect(find.text('Screen C'), findsOneWidget);
});
testWidgets('StatefulShellRoute can use parent navigator key',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shellNavigatorKey =
GlobalKey<NavigatorState>();
final List<RouteBase> routes = <RouteBase>[
ShellRoute(
navigatorKey: shellNavigatorKey,
builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: Column(
children: <Widget>[
const Text('Screen A'),
Expanded(child: child),
],
),
);
},
routes: <RouteBase>[
GoRoute(
path: '/b',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen B'),
);
},
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
parentNavigatorKey: rootNavigatorKey,
builder: (_, __, StatefulNavigationShell navigationShell) {
return Column(
children: <Widget>[
const Text('Screen D'),
Expanded(child: navigationShell),
],
);
},
branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: 'c',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen C'),
);
},
),
],
),
],
),
],
),
],
),
];
await createRouter(routes, tester,
initialLocation: '/b/c', navigatorKey: rootNavigatorKey);
expect(find.text('Screen A'), findsNothing);
expect(find.text('Screen B'), findsNothing);
expect(find.text('Screen D'), findsOneWidget);
expect(find.text('Screen C'), findsOneWidget);
});
test('ShellRoute parent navigator key throw if not match', () async {
final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
bool hasError = false;
try {
ShellRoute(
navigatorKey: key1,
builder: (_, __, Widget child) => child,
routes: <RouteBase>[
ShellRoute(
parentNavigatorKey: key2,
builder: (_, __, Widget child) => child,
routes: <RouteBase>[
GoRoute(
path: '1',
builder: (_, __) => const Text('/route/1'),
),
],
),
],
);
} on AssertionError catch (_) {
hasError = true;
}
expect(hasError, isTrue);
});
group('Redirect only GoRoute', () {
testWidgets('can redirect to subroute', (WidgetTester tester) async {
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
builder: (_, __) => const Text('home'),
routes: <RouteBase>[
GoRoute(
path: 'route',
redirect: (_, __) => '/route/1',
routes: <RouteBase>[
GoRoute(
path: '1',
builder: (_, __) => const Text('/route/1'),
),
],
),
],
),
],
tester,
);
expect(find.text('home'), findsOneWidget);
router.go('/route');
await tester.pumpAndSettle();
// Should redirect to /route/1 without error.
expect(find.text('/route/1'), findsOneWidget);
router.pop();
await tester.pumpAndSettle();
// Should go back directly to home page.
expect(find.text('home'), findsOneWidget);
});
testWidgets('throw if redirect to itself.', (WidgetTester tester) async {
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
builder: (_, __) => const Text('home'),
routes: <RouteBase>[
GoRoute(
path: 'route',
redirect: (_, __) => '/route',
routes: <RouteBase>[
GoRoute(
path: '1',
builder: (_, __) => const Text('/route/1'),
),
],
),
],
),
],
tester,
);
expect(find.text('home'), findsOneWidget);
router.go('/route');
await tester.pumpAndSettle();
// Should redirect to /route/1 without error.
expect(tester.takeException(), isAssertionError);
});
testWidgets('throw if sub route does not conform with parent navigator key',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
bool hasError = false;
try {
ShellRoute(
navigatorKey: key1,
builder: (_, __, Widget child) => child,
routes: <RouteBase>[
GoRoute(
path: '/',
redirect: (_, __) => '/route',
routes: <RouteBase>[
GoRoute(
parentNavigatorKey: key2,
path: 'route',
builder: (_, __) => const Text('/route/1'),
),
],
),
],
);
} on AssertionError catch (_) {
hasError = true;
}
expect(hasError, isTrue);
});
});
}
| packages/packages/go_router/test/go_route_test.dart/0 | {
"file_path": "packages/packages/go_router/test/go_route_test.dart",
"repo_id": "packages",
"token_count": 4569
} | 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 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
void main() {
testWidgets('GoRouter does not request focus if requestFocus is false',
(WidgetTester tester) async {
final GlobalKey innerKey = GlobalKey();
final FocusScopeNode focusNode = FocusScopeNode();
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
GoRoute(
path: '/',
name: 'home',
builder: (_, __) => const Text('A'),
),
GoRoute(
path: '/second',
name: 'second',
builder: (_, __) => Text('B', key: innerKey),
),
],
requestFocus: false,
);
await tester.pumpWidget(Column(
children: <Widget>[
FocusScope(node: focusNode, child: Container()),
Expanded(
child: MaterialApp.router(
routerConfig: router,
),
),
],
));
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
expect(focusNode.hasFocus, false);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
router.pushNamed('second');
await tester.pumpAndSettle();
expect(find.text('A', skipOffstage: false), findsOneWidget);
expect(find.text('B'), findsOneWidget);
expect(focusNode.hasFocus, true);
router.pop();
await tester.pumpAndSettle();
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
expect(focusNode.hasFocus, true);
});
}
| packages/packages/go_router/test/request_focus.dart/0 | {
"file_path": "packages/packages/go_router/test/request_focus.dart",
"repo_id": "packages",
"token_count": 736
} | 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.
/// Configuration for using `package:build`-compatible build systems.
///
/// See:
/// * [build_runner](https://pub.dev/packages/build_runner)
///
/// This library is **not** intended to be imported by typical end-users unless
/// you are creating a custom compilation pipeline. See documentation for
/// details, and `build.yaml` for how these builders are configured by default.
library go_router_builder;
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'src/go_router_generator.dart';
/// Supports `package:build_runner` creation and configuration of
/// `go_router`.
///
/// Not meant to be invoked by hand-authored code.
Builder goRouterBuilder(BuilderOptions options) => SharedPartBuilder(
const <Generator>[GoRouterGenerator()],
'go_router',
);
| packages/packages/go_router_builder/lib/go_router_builder.dart/0 | {
"file_path": "packages/packages/go_router_builder/lib/go_router_builder.dart",
"repo_id": "packages",
"token_count": 280
} | 1,021 |
RouteBase get $iterableDefaultValueRoute => GoRouteData.$route(
path: '/iterable-default-value-route',
factory: $IterableDefaultValueRouteExtension._fromState,
);
extension $IterableDefaultValueRouteExtension on IterableDefaultValueRoute {
static IterableDefaultValueRoute _fromState(GoRouterState state) =>
IterableDefaultValueRoute(
param: state.uri.queryParametersAll['param']?.map(int.parse) ??
const <int>[0],
);
String get location => GoRouteData.$location(
'/iterable-default-value-route',
queryParams: {
if (param != const <int>[0])
'param': param.map((e) => e.toString()).toList(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
| packages/packages/go_router_builder/test_inputs/iterable_with_default_value.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/iterable_with_default_value.dart.expect",
"repo_id": "packages",
"token_count": 358
} | 1,022 |
Required parameters in the path cannot be nullable.
| packages/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart.expect",
"repo_id": "packages",
"token_count": 11
} | 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 'dart:js_interop';
import 'package:web/web.dart' as web;
// TODO(kevmoo): Make this file unnecessary, https://github.com/dart-lang/web/issues/175
/// This extension gives web.window a nullable getter to the `trustedTypes`
/// property, which needs to be used to check for feature support.
extension NullableTrustedTypesGetter on web.Window {
/// (Nullable) Bindings to window.trustedTypes.
///
/// This may be null if the browser doesn't support the Trusted Types API.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
@JS('trustedTypes')
external web.TrustedTypePolicyFactory? get nullableTrustedTypes;
}
/// Allows setting a TrustedScriptURL as the src of a script element.
extension TrustedTypeSrcAttribute on web.HTMLScriptElement {
@JS('src')
external set trustedSrc(web.TrustedScriptURL value);
}
/// Allows creating a script URL only from a string, with no arguments.
extension CreateScriptUrlNoArgs on web.TrustedTypePolicy {
/// Allows calling `createScriptURL` with only the `input` argument.
@JS('createScriptURL')
external web.TrustedScriptURL createScriptURLNoArgs(
String input,
);
}
| packages/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/lib/src/js_interop/package_web_tweaks.dart",
"repo_id": "packages",
"token_count": 398
} | 1,024 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/google_maps_flutter/google_maps_flutter/example/android/gradle.properties/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 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.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'fake_google_maps_flutter_platform.dart';
Widget _mapWithCircles(Set<Circle> circles) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
circles: circles,
),
);
}
void main() {
late FakeGoogleMapsFlutterPlatform platform;
setUp(() {
platform = FakeGoogleMapsFlutterPlatform();
GoogleMapsFlutterPlatform.instance = platform;
});
testWidgets('Initializing a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToAdd.length, 1);
final Circle initializedCircle = map.circleUpdates.last.circlesToAdd.first;
expect(initializedCircle, equals(c1));
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToChange.isEmpty, true);
});
testWidgets('Adding a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1, c2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToAdd.length, 1);
final Circle addedCircle = map.circleUpdates.last.circlesToAdd.first;
expect(addedCircle, equals(c2));
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToChange.isEmpty, true);
});
testWidgets('Removing a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circleIdsToRemove.length, 1);
expect(map.circleUpdates.last.circleIdsToRemove.first, equals(c1.circleId));
expect(map.circleUpdates.last.circlesToChange.isEmpty, true);
expect(map.circleUpdates.last.circlesToAdd.isEmpty, true);
});
testWidgets('Updating a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_1'), radius: 10);
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange.length, 1);
expect(map.circleUpdates.last.circlesToChange.first, equals(c2));
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToAdd.isEmpty, true);
});
testWidgets('Updating a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_1'), radius: 10);
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange.length, 1);
final Circle update = map.circleUpdates.last.circlesToChange.first;
expect(update, equals(c2));
expect(update.radius, 10);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Circle c1 = const Circle(circleId: CircleId('circle_1'));
Circle c2 = const Circle(circleId: CircleId('circle_2'));
final Set<Circle> prev = <Circle>{c1, c2};
c1 = const Circle(circleId: CircleId('circle_1'), visible: false);
c2 = const Circle(circleId: CircleId('circle_2'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange, cur);
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Circle c2 = const Circle(circleId: CircleId('circle_2'));
const Circle c3 = Circle(circleId: CircleId('circle_3'));
final Set<Circle> prev = <Circle>{c2, c3};
// c1 is added, c2 is updated, c3 is removed.
const Circle c1 = Circle(circleId: CircleId('circle_1'));
c2 = const Circle(circleId: CircleId('circle_2'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange.length, 1);
expect(map.circleUpdates.last.circlesToAdd.length, 1);
expect(map.circleUpdates.last.circleIdsToRemove.length, 1);
expect(map.circleUpdates.last.circlesToChange.first, equals(c2));
expect(map.circleUpdates.last.circlesToAdd.first, equals(c1));
expect(map.circleUpdates.last.circleIdsToRemove.first, equals(c3.circleId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
Circle c3 = const Circle(circleId: CircleId('circle_3'));
final Set<Circle> prev = <Circle>{c1, c2, c3};
c3 = const Circle(circleId: CircleId('circle_3'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2, c3};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange, <Circle>{c3});
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Circle c1 = const Circle(circleId: CircleId('circle_1'));
final Set<Circle> prev = <Circle>{c1};
c1 = Circle(circleId: const CircleId('circle_1'), onTap: () {});
final Set<Circle> cur = <Circle>{c1};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.last.circlesToChange.isEmpty, true);
expect(map.circleUpdates.last.circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates.last.circlesToAdd.isEmpty, true);
});
testWidgets('multi-update with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
const Circle c3 = Circle(circleId: CircleId('circle_3'), radius: 1);
const Circle c3updated = Circle(circleId: CircleId('circle_3'), radius: 10);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithCircles(<Circle>{c1, c2}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1, c3}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1, c3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.circleUpdates.length, 3);
expect(map.circleUpdates[0].circlesToChange.isEmpty, true);
expect(map.circleUpdates[0].circlesToAdd, <Circle>{c1, c2});
expect(map.circleUpdates[0].circleIdsToRemove.isEmpty, true);
expect(map.circleUpdates[1].circlesToChange.isEmpty, true);
expect(map.circleUpdates[1].circlesToAdd, <Circle>{c3});
expect(map.circleUpdates[1].circleIdsToRemove, <CircleId>{c2.circleId});
expect(map.circleUpdates[2].circlesToChange, <Circle>{c3updated});
expect(map.circleUpdates[2].circlesToAdd.isEmpty, true);
expect(map.circleUpdates[2].circleIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
}
| packages/packages/google_maps_flutter/google_maps_flutter/test/circle_updates_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/circle_updates_test.dart",
"repo_id": "packages",
"token_count": 3205
} | 1,026 |
// 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.googlemaps;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
/** Controller of a single Circle on the map. */
class CircleController implements CircleOptionsSink {
private final Circle circle;
private final String googleMapsCircleId;
private final float density;
private boolean consumeTapEvents;
CircleController(Circle circle, boolean consumeTapEvents, float density) {
this.circle = circle;
this.consumeTapEvents = consumeTapEvents;
this.density = density;
this.googleMapsCircleId = circle.getId();
}
void remove() {
circle.remove();
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
circle.setClickable(consumeTapEvents);
}
@Override
public void setStrokeColor(int strokeColor) {
circle.setStrokeColor(strokeColor);
}
@Override
public void setFillColor(int fillColor) {
circle.setFillColor(fillColor);
}
@Override
public void setCenter(LatLng center) {
circle.setCenter(center);
}
@Override
public void setRadius(double radius) {
circle.setRadius(radius);
}
@Override
public void setVisible(boolean visible) {
circle.setVisible(visible);
}
@Override
public void setStrokeWidth(float strokeWidth) {
circle.setStrokeWidth(strokeWidth * density);
}
@Override
public void setZIndex(float zIndex) {
circle.setZIndex(zIndex);
}
String getGoogleMapsCircleId() {
return googleMapsCircleId;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleController.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleController.java",
"repo_id": "packages",
"token_count": 575
} | 1,027 |
// 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.googlemaps;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolygonOptions;
import java.util.List;
class PolygonBuilder implements PolygonOptionsSink {
private final PolygonOptions polygonOptions;
private final float density;
private boolean consumeTapEvents;
PolygonBuilder(float density) {
this.polygonOptions = new PolygonOptions();
this.density = density;
}
PolygonOptions build() {
return polygonOptions;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
@Override
public void setFillColor(int color) {
polygonOptions.fillColor(color);
}
@Override
public void setStrokeColor(int color) {
polygonOptions.strokeColor(color);
}
@Override
public void setPoints(List<LatLng> points) {
polygonOptions.addAll(points);
}
@Override
public void setHoles(List<List<LatLng>> holes) {
for (List<LatLng> hole : holes) {
polygonOptions.addHole(hole);
}
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
polygonOptions.clickable(consumeTapEvents);
}
@Override
public void setGeodesic(boolean geodisc) {
polygonOptions.geodesic(geodisc);
}
@Override
public void setVisible(boolean visible) {
polygonOptions.visible(visible);
}
@Override
public void setStrokeWidth(float width) {
polygonOptions.strokeWidth(width * density);
}
@Override
public void setZIndex(float zIndex) {
polygonOptions.zIndex(zIndex);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonBuilder.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonBuilder.java",
"repo_id": "packages",
"token_count": 582
} | 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 io.flutter.plugins.googlemaps;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.Context;
import android.os.Build;
import androidx.activity.ComponentActivity;
import androidx.test.core.app.ApplicationProvider;
import com.google.android.gms.maps.GoogleMap;
import io.flutter.plugin.common.BinaryMessenger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.P)
public class GoogleMapControllerTest {
private Context context;
private ComponentActivity activity;
private GoogleMapController googleMapController;
AutoCloseable mockCloseable;
@Mock BinaryMessenger mockMessenger;
@Mock GoogleMap mockGoogleMap;
@Before
public void before() {
mockCloseable = MockitoAnnotations.openMocks(this);
context = ApplicationProvider.getApplicationContext();
setUpActivityLegacy();
googleMapController =
new GoogleMapController(0, context, mockMessenger, activity::getLifecycle, null);
googleMapController.init();
}
// TODO(stuartmorgan): Update this to a non-deprecated test API.
// See https://github.com/flutter/flutter/issues/122102
@SuppressWarnings("deprecation")
private void setUpActivityLegacy() {
activity = Robolectric.setupActivity(ComponentActivity.class);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void DisposeReleaseTheMap() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
assertTrue(googleMapController != null);
googleMapController.dispose();
assertNull(googleMapController.getView());
}
@Test
public void OnDestroyReleaseTheMap() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
assertTrue(googleMapController != null);
googleMapController.onDestroy(activity);
assertNull(googleMapController.getView());
}
@Test
public void OnMapReadySetsPaddingIfInitialPaddingIsThere() {
float padding = 10f;
int paddingWithDensity = (int) (padding * googleMapController.density);
googleMapController.setInitialPadding(padding, padding, padding, padding);
googleMapController.onMapReady(mockGoogleMap);
verify(mockGoogleMap, times(1))
.setPadding(paddingWithDensity, paddingWithDensity, paddingWithDensity, paddingWithDensity);
}
@Test
public void SetPaddingStoresThePaddingValuesInInInitialPaddingWhenGoogleMapIsNull() {
assertNull(googleMapController.initialPadding);
googleMapController.setPadding(0f, 0f, 0f, 0f);
assertNotNull(googleMapController.initialPadding);
Assert.assertEquals(4, googleMapController.initialPadding.size());
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapControllerTest.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapControllerTest.java",
"repo_id": "packages",
"token_count": 1045
} | 1,029 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.googlemapsexample">
<!-- Flutter needs internet permission to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name=".GoogleMapsTestActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
</application>
</manifest>
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 321
} | 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.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
class PaddingPage extends GoogleMapExampleAppPage {
const PaddingPage({Key? key})
: super(const Icon(Icons.map), 'Add padding to the map', key: key);
@override
Widget build(BuildContext context) {
return const MarkerIconsBody();
}
}
class MarkerIconsBody extends StatefulWidget {
const MarkerIconsBody({super.key});
@override
State<StatefulWidget> createState() => MarkerIconsBodyState();
}
const LatLng _kMapCenter = LatLng(52.4478, -3.5402);
class MarkerIconsBodyState extends State<MarkerIconsBody> {
ExampleGoogleMapController? controller;
EdgeInsets _padding = EdgeInsets.zero;
@override
Widget build(BuildContext context) {
final ExampleGoogleMap googleMap = ExampleGoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: _kMapCenter,
zoom: 7.0,
),
padding: _padding,
);
final List<Widget> columnChildren = <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
const Padding(
padding: EdgeInsets.only(top: 20),
child: Center(
child: Text(
'Enter Padding Below',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
),
];
columnChildren.addAll(<Widget>[_paddingInput(), _buttons()]);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
);
}
void _onMapCreated(ExampleGoogleMapController controllerParam) {
setState(() {
controller = controllerParam;
});
}
final TextEditingController _topController = TextEditingController();
final TextEditingController _bottomController = TextEditingController();
final TextEditingController _leftController = TextEditingController();
final TextEditingController _rightController = TextEditingController();
Widget _paddingInput() {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: <Widget>[
Flexible(
flex: 2,
child: TextField(
controller: _topController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Top',
),
),
),
const Spacer(),
Flexible(
flex: 2,
child: TextField(
controller: _bottomController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Bottom',
),
),
),
const Spacer(),
Flexible(
flex: 2,
child: TextField(
controller: _leftController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Left',
),
),
),
const Spacer(),
Flexible(
flex: 2,
child: TextField(
controller: _rightController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Right',
),
),
),
],
),
);
}
Widget _buttons() {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
child: const Text('Set Padding'),
onPressed: () {
setState(() {
_padding = EdgeInsets.fromLTRB(
double.tryParse(_leftController.value.text) ?? 0,
double.tryParse(_topController.value.text) ?? 0,
double.tryParse(_rightController.value.text) ?? 0,
double.tryParse(_bottomController.value.text) ?? 0);
});
},
),
TextButton(
child: const Text('Reset Padding'),
onPressed: () {
setState(() {
_topController.clear();
_bottomController.clear();
_leftController.clear();
_rightController.clear();
_padding = EdgeInsets.zero;
});
},
)
],
),
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart",
"repo_id": "packages",
"token_count": 2428
} | 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.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
const CameraPosition _kInitialPosition =
CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0);
class MapClickPage extends GoogleMapExampleAppPage {
const MapClickPage({Key? key})
: super(const Icon(Icons.mouse), 'Map click', key: key);
@override
Widget build(BuildContext context) {
return const _MapClickBody();
}
}
class _MapClickBody extends StatefulWidget {
const _MapClickBody();
@override
State<StatefulWidget> createState() => _MapClickBodyState();
}
class _MapClickBodyState extends State<_MapClickBody> {
_MapClickBodyState();
ExampleGoogleMapController? mapController;
LatLng? _lastTap;
LatLng? _lastLongPress;
@override
Widget build(BuildContext context) {
final ExampleGoogleMap googleMap = ExampleGoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: _kInitialPosition,
onTap: (LatLng pos) {
setState(() {
_lastTap = pos;
});
},
onLongPress: (LatLng pos) {
setState(() {
_lastLongPress = pos;
});
},
);
final List<Widget> columnChildren = <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
];
if (mapController != null) {
final String lastTap = 'Tap:\n${_lastTap ?? ""}\n';
final String lastLongPress = 'Long press:\n${_lastLongPress ?? ""}';
columnChildren.add(Center(
child: Text(
lastTap,
textAlign: TextAlign.center,
)));
columnChildren.add(Center(
child: Text(
_lastTap != null ? 'Tapped' : '',
textAlign: TextAlign.center,
)));
columnChildren.add(Center(
child: Text(
lastLongPress,
textAlign: TextAlign.center,
)));
columnChildren.add(Center(
child: Text(
_lastLongPress != null ? 'Long pressed' : '',
textAlign: TextAlign.center,
)));
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
);
}
Future<void> onMapCreated(ExampleGoogleMapController controller) async {
setState(() {
mapController = controller;
});
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_click.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_click.dart",
"repo_id": "packages",
"token_count": 1129
} | 1,032 |
name: maps_example_dart
description: Shared Dart code for the example apps.
publish_to: none
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
dependencies:
cupertino_icons: ^1.0.5
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter_ios:
# When depending on this package from a real application you should use:
# google_maps_flutter_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: ../../../
google_maps_flutter_platform_interface: ^2.5.0
dev_dependencies:
flutter_test:
sdk: flutter
stream_transform: ^2.0.0
flutter:
uses-material-design: true
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml",
"repo_id": "packages",
"token_count": 297
} | 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 "GoogleMapMarkerController.h"
#import "FLTGoogleMapJSONConversions.h"
@interface FLTGoogleMapMarkerController ()
@property(strong, nonatomic) GMSMarker *marker;
@property(weak, nonatomic) GMSMapView *mapView;
@property(assign, nonatomic, readwrite) BOOL consumeTapEvents;
@end
@implementation FLTGoogleMapMarkerController
- (instancetype)initMarkerWithPosition:(CLLocationCoordinate2D)position
identifier:(NSString *)identifier
mapView:(GMSMapView *)mapView {
self = [super init];
if (self) {
_marker = [GMSMarker markerWithPosition:position];
_mapView = mapView;
_marker.userData = @[ identifier ];
}
return self;
}
- (void)showInfoWindow {
self.mapView.selectedMarker = self.marker;
}
- (void)hideInfoWindow {
if (self.mapView.selectedMarker == self.marker) {
self.mapView.selectedMarker = nil;
}
}
- (BOOL)isInfoWindowShown {
return self.mapView.selectedMarker == self.marker;
}
- (void)removeMarker {
self.marker.map = nil;
}
- (void)setAlpha:(float)alpha {
self.marker.opacity = alpha;
}
- (void)setAnchor:(CGPoint)anchor {
self.marker.groundAnchor = anchor;
}
- (void)setDraggable:(BOOL)draggable {
self.marker.draggable = draggable;
}
- (void)setFlat:(BOOL)flat {
self.marker.flat = flat;
}
- (void)setIcon:(UIImage *)icon {
self.marker.icon = icon;
}
- (void)setInfoWindowAnchor:(CGPoint)anchor {
self.marker.infoWindowAnchor = anchor;
}
- (void)setInfoWindowTitle:(NSString *)title snippet:(NSString *)snippet {
self.marker.title = title;
self.marker.snippet = snippet;
}
- (void)setPosition:(CLLocationCoordinate2D)position {
self.marker.position = position;
}
- (void)setRotation:(CLLocationDegrees)rotation {
self.marker.rotation = rotation;
}
- (void)setVisible:(BOOL)visible {
self.marker.map = visible ? self.mapView : nil;
}
- (void)setZIndex:(int)zIndex {
self.marker.zIndex = zIndex;
}
- (void)interpretMarkerOptions:(NSDictionary *)data
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
NSNumber *alpha = data[@"alpha"];
if (alpha && alpha != (id)[NSNull null]) {
[self setAlpha:[alpha floatValue]];
}
NSArray *anchor = data[@"anchor"];
if (anchor && anchor != (id)[NSNull null]) {
[self setAnchor:[FLTGoogleMapJSONConversions pointFromArray:anchor]];
}
NSNumber *draggable = data[@"draggable"];
if (draggable && draggable != (id)[NSNull null]) {
[self setDraggable:[draggable boolValue]];
}
NSArray *icon = data[@"icon"];
if (icon && icon != (id)[NSNull null]) {
UIImage *image = [self extractIconFromData:icon registrar:registrar];
[self setIcon:image];
}
NSNumber *flat = data[@"flat"];
if (flat && flat != (id)[NSNull null]) {
[self setFlat:[flat boolValue]];
}
NSNumber *consumeTapEvents = data[@"consumeTapEvents"];
if (consumeTapEvents && consumeTapEvents != (id)[NSNull null]) {
[self setConsumeTapEvents:[consumeTapEvents boolValue]];
}
[self interpretInfoWindow:data];
NSArray *position = data[@"position"];
if (position && position != (id)[NSNull null]) {
[self setPosition:[FLTGoogleMapJSONConversions locationFromLatLong:position]];
}
NSNumber *rotation = data[@"rotation"];
if (rotation && rotation != (id)[NSNull null]) {
[self setRotation:[rotation doubleValue]];
}
NSNumber *visible = data[@"visible"];
if (visible && visible != (id)[NSNull null]) {
[self setVisible:[visible boolValue]];
}
NSNumber *zIndex = data[@"zIndex"];
if (zIndex && zIndex != (id)[NSNull null]) {
[self setZIndex:[zIndex intValue]];
}
}
- (void)interpretInfoWindow:(NSDictionary *)data {
NSDictionary *infoWindow = data[@"infoWindow"];
if (infoWindow && infoWindow != (id)[NSNull null]) {
NSString *title = infoWindow[@"title"];
NSString *snippet = infoWindow[@"snippet"];
if (title && title != (id)[NSNull null]) {
[self setInfoWindowTitle:title snippet:snippet];
}
NSArray *infoWindowAnchor = infoWindow[@"infoWindowAnchor"];
if (infoWindowAnchor && infoWindowAnchor != (id)[NSNull null]) {
[self setInfoWindowAnchor:[FLTGoogleMapJSONConversions pointFromArray:infoWindowAnchor]];
}
}
}
- (UIImage *)extractIconFromData:(NSArray *)iconData
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
UIImage *image;
if ([iconData.firstObject isEqualToString:@"defaultMarker"]) {
CGFloat hue = (iconData.count == 1) ? 0.0f : [iconData[1] doubleValue];
image = [GMSMarker markerImageWithColor:[UIColor colorWithHue:hue / 360.0
saturation:1.0
brightness:0.7
alpha:1.0]];
} else if ([iconData.firstObject isEqualToString:@"fromAsset"]) {
if (iconData.count == 2) {
image = [UIImage imageNamed:[registrar lookupKeyForAsset:iconData[1]]];
} else {
image = [UIImage imageNamed:[registrar lookupKeyForAsset:iconData[1]
fromPackage:iconData[2]]];
}
} else if ([iconData.firstObject isEqualToString:@"fromAssetImage"]) {
if (iconData.count == 3) {
image = [UIImage imageNamed:[registrar lookupKeyForAsset:iconData[1]]];
id scaleParam = iconData[2];
image = [self scaleImage:image by:scaleParam];
} else {
NSString *error =
[NSString stringWithFormat:@"'fromAssetImage' should have exactly 3 arguments. Got: %lu",
(unsigned long)iconData.count];
NSException *exception = [NSException exceptionWithName:@"InvalidBitmapDescriptor"
reason:error
userInfo:nil];
@throw exception;
}
} else if ([iconData[0] isEqualToString:@"fromBytes"]) {
if (iconData.count == 2) {
@try {
FlutterStandardTypedData *byteData = iconData[1];
CGFloat screenScale = [[UIScreen mainScreen] scale];
image = [UIImage imageWithData:[byteData data] scale:screenScale];
} @catch (NSException *exception) {
@throw [NSException exceptionWithName:@"InvalidByteDescriptor"
reason:@"Unable to interpret bytes as a valid image."
userInfo:nil];
}
} else {
NSString *error = [NSString
stringWithFormat:@"fromBytes should have exactly one argument, the bytes. Got: %lu",
(unsigned long)iconData.count];
NSException *exception = [NSException exceptionWithName:@"InvalidByteDescriptor"
reason:error
userInfo:nil];
@throw exception;
}
}
return image;
}
- (UIImage *)scaleImage:(UIImage *)image by:(id)scaleParam {
double scale = 1.0;
if ([scaleParam isKindOfClass:[NSNumber class]]) {
scale = [scaleParam doubleValue];
}
if (fabs(scale - 1) > 1e-3) {
return [UIImage imageWithCGImage:[image CGImage]
scale:(image.scale * scale)
orientation:(image.imageOrientation)];
}
return image;
}
@end
@interface FLTMarkersController ()
@property(strong, nonatomic) NSMutableDictionary *markerIdentifierToController;
@property(strong, nonatomic) FlutterMethodChannel *methodChannel;
@property(weak, nonatomic) NSObject<FlutterPluginRegistrar> *registrar;
@property(weak, nonatomic) GMSMapView *mapView;
@end
@implementation FLTMarkersController
- (instancetype)initWithMethodChannel:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_methodChannel = methodChannel;
_mapView = mapView;
_markerIdentifierToController = [[NSMutableDictionary alloc] init];
_registrar = registrar;
}
return self;
}
- (void)addMarkers:(NSArray *)markersToAdd {
for (NSDictionary *marker in markersToAdd) {
CLLocationCoordinate2D position = [FLTMarkersController getPosition:marker];
NSString *identifier = marker[@"markerId"];
FLTGoogleMapMarkerController *controller =
[[FLTGoogleMapMarkerController alloc] initMarkerWithPosition:position
identifier:identifier
mapView:self.mapView];
[controller interpretMarkerOptions:marker registrar:self.registrar];
self.markerIdentifierToController[identifier] = controller;
}
}
- (void)changeMarkers:(NSArray *)markersToChange {
for (NSDictionary *marker in markersToChange) {
NSString *identifier = marker[@"markerId"];
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller interpretMarkerOptions:marker registrar:self.registrar];
}
}
- (void)removeMarkersWithIdentifiers:(NSArray *)identifiers {
for (NSString *identifier in identifiers) {
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller removeMarker];
[self.markerIdentifierToController removeObjectForKey:identifier];
}
}
- (BOOL)didTapMarkerWithIdentifier:(NSString *)identifier {
if (!identifier) {
return NO;
}
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
return NO;
}
[self.methodChannel invokeMethod:@"marker#onTap" arguments:@{@"markerId" : identifier}];
return controller.consumeTapEvents;
}
- (void)didStartDraggingMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)location {
if (!identifier) {
return;
}
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
return;
}
[self.methodChannel invokeMethod:@"marker#onDragStart"
arguments:@{
@"markerId" : identifier,
@"position" : [FLTGoogleMapJSONConversions arrayFromLocation:location]
}];
}
- (void)didDragMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)location {
if (!identifier) {
return;
}
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
return;
}
[self.methodChannel invokeMethod:@"marker#onDrag"
arguments:@{
@"markerId" : identifier,
@"position" : [FLTGoogleMapJSONConversions arrayFromLocation:location]
}];
}
- (void)didEndDraggingMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)location {
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (!controller) {
return;
}
[self.methodChannel invokeMethod:@"marker#onDragEnd"
arguments:@{
@"markerId" : identifier,
@"position" : [FLTGoogleMapJSONConversions arrayFromLocation:location]
}];
}
- (void)didTapInfoWindowOfMarkerWithIdentifier:(NSString *)identifier {
if (identifier && self.markerIdentifierToController[identifier]) {
[self.methodChannel invokeMethod:@"infoWindow#onTap" arguments:@{@"markerId" : identifier}];
}
}
- (void)showMarkerInfoWindowWithIdentifier:(NSString *)identifier result:(FlutterResult)result {
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (controller) {
[controller showInfoWindow];
result(nil);
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"showInfoWindow called with invalid markerId"
details:nil]);
}
}
- (void)hideMarkerInfoWindowWithIdentifier:(NSString *)identifier result:(FlutterResult)result {
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (controller) {
[controller hideInfoWindow];
result(nil);
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"hideInfoWindow called with invalid markerId"
details:nil]);
}
}
- (void)isInfoWindowShownForMarkerWithIdentifier:(NSString *)identifier
result:(FlutterResult)result {
FLTGoogleMapMarkerController *controller = self.markerIdentifierToController[identifier];
if (controller) {
result(@([controller isInfoWindowShown]));
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"isInfoWindowShown called with invalid markerId"
details:nil]);
}
}
+ (CLLocationCoordinate2D)getPosition:(NSDictionary *)marker {
NSArray *position = marker[@"position"];
return [FLTGoogleMapJSONConversions locationFromLatLong:position];
}
@end
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapMarkerController.m/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapMarkerController.m",
"repo_id": "packages",
"token_count": 5763
} | 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.
/// Joint types for [Polyline].
enum JointType {
/// Mitered joint, with fixed pointed extrusion equal to half the stroke width on the outside of the joint.
///
/// Constant Value: 0
mitered._(0),
/// Flat bevel on the outside of the joint.
///
/// Constant Value: 1
bevel._(1),
/// Rounded on the outside of the joint by an arc of radius equal to half the stroke width, centered at the vertex.
///
/// Constant Value: 2
round._(2);
const JointType._(this.value);
/// The value representing the [JointType] on the sdk.
final int value;
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/joint_type.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/joint_type.dart",
"repo_id": "packages",
"token_count": 213
} | 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.
import 'package:flutter/foundation.dart' show immutable;
import 'types.dart';
/// Uniquely identifies a [TileOverlay] among [GoogleMap] tile overlays.
@immutable
class TileOverlayId extends MapsObjectId<TileOverlay> {
/// Creates an immutable identifier for a [TileOverlay].
const TileOverlayId(super.value);
}
/// A set of images which are displayed on top of the base map tiles.
///
/// These tiles may be transparent, allowing you to add features to existing maps.
///
/// ## Tile Coordinates
///
/// Note that the world is projected using the Mercator projection
/// (see [Wikipedia](https://en.wikipedia.org/wiki/Mercator_projection)) with the left (west) side
/// of the map corresponding to -180 degrees of longitude and the right (east) side of the map
/// corresponding to 180 degrees of longitude. To make the map square, the top (north) side of the
/// map corresponds to 85.0511 degrees of latitude and the bottom (south) side of the map
/// corresponds to -85.0511 degrees of latitude. Areas outside this latitude range are not rendered.
///
/// At each zoom level, the map is divided into tiles and only the tiles that overlap the screen are
/// downloaded and rendered. Each tile is square and the map is divided into tiles as follows:
///
/// * At zoom level 0, one tile represents the entire world. The coordinates of that tile are
/// (x, y) = (0, 0).
/// * At zoom level 1, the world is divided into 4 tiles arranged in a 2 x 2 grid.
/// * ...
/// * At zoom level N, the world is divided into 4N tiles arranged in a 2N x 2N grid.
///
/// Note that the minimum zoom level that the camera supports (which can depend on various factors)
/// is GoogleMap.getMinZoomLevel and the maximum zoom level is GoogleMap.getMaxZoomLevel.
///
/// The coordinates of the tiles are measured from the top left (northwest) corner of the map.
/// At zoom level N, the x values of the tile coordinates range from 0 to 2N - 1 and increase from
/// west to east and the y values range from 0 to 2N - 1 and increase from north to south.
@immutable
class TileOverlay implements MapsObject<TileOverlay> {
/// Creates an immutable representation of a [TileOverlay] to draw on [GoogleMap].
const TileOverlay({
required this.tileOverlayId,
this.fadeIn = true,
this.tileProvider,
this.transparency = 0.0,
this.zIndex = 0,
this.visible = true,
this.tileSize = 256,
}) : assert(transparency >= 0.0 && transparency <= 1.0);
/// Uniquely identifies a [TileOverlay].
final TileOverlayId tileOverlayId;
@override
TileOverlayId get mapsId => tileOverlayId;
/// Whether the tiles should fade in. The default is true.
final bool fadeIn;
/// The tile provider to use for this tile overlay.
final TileProvider? tileProvider;
/// The transparency of the tile overlay. The default transparency is 0 (opaque).
final double transparency;
/// The tile overlay's zIndex, i.e., the order in which it will be drawn where
/// overlays with larger values are drawn above those with lower values
final int zIndex;
/// The visibility for the tile overlay. The default visibility is true.
final bool visible;
/// Specifies the number of logical pixels (not points) that the returned tile images will prefer
/// to display as. iOS only.
///
/// Defaults to 256, which is the traditional size of Google Maps tiles.
/// As an example, an application developer may wish to provide retina tiles (512 pixel edge length)
/// on retina devices, to keep the same number of tiles per view as the default value of 256
/// would give on a non-retina device.
final int tileSize;
/// Creates a new [TileOverlay] object whose values are the same as this instance,
/// unless overwritten by the specified parameters.
TileOverlay copyWith({
bool? fadeInParam,
TileProvider? tileProviderParam,
double? transparencyParam,
int? zIndexParam,
bool? visibleParam,
int? tileSizeParam,
}) {
return TileOverlay(
tileOverlayId: tileOverlayId,
fadeIn: fadeInParam ?? fadeIn,
tileProvider: tileProviderParam ?? tileProvider,
transparency: transparencyParam ?? transparency,
zIndex: zIndexParam ?? zIndex,
visible: visibleParam ?? visible,
tileSize: tileSizeParam ?? tileSize,
);
}
@override
TileOverlay clone() => copyWith();
/// Converts this object to JSON.
@override
Object toJson() {
final Map<String, Object> json = <String, Object>{};
void addIfPresent(String fieldName, Object? value) {
if (value != null) {
json[fieldName] = value;
}
}
addIfPresent('tileOverlayId', tileOverlayId.value);
addIfPresent('fadeIn', fadeIn);
addIfPresent('transparency', transparency);
addIfPresent('zIndex', zIndex);
addIfPresent('visible', visible);
addIfPresent('tileSize', tileSize);
return json;
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is TileOverlay &&
tileOverlayId == other.tileOverlayId &&
fadeIn == other.fadeIn &&
tileProvider == other.tileProvider &&
transparency == other.transparency &&
zIndex == other.zIndex &&
visible == other.visible &&
tileSize == other.tileSize;
}
@override
int get hashCode => Object.hash(tileOverlayId, fadeIn, tileProvider,
transparency, zIndex, visible, tileSize);
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart",
"repo_id": "packages",
"token_count": 1672
} | 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:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Store the initial instance before any tests change it.
final GoogleMapsFlutterPlatform initialInstance =
GoogleMapsFlutterPlatform.instance;
group('$GoogleMapsFlutterPlatform', () {
test('$MethodChannelGoogleMapsFlutter() is the default instance', () {
expect(initialInstance, isInstanceOf<MethodChannelGoogleMapsFlutter>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
GoogleMapsFlutterPlatform.instance =
ImplementsGoogleMapsFlutterPlatform();
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes
// throw a `NoSuchMethodError` and other times throw an
// `AssertionError`. After the issue is fixed, an `AssertionError` will
// always be thrown. For the purpose of this test, we don't really care
// what exception is thrown, so just allow any exception.
}, throwsA(anything));
});
test('Can be mocked with `implements`', () {
final GoogleMapsFlutterPlatformMock mock =
GoogleMapsFlutterPlatformMock();
GoogleMapsFlutterPlatform.instance = mock;
});
test('Can be extended', () {
GoogleMapsFlutterPlatform.instance = ExtendsGoogleMapsFlutterPlatform();
});
test(
'default implementation of `buildViewWithTextDirection` delegates to `buildView`',
() {
final GoogleMapsFlutterPlatform platform =
BuildViewGoogleMapsFlutterPlatform();
expect(
platform.buildViewWithTextDirection(
0,
(_) {},
initialCameraPosition:
const CameraPosition(target: LatLng(0.0, 0.0)),
textDirection: TextDirection.ltr,
),
isA<Text>(),
);
},
);
test(
'default implementation of `buildViewWithConfiguration` delegates to `buildViewWithTextDirection`',
() {
final GoogleMapsFlutterPlatform platform =
BuildViewGoogleMapsFlutterPlatform();
expect(
platform.buildViewWithConfiguration(
0,
(_) {},
widgetConfiguration: const MapWidgetConfiguration(
initialCameraPosition: CameraPosition(target: LatLng(0.0, 0.0)),
textDirection: TextDirection.ltr,
),
),
isA<Text>(),
);
},
);
test(
'updateClusterManagers() throws UnimplementedError',
() {
expect(
() => BuildViewGoogleMapsFlutterPlatform().updateClusterManagers(
ClusterManagerUpdates.from(
<ClusterManager>{
const ClusterManager(
clusterManagerId: ClusterManagerId('123'))
},
<ClusterManager>{
const ClusterManager(
clusterManagerId: ClusterManagerId('456'))
},
),
mapId: 0),
throwsUnimplementedError);
},
);
test(
'onClusterTap() throws UnimplementedError',
() {
expect(
() => BuildViewGoogleMapsFlutterPlatform().onClusterTap(mapId: 0),
throwsUnimplementedError);
},
);
test(
'default implementation of `getStyleError` returns null',
() async {
final GoogleMapsFlutterPlatform platform =
BuildViewGoogleMapsFlutterPlatform();
expect(await platform.getStyleError(mapId: 0), null);
},
);
});
}
class GoogleMapsFlutterPlatformMock extends Mock
with MockPlatformInterfaceMixin
implements GoogleMapsFlutterPlatform {}
class ImplementsGoogleMapsFlutterPlatform extends Mock
implements GoogleMapsFlutterPlatform {}
class ExtendsGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform {}
class BuildViewGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform {
@override
Widget buildView(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required CameraPosition initialCameraPosition,
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<Circle> circles = const <Circle>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
Set<ClusterManager> clusterManagers = const <ClusterManager>{},
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers =
const <Factory<OneSequenceGestureRecognizer>>{},
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
return const Text('');
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart",
"repo_id": "packages",
"token_count": 2127
} | 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.
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
/// Function that gets the [MapConfiguration] for a given `mapId`.
typedef ConfigurationProvider = MapConfiguration Function(int mapId);
/// This platform implementation allows inspecting the running maps.
class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform {
/// Build an "inspector" that is able to look into maps.
GoogleMapsInspectorWeb(ConfigurationProvider configurationProvider)
: _configurationProvider = configurationProvider;
final ConfigurationProvider _configurationProvider;
@override
Future<bool> areBuildingsEnabled({required int mapId}) async {
return false; // Not supported on the web
}
@override
Future<bool> areRotateGesturesEnabled({required int mapId}) async {
return false; // Not supported on the web
}
@override
Future<bool> areScrollGesturesEnabled({required int mapId}) async {
return _configurationProvider(mapId).scrollGesturesEnabled ?? false;
}
@override
Future<bool> areTiltGesturesEnabled({required int mapId}) async {
return false; // Not supported on the web
}
@override
Future<bool> areZoomControlsEnabled({required int mapId}) async {
return _configurationProvider(mapId).zoomControlsEnabled ?? false;
}
@override
Future<bool> areZoomGesturesEnabled({required int mapId}) async {
return _configurationProvider(mapId).zoomGesturesEnabled ?? false;
}
@override
Future<MinMaxZoomPreference> getMinMaxZoomLevels({required int mapId}) async {
final MapConfiguration config = _configurationProvider(mapId);
assert(config.minMaxZoomPreference != null);
return config.minMaxZoomPreference!;
}
@override
Future<TileOverlay?> getTileOverlayInfo(
TileOverlayId tileOverlayId, {
required int mapId,
}) async {
return null; // Custom tiles not supported on the web
}
@override
Future<bool> isCompassEnabled({required int mapId}) async {
return false; // There's no compass on the web
}
@override
Future<bool> isLiteModeEnabled({required int mapId}) async {
return false; // There's no lite mode on the web
}
@override
Future<bool> isMapToolbarEnabled({required int mapId}) async {
return false; // There's no Map Toolbar on the web
}
@override
Future<bool> isMyLocationButtonEnabled({required int mapId}) async {
return false; // My Location widget not supported on the web
}
@override
Future<bool> isTrafficEnabled({required int mapId}) async {
return _configurationProvider(mapId).trafficEnabled ?? false;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart",
"repo_id": "packages",
"token_count": 830
} | 1,038 |
// 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.
/// A regular expression that matches against the "size directive" path
/// segment of Google profile image URLs.
///
/// The format is is "`/sNN-c/`", where `NN` is the max width/height of the
/// image, and "`c`" indicates we want the image cropped.
final RegExp sizeDirective = RegExp(r'^s[0-9]{1,5}(-c)?$');
/// Adds [size] (and crop) directive to [photoUrl].
///
/// There are two formats for photoUrls coming from the Sign In backend.
///
/// The two formats can be told apart by the number of path segments in the
/// URL (path segments: parts of the URL separated by slashes "/"):
///
/// * If the URL has 2 or less path segments, it is a *new* style URL.
/// * If the URL has more than 2 path segments, it is an old style URL.
///
/// Old style URLs encode the image transformation directives as the last
/// path segment. Look at the [sizeDirective] Regular Expression for more
/// information about these URLs.
///
/// New style URLs carry the same directives at the end of the URL,
/// after an = sign, like: "`=s120-c-fSoften=1,50,0`".
///
/// Directives may contain the "=" sign (`fSoften=1,50,0`), but it seems the
/// base URL of the images don't. "Everything after the first = sign" is a
/// good heuristic to split new style URLs.
///
/// Each directive is separated from others by dashes. Directives are the same
/// as described in the [sizeDirective] RegExp.
///
/// Modified image URLs are recomposed by performing the parsing steps in reverse.
String addSizeDirectiveToUrl(String photoUrl, double size) {
final Uri profileUri = Uri.parse(photoUrl);
final List<String> pathSegments = List<String>.from(profileUri.pathSegments);
if (pathSegments.length <= 2) {
final String imagePath = pathSegments.last;
// Does this have any existing transformation directives?
final int directiveSeparator = imagePath.indexOf('=');
if (directiveSeparator >= 0) {
// Split the baseUrl from the sizing directive by the first "="
final String baseUrl = imagePath.substring(0, directiveSeparator);
final String directive = imagePath.substring(directiveSeparator + 1);
// Split the directive by "-"
final Set<String> directives = Set<String>.from(directive.split('-'))
// Remove the size directive, if present, and any empty values
..removeWhere((String s) => s.isEmpty || sizeDirective.hasMatch(s))
// Add the size and crop directives
..addAll(<String>['c', 's${size.round()}']);
// Recompose the URL by performing the reverse of the parsing
pathSegments.last = '$baseUrl=${directives.join("-")}';
} else {
pathSegments.last = '${pathSegments.last}=c-s${size.round()}';
}
} else {
// Old style URLs
pathSegments
..removeWhere(sizeDirective.hasMatch)
..insert(pathSegments.length - 1, 's${size.round()}-c');
}
return Uri(
scheme: profileUri.scheme,
host: profileUri.host,
pathSegments: pathSegments,
).toString();
}
| packages/packages/google_sign_in/google_sign_in/lib/src/fife.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/lib/src/fife.dart",
"repo_id": "packages",
"token_count": 997
} | 1,039 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.googlesignin">
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
| packages/packages/google_sign_in/google_sign_in_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_android/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 67
} | 1,040 |
name: google_sign_in_example
description: Example of Google Sign-In plugin.
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
google_sign_in_android:
# When depending on this package from a real application you should use:
# google_sign_in_android: ^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: ../
google_sign_in_platform_interface: ^2.2.0
http: ">=0.13.0 <2.0.0"
dev_dependencies:
espresso: ^0.2.0
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 293
} | 1,041 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in_ios/google_sign_in_ios.dart';
import 'package:google_sign_in_ios/src/messages.g.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'google_sign_in_ios_test.mocks.dart';
final GoogleSignInUserData _user = GoogleSignInUserData(
email: '[email protected]',
id: '8162538176523816253123',
photoUrl: 'https://lh5.googleusercontent.com/photo.jpg',
displayName: 'John Doe',
serverAuthCode: '789',
idToken: '123');
final GoogleSignInTokenData _token = GoogleSignInTokenData(
idToken: '123',
accessToken: '456',
);
@GenerateMocks(<Type>[GoogleSignInApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late GoogleSignInIOS googleSignIn;
late MockGoogleSignInApi api;
setUp(() {
api = MockGoogleSignInApi();
googleSignIn = GoogleSignInIOS(api: api);
});
test('registered instance', () {
GoogleSignInIOS.registerWith();
expect(GoogleSignInPlatform.instance, isA<GoogleSignInIOS>());
});
test('init throws for SignInOptions.games', () async {
expect(
() => googleSignIn.init(
hostedDomain: 'example.com',
signInOption: SignInOption.games,
clientId: 'fakeClientId'),
throwsA(isInstanceOf<PlatformException>().having(
(PlatformException e) => e.code, 'code', 'unsupported-options')));
});
test('signInSilently transforms platform data to GoogleSignInUserData',
() async {
when(api.signInSilently()).thenAnswer((_) async => UserData(
email: _user.email,
userId: _user.id,
photoUrl: _user.photoUrl,
displayName: _user.displayName,
serverAuthCode: _user.serverAuthCode,
idToken: _user.idToken,
));
final dynamic response = await googleSignIn.signInSilently();
expect(response, _user);
});
test('signInSilently Exceptions -> throws', () async {
when(api.signInSilently())
.thenAnswer((_) async => throw PlatformException(code: 'fail'));
expect(googleSignIn.signInSilently(),
throwsA(isInstanceOf<PlatformException>()));
});
test('signIn transforms platform data to GoogleSignInUserData', () async {
when(api.signIn()).thenAnswer((_) async => UserData(
email: _user.email,
userId: _user.id,
photoUrl: _user.photoUrl,
displayName: _user.displayName,
serverAuthCode: _user.serverAuthCode,
idToken: _user.idToken,
));
final dynamic response = await googleSignIn.signIn();
expect(response, _user);
});
test('signIn Exceptions -> throws', () async {
when(api.signIn())
.thenAnswer((_) async => throw PlatformException(code: 'fail'));
expect(googleSignIn.signIn(), throwsA(isInstanceOf<PlatformException>()));
});
test('getTokens transforms platform data to GoogleSignInTokenData', () async {
const bool recoverAuth = false;
when(api.getAccessToken()).thenAnswer((_) async =>
TokenData(idToken: _token.idToken, accessToken: _token.accessToken));
final GoogleSignInTokenData response = await googleSignIn.getTokens(
email: _user.email, shouldRecoverAuth: recoverAuth);
expect(response, _token);
});
test('clearAuthCache silently no-ops', () async {
expect(googleSignIn.clearAuthCache(token: 'abc'), completes);
});
test('initWithParams passes arguments', () async {
const SignInInitParameters initParams = SignInInitParameters(
hostedDomain: 'example.com',
scopes: <String>['two', 'scopes'],
clientId: 'fakeClientId',
);
await googleSignIn.init(
hostedDomain: initParams.hostedDomain,
scopes: initParams.scopes,
signInOption: initParams.signInOption,
clientId: initParams.clientId,
);
final VerificationResult result = verify(api.init(captureAny));
final InitParams passedParams = result.captured[0] as InitParams;
expect(passedParams.hostedDomain, initParams.hostedDomain);
expect(passedParams.scopes, initParams.scopes);
expect(passedParams.clientId, initParams.clientId);
// This should use whatever the SignInInitParameters defaults are.
expect(passedParams.serverClientId, initParams.serverClientId);
});
test('initWithParams passes arguments', () async {
const SignInInitParameters initParams = SignInInitParameters(
hostedDomain: 'example.com',
scopes: <String>['two', 'scopes'],
clientId: 'fakeClientId',
serverClientId: 'fakeServerClientId',
forceCodeForRefreshToken: true,
);
await googleSignIn.initWithParams(initParams);
final VerificationResult result = verify(api.init(captureAny));
final InitParams passedParams = result.captured[0] as InitParams;
expect(passedParams.hostedDomain, initParams.hostedDomain);
expect(passedParams.scopes, initParams.scopes);
expect(passedParams.clientId, initParams.clientId);
expect(passedParams.serverClientId, initParams.serverClientId);
});
test('requestScopes passes arguments', () async {
const List<String> scopes = <String>['newScope', 'anotherScope'];
when(api.requestScopes(scopes)).thenAnswer((_) async => true);
final bool response = await googleSignIn.requestScopes(scopes);
expect(response, true);
});
test('signOut calls through', () async {
await googleSignIn.signOut();
verify(api.signOut());
});
test('disconnect calls through', () async {
await googleSignIn.disconnect();
verify(api.disconnect());
});
test('isSignedIn passes true response', () async {
when(api.isSignedIn()).thenAnswer((_) async => true);
expect(await googleSignIn.isSignedIn(), true);
});
test('isSignedIn passes false response', () async {
when(api.isSignedIn()).thenAnswer((_) async => false);
expect(await googleSignIn.isSignedIn(), false);
});
}
| packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart",
"repo_id": "packages",
"token_count": 2272
} | 1,042 |
# google\_sign\_in\_web
The web implementation of [google_sign_in](https://pub.dev/packages/google_sign_in)
## Migrating to v0.11 and v0.12 (Google Identity Services)
The `google_sign_in_web` plugin is backed by the new Google Identity Services
(GIS) JS SDK since version 0.11.0.
The GIS SDK is used both for [Authentication](https://developers.google.com/identity/gsi/web/guides/overview)
and [Authorization](https://developers.google.com/identity/oauth2/web/guides/overview) flows.
The GIS SDK, however, doesn't behave exactly like the one being deprecated.
Some concepts have experienced pretty drastic changes, and that's why this
plugin required a major version update.
### Differences between Google Identity Services SDK and Google Sign-In for Web SDK.
The **Google Sign-In JavaScript for Web JS SDK** is set to be deprecated after
March 31, 2023. **Google Identity Services (GIS) SDK** is the new solution to
quickly and easily sign users into your app suing their Google accounts.
* In the GIS SDK, Authentication and Authorization are now two separate concerns.
* Authentication (information about the current user) flows will not
authorize `scopes` anymore.
* Authorization (permissions for the app to access certain user information)
flows will not return authentication information.
* The GIS SDK no longer has direct access to previously-seen users upon initialization.
* `signInSilently` now displays the One Tap UX for web.
* **Since 0.12** The plugin provides an `idToken` (JWT-encoded info) when the
user successfully completes an authentication flow:
* In the plugin: `signInSilently` and through the web-only `renderButton` widget.
* The plugin `signIn` method uses the OAuth "Implicit Flow" to Authorize the requested `scopes`.
* This method only provides an `accessToken`, and not an `idToken`, so if your
app needs an `idToken`, this method **should be avoided on the web**.
* The GIS SDK no longer handles sign-in state and user sessions, it only provides
Authentication credentials for the moment the user did authenticate.
* The GIS SDK no longer is able to renew Authorization sessions on the web.
Once the token expires, API requests will begin to fail with unauthorized,
and user Authorization is required again.
See more differences in the following migration guides:
* Authentication > [Migrating from Google Sign-In](https://developers.google.com/identity/gsi/web/guides/migration)
* Authorization > [Migrate to Google Identity Services](https://developers.google.com/identity/oauth2/web/guides/migration-to-gis)
### New use cases to take into account in your app
#### Authentication != Authorization
In the GIS SDK, the concepts of Authentication and Authorization have been separated.
It is possible now to have an Authenticated user that hasn't Authorized any `scopes`.
Flutter apps that need to run in the web must now handle the fact that an Authenticated
user may not have permissions to access the `scopes` it requires to function.
The Google Sign In plugin has a new `canAccessScopes` method that can be used to
check if a user is Authorized or not.
It is also possible that Authorizations expire while users are using an app
(after 3600 seconds), so apps should monitor response failures from the APIs, and
prompt users (interactively) to grant permissions again.
Check the "Integration considerations > [UX separation for authentication and authorization](https://developers.google.com/identity/gsi/web/guides/integrate#ux_separation_for_authentication_and_authorization)
guide" in the official GIS SDK documentation for more information about this.
_(See also the [package:google_sign_in example app](https://pub.dev/packages/google_sign_in/example)
for a simple implementation of this (look at the `isAuthorized` variable).)_
#### Is this separation *always required*?
Only if the scopes required by an app are different from the
[OpenID Connect scopes](https://developers.google.com/identity/protocols/oauth2/scopes#openid-connect).
If an app only needs an `idToken`, or the OpenID Connect scopes, the Authentication
bits of the plugin should be enough for your app (`signInSilently` and `renderButton`).
### What happened to the `signIn` method on the web?
Because the GIS SDK for web no longer provides users with the ability to create
their own Sign-In buttons, or an API to start the sign in flow, the current
implementation of `signIn` (that does authorization and authentication) is no
longer feasible on the web.
The web plugin attempts to simulate the old `signIn` behavior by using the
[OAuth Implicit pop-up flow](https://developers.google.com/identity/oauth2/web/guides/use-token-model),
which authenticates and authorizes users.
The drawback of this approach is that the OAuth flow **only returns an `accessToken`**,
and a synthetic version of the User Data, that does **not include an `idToken`**.
The solution to this is to **migrate your custom "Sign In" buttons in the web to
the Button Widget provided by this package: `Widget renderButton()`.**
_(Check the [package:google_sign_in example app](https://pub.dev/packages/google_sign_in/example)
for an example on how to mix the `renderButton` widget on the web, with a custom
button for the mobile.)_
#### Enable access to the People API for your GCP project
If you want to use the `signIn` method on the web, the plugin will do an additional
request to the PeopleAPI to retrieve the logged-in user information (minus the `idToken`).
For this to work, you must enable access to the People API on your Client ID in
the GCP console.
This is **not recommended**. Ideally, your web application should use a mix of
`signInSilently` and the Google Sign In web `renderButton` to authenticate your
users, and then `canAccessScopes` and `requestScopes` to authorize the `scopes`
that are needed.
#### Why is the `idToken` missing after `signIn`?
The `idToken` is cryptographically signed by Google Identity Services, and
this plugin can't spoof that signature.
#### User Sessions
Since the GIS SDK does _not_ manage user sessions anymore, apps that relied on
this feature might break.
If long-lived sessions are required, consider using some user authentication
system that supports Google Sign In as a federated Authentication provider,
like [Firebase Auth](https://firebase.google.com/docs/auth/flutter/federated-auth#google),
or similar.
#### Expired / Invalid Authorization Tokens
Since the GIS SDK does _not_ auto-renew authorization tokens anymore, it's now
the responsibility of your app to do so.
Apps now need to monitor the status code of their REST API requests for response
codes different to `200`. For example:
* `401`: Missing or invalid access token.
* `403`: Expired access token.
In either case, your app needs to prompt the end user to `requestScopes`, to
**interactively** renew the token.
The GIS SDK limits authorization token duration to one hour (3600 seconds).
## Usage
### Import the package
This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),
which means you can simply use `google_sign_in`
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.
For example, you need to import this package directly if you plan to use the
web-only `Widget renderButton()` method.
### Web integration
First, go through the instructions [here](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid) to create your Google Sign-In OAuth client ID.
On your `web/index.html` file, add the following `meta` tag, somewhere in the
`head` of the document:
```html
<meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">
```
For this client to work correctly, the last step is to configure the **Authorized JavaScript origins**, which _identify the domains from which your application can send API requests._ When in local development, this is normally `localhost` and some port.
You can do this by:
1. Going to the [Credentials page](https://console.developers.google.com/apis/credentials).
2. Clicking "Edit" in the OAuth 2.0 Web application client that you created above.
3. Adding the URIs you want to the **Authorized JavaScript origins**.
For local development, you must add two `localhost` entries:
* `http://localhost` and
* `http://localhost:7357` (or any port that is free in your machine)
#### Starting flutter in http://localhost:7357
Normally `flutter run` starts in a random port. In the case where you need to deal with authentication like the above, that's not the most appropriate behavior.
You can tell `flutter run` to listen for requests in a specific host and port with the following:
```sh
flutter run -d chrome --web-hostname localhost --web-port 7357
```
### Other APIs
Read the rest of the instructions if you need to add extra APIs (like Google People API).
### Using the plugin
See the [**Usage** instructions of `package:google_sign_in`](https://pub.dev/packages/google_sign_in#usage)
Note that the **`serverClientId` parameter of the `GoogleSignIn` constructor is not supported on Web.**
## Example
Find the example wiring in the [Google sign-in example application](https://github.com/flutter/packages/blob/main/packages/google_sign_in/google_sign_in/example/lib/main.dart).
## API details
See [google_sign_in.dart](https://github.com/flutter/packages/blob/main/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart) for more API details.
## Contributions and Testing
Tests are crucial for contributions to this package. All new contributions should be reasonably tested.
**Check the [`test/README.md` file](https://github.com/flutter/packages/blob/main/packages/google_sign_in/google_sign_in_web/test/README.md)** for more information on how to run tests on this package.
Contributions to this package are welcome. Read the [Contributing to Flutter Plugins](https://github.com/flutter/packages/blob/main/CONTRIBUTING.md) guide to get started.
## Issues and feedback
Please file [issues](https://github.com/flutter/flutter/issues/new)
to send feedback or report a bug.
**Thank you!**
| packages/packages/google_sign_in/google_sign_in_web/README.md/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/README.md",
"repo_id": "packages",
"token_count": 2809
} | 1,043 |
name: google_sign_in_web_integration_tests
publish_to: none
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
google_identity_services_web: ^0.3.1
google_sign_in_platform_interface: ^2.4.0
google_sign_in_web:
path: ../
dev_dependencies:
build_runner: ^2.1.1
flutter_test:
sdk: flutter
http: ">=0.13.0 <2.0.0"
integration_test:
sdk: flutter
mockito: 5.4.4
web: ^0.5.0
flutter:
uses-material-design: true
| packages/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 240
} | 1,044 |
# Image Picker plugin for Flutter
<?code-excerpt path-base="example/lib"?>
[](https://pub.dev/packages/image_picker)
A Flutter plugin for iOS and Android for picking images from the image library,
and taking new pictures with the camera.
| | Android | iOS | Linux | macOS | Web | Windows |
|-------------|---------|---------|-------|--------|---------------------------------|-------------|
| **Support** | SDK 21+ | iOS 12+ | Any | 10.14+ | [See `image_picker_for_web`](https://pub.dev/packages/image_picker_for_web#limitations-on-the-web-platform) | Windows 10+ |
## Installation
First, add `image_picker` as a
[dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels).
### iOS
Starting with version **0.8.1** the iOS implementation uses PHPicker to pick
(multiple) images on iOS 14 or higher.
As a result of implementing PHPicker it becomes impossible to pick HEIC images
on the iOS simulator in iOS 14+. This is a known issue. Please test this on a
real device, or test with non-HEIC images until Apple solves this issue.
[63426347 - Apple known issue](https://www.google.com/search?q=63426347+apple&sxsrf=ALeKk01YnTMid5S0PYvhL8GbgXJ40ZS[…]t=gws-wiz&ved=0ahUKEwjKh8XH_5HwAhWL_rsIHUmHDN8Q4dUDCA8&uact=5)
Add the following keys to your _Info.plist_ file, located in
`<project root>/ios/Runner/Info.plist`:
* `NSPhotoLibraryUsageDescription` - describe why your app needs permission for
the photo library. This is called _Privacy - Photo Library Usage Description_ in
the visual editor.
* This permission will not be requested if you always pass `false` for
`requestFullMetadata`, but App Store policy requires including the plist
entry.
* `NSCameraUsageDescription` - describe why your app needs access to the camera.
This is called _Privacy - Camera Usage Description_ in the visual editor.
* `NSMicrophoneUsageDescription` - describe why your app needs access to the
microphone, if you intend to record videos. This is called
_Privacy - Microphone Usage Description_ in the visual editor.
### Android
Starting with version **0.8.1** the Android implementation support to pick
(multiple) images on Android 4.3 or higher.
No configuration required - the plugin should work out of the box. It is however
highly recommended to prepare for Android killing the application when low on memory. How to prepare for this is discussed in the
[Handling MainActivity destruction on Android](#handling-mainactivity-destruction-on-android)
section.
It is no longer required to add `android:requestLegacyExternalStorage="true"` as
an attribute to the `<application>` tag in AndroidManifest.xml, as
`image_picker` has been updated to make use of scoped storage.
#### Handling MainActivity destruction
When under high memory pressure the Android system may kill the MainActivity of
the application using the image_picker. On Android the image_picker makes use
of the default `Intent.ACTION_GET_CONTENT` or `MediaStore.ACTION_IMAGE_CAPTURE`
intents. This means that while the intent is executing the source application
is moved to the background and becomes eligible for cleanup when the system is
low on memory. When the intent finishes executing, Android will restart the
application. Since the data is never returned to the original call use the
`ImagePicker.retrieveLostData()` method to retrieve the lost data. For example:
<?code-excerpt "readme_excerpts.dart (LostData)"?>
```dart
Future<void> getLostData() async {
final ImagePicker picker = ImagePicker();
final LostDataResponse response = await picker.retrieveLostData();
if (response.isEmpty) {
return;
}
final List<XFile>? files = response.files;
if (files != null) {
_handleLostFiles(files);
} else {
_handleError(response.exception);
}
}
```
This check should always be run at startup in order to detect and handle this
case. Please refer to the
[example app](https://pub.dev/packages/image_picker/example) for a more complete
example of handling this flow.
#### Permanently storing images and videos
Images and videos picked using the camera are saved to your application's local
cache, and should therefore be expected to only be around temporarily.
If you require your picked image to be stored permanently, it is your
responsibility to move it to a more permanent location.
#### Android Photo Picker
This package has optional
[Android Photo Picker](https://developer.android.com/training/data-storage/shared/photopicker)
functionality.
[Learn how to use it](https://pub.dev/packages/image_picker_android).
#### Using `launchMode: singleInstance`
Launching the image picker from an `Activity` with `launchMode: singleInstance`
will always return `RESULT_CANCELED`.
In this launch mode, new activities are created in a separate [Task](https://developer.android.com/guide/components/activities/tasks-and-back-stack).
As activities cannot communicate between tasks, the image picker activity cannot
send back its eventual result to the calling activity.
To work around this problem, consider using `launchMode: singleTask` instead.
### Windows, macOS, and Linux
This plugin currently has limited support for the three desktop platforms,
serving as a wrapper around the [`file_selector`](https://pub.dev/packages/file_selector)
plugin with appropriate file type filters set. Selection modification options,
such as max width and height, are not yet supported.
By default, `ImageSource.camera` is not supported, since unlike on Android and
iOS there is no system-provided UI for taking photos. However, the desktop
implementations allow delegating to a camera handler by setting a
`cameraDelegate` before using `image_picker`, such as in `main()`:
<?code-excerpt "readme_excerpts.dart (CameraDelegate)"?>
```dart
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
// ···
class MyCameraDelegate extends ImagePickerCameraDelegate {
@override
Future<XFile?> takePhoto(
{ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions()}) async {
return _takeAPhoto(options.preferredCameraDevice);
}
@override
Future<XFile?> takeVideo(
{ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions()}) async {
return _takeAVideo(options.preferredCameraDevice);
}
}
// ···
void setUpCameraDelegate() {
final ImagePickerPlatform instance = ImagePickerPlatform.instance;
if (instance is CameraDelegatingImagePickerPlatform) {
instance.cameraDelegate = MyCameraDelegate();
}
}
```
Once you have set a `cameraDelegate`, `image_picker` calls with
`ImageSource.camera` will work as normal, calling your provided delegate. We
encourage the community to build packages that implement
`ImagePickerCameraDelegate`, to provide options for desktop camera UI.
#### macOS installation
Since the macOS implementation uses `file_selector`, you will need to
add a filesystem access
[entitlement](https://docs.flutter.dev/platform-integration/macos/building#entitlements-and-the-app-sandbox):
```xml
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
```
### Example
<?code-excerpt "readme_excerpts.dart (Pick)"?>
```dart
final ImagePicker picker = ImagePicker();
// Pick an image.
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
// Capture a photo.
final XFile? photo = await picker.pickImage(source: ImageSource.camera);
// Pick a video.
final XFile? galleryVideo =
await picker.pickVideo(source: ImageSource.gallery);
// Capture a video.
final XFile? cameraVideo = await picker.pickVideo(source: ImageSource.camera);
// Pick multiple images.
final List<XFile> images = await picker.pickMultiImage();
// Pick singe image or video.
final XFile? media = await picker.pickMedia();
// Pick multiple images and videos.
final List<XFile> medias = await picker.pickMultipleMedia();
```
## Migrating to 1.0
Starting with version 0.8.2 of the image_picker plugin, new methods were
added that return `XFile` instances (from the
[cross_file](https://pub.dev/packages/cross_file) package) rather than the
plugin's own `PickedFile` instances. The previous methods were supported through
0.8.9, and removed in 1.0.0.
#### Call the new methods
| Old API | New API |
|---------|---------|
| `PickedFile image = await _picker.getImage(...)` | `XFile image = await _picker.pickImage(...)` |
| `List<PickedFile> images = await _picker.getMultiImage(...)` | `List<XFile> images = await _picker.pickMultiImage(...)` |
| `PickedFile video = await _picker.getVideo(...)` | `XFile video = await _picker.pickVideo(...)` |
| `LostData response = await _picker.getLostData()` | `LostDataResponse response = await _picker.retrieveLostData()` |
| packages/packages/image_picker/image_picker/README.md/0 | {
"file_path": "packages/packages/image_picker/image_picker/README.md",
"repo_id": "packages",
"token_count": 2581
} | 1,045 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/image_picker/image_picker/example/android/gradle.properties/0 | {
"file_path": "packages/packages/image_picker/image_picker/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,046 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| packages/packages/image_picker/image_picker_android/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "packages",
"token_count": 73
} | 1,047 |
// 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.imagepicker;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import androidx.annotation.Nullable;
import io.flutter.plugins.imagepicker.Messages.FlutterError;
import io.flutter.plugins.imagepicker.Messages.GeneralOptions;
import io.flutter.plugins.imagepicker.Messages.ImageSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.MediaSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.VideoSelectionOptions;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class ImagePickerDelegateTest {
private static final Double WIDTH = 10.0;
private static final Double HEIGHT = 10.0;
private static final Long MAX_DURATION = 10L;
private static final Integer IMAGE_QUALITY = 90;
private static final ImageSelectionOptions DEFAULT_IMAGE_OPTIONS =
new ImageSelectionOptions.Builder().setQuality((long) 100).build();
private static final ImageSelectionOptions RESIZE_TRIGGERING_IMAGE_OPTIONS =
new ImageSelectionOptions.Builder().setQuality((long) 100).setMaxWidth(WIDTH).build();
private static final VideoSelectionOptions DEFAULT_VIDEO_OPTIONS =
new VideoSelectionOptions.Builder().build();
private static final MediaSelectionOptions DEFAULT_MEDIA_OPTIONS =
new MediaSelectionOptions.Builder().setImageSelectionOptions(DEFAULT_IMAGE_OPTIONS).build();
@Mock Activity mockActivity;
@Mock ImageResizer mockImageResizer;
@Mock Messages.Result<List<String>> mockResult;
@Mock ImagePickerDelegate.PermissionManager mockPermissionManager;
@Mock FileUtils mockFileUtils;
@Mock Intent mockIntent;
@Mock ImagePickerCache cache;
@Mock ExecutorService mockExecutor;
ImagePickerDelegate.FileUriResolver mockFileUriResolver;
MockedStatic<File> mockStaticFile;
AutoCloseable mockCloseable;
File externalDirectory;
private static class MockFileUriResolver implements ImagePickerDelegate.FileUriResolver {
@Override
public Uri resolveFileProviderUriForFile(String fileProviderName, File imageFile) {
return null;
}
@Override
public void getFullImagePath(Uri imageUri, ImagePickerDelegate.OnPathReadyListener listener) {
listener.onPathReady("pathFromUri");
}
}
@Before
public void setUp() throws IOException {
mockCloseable = MockitoAnnotations.openMocks(this);
mockStaticFile = Mockito.mockStatic(File.class);
mockStaticFile
.when(() -> File.createTempFile(any(), any(), any()))
.thenReturn(new File("/tmpfile"));
when(mockActivity.getPackageName()).thenReturn("com.example.test");
when(mockActivity.getPackageManager()).thenReturn(mock(PackageManager.class));
TemporaryFolder temporaryFolder = new TemporaryFolder();
temporaryFolder.create();
externalDirectory = temporaryFolder.newFolder("image_picker_cache");
when(mockActivity.getCacheDir()).thenReturn(externalDirectory);
when(mockFileUtils.getPathFromUri(any(Context.class), any(Uri.class)))
.thenReturn("pathFromUri");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, null, 100))
.thenReturn("originalPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, null, IMAGE_QUALITY))
.thenReturn("originalPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, HEIGHT, 100))
.thenReturn("scaledPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, null, 100))
.thenReturn("scaledPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, HEIGHT, 100))
.thenReturn("scaledPath");
mockFileUriResolver = new MockFileUriResolver();
Uri mockUri = mock(Uri.class);
when(mockIntent.getData()).thenReturn(mockUri);
}
@After
public void tearDown() throws Exception {
mockStaticFile.close();
mockCloseable.close();
}
@Test
public void whenConstructed_setsCorrectFileProviderName() {
ImagePickerDelegate delegate = createDelegate();
assertThat(delegate.fileProviderName, equalTo("com.example.test.flutter.image_provider"));
}
@Test
public void chooseImageFromGallery_whenPendingResultExists_finishesWithAlreadyActiveError() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.chooseImageFromGallery(DEFAULT_IMAGE_OPTIONS, false, mockResult);
verifyFinishedWithAlreadyActiveError();
verifyNoMoreInteractions(mockResult);
}
@Test
public void chooseMultiImageFromGallery_whenPendingResultExists_finishesWithAlreadyActiveError() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.chooseMultiImageFromGallery(DEFAULT_IMAGE_OPTIONS, false, mockResult);
verifyFinishedWithAlreadyActiveError();
verifyNoMoreInteractions(mockResult);
}
@Test
public void chooseMediaFromGallery_whenPendingResultExists_finishesWithAlreadyActiveError() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
GeneralOptions generalOptions =
new GeneralOptions.Builder().setAllowMultiple(true).setUsePhotoPicker(true).build();
delegate.chooseMediaFromGallery(DEFAULT_MEDIA_OPTIONS, generalOptions, mockResult);
verifyFinishedWithAlreadyActiveError();
verifyNoMoreInteractions(mockResult);
}
@Test
@Config(sdk = 30)
public void chooseImageFromGallery_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseImageFromGallery(DEFAULT_IMAGE_OPTIONS, false, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY));
}
@Test
@Config(minSdk = 33)
public void chooseImageFromGallery_withPhotoPicker_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseImageFromGallery(DEFAULT_IMAGE_OPTIONS, true, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY));
}
@Test
@Config(sdk = 30)
public void chooseMultiImageFromGallery_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseMultiImageFromGallery(DEFAULT_IMAGE_OPTIONS, true, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class),
eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY));
}
@Test
@Config(minSdk = 33)
public void chooseMultiImageFromGallery_withPhotoPicker_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseMultiImageFromGallery(DEFAULT_IMAGE_OPTIONS, false, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class),
eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY));
}
@Test
@Config(sdk = 30)
public void chooseVideoFromGallery_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseVideoFromGallery(DEFAULT_VIDEO_OPTIONS, true, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY));
}
@Test
@Config(minSdk = 33)
public void chooseVideoFromGallery_withPhotoPicker_launchesChooseFromGalleryIntent() {
ImagePickerDelegate delegate = createDelegate();
delegate.chooseVideoFromGallery(DEFAULT_VIDEO_OPTIONS, true, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY));
}
@Test
public void takeImageWithCamera_whenPendingResultExists_finishesWithAlreadyActiveError() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
verifyFinishedWithAlreadyActiveError();
verifyNoMoreInteractions(mockResult);
}
@Test
public void takeImageWithCamera_whenHasNoCameraPermission_requestsForPermission() {
when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(false);
when(mockPermissionManager.needRequestCameraPermission()).thenReturn(true);
ImagePickerDelegate delegate = createDelegate();
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
verify(mockPermissionManager)
.askForPermission(
Manifest.permission.CAMERA, ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION);
}
@Test
public void takeImageWithCamera_whenCameraPermissionNotPresent_requestsForPermission() {
when(mockPermissionManager.needRequestCameraPermission()).thenReturn(false);
ImagePickerDelegate delegate = createDelegate();
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA));
}
@Test
public void
takeImageWithCamera_whenHasCameraPermission_andAnActivityCanHandleCameraIntent_launchesTakeWithCameraIntent() {
when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true);
ImagePickerDelegate delegate = createDelegate();
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA));
}
@Test
public void
takeImageWithCamera_whenHasCameraPermission_andNoActivityToHandleCameraIntent_finishesWithNoCamerasAvailableError() {
when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true);
doThrow(ActivityNotFoundException.class)
.when(mockActivity)
.startActivityForResult(any(Intent.class), anyInt());
ImagePickerDelegate delegate = createDelegate();
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("no_available_camera", errorCaptor.getValue().code);
assertEquals("No cameras available for taking pictures.", errorCaptor.getValue().getMessage());
verifyNoMoreInteractions(mockResult);
}
@Test
public void takeImageWithCamera_writesImageToCacheDirectory() {
when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true);
ImagePickerDelegate delegate = createDelegate();
delegate.takeImageWithCamera(DEFAULT_IMAGE_OPTIONS, mockResult);
mockStaticFile.verify(
() -> File.createTempFile(any(), eq(".jpg"), eq(externalDirectory)), times(1));
}
@Test
public void onRequestPermissionsResult_whenCameraPermissionDenied_finishesWithError() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onRequestPermissionsResult(
ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION,
new String[] {Manifest.permission.CAMERA},
new int[] {PackageManager.PERMISSION_DENIED});
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("camera_access_denied", errorCaptor.getValue().code);
assertEquals("The user did not allow camera access.", errorCaptor.getValue().getMessage());
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onRequestTakeVideoPermissionsResult_whenCameraPermissionGranted_launchesTakeVideoWithCameraIntent() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(null, DEFAULT_VIDEO_OPTIONS);
delegate.onRequestPermissionsResult(
ImagePickerDelegate.REQUEST_CAMERA_VIDEO_PERMISSION,
new String[] {Manifest.permission.CAMERA},
new int[] {PackageManager.PERMISSION_GRANTED});
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA));
}
@Test
public void
onRequestTakeImagePermissionsResult_whenCameraPermissionGranted_launchesTakeWithCameraIntent() {
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onRequestPermissionsResult(
ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION,
new String[] {Manifest.permission.CAMERA},
new int[] {PackageManager.PERMISSION_GRANTED});
verify(mockActivity)
.startActivityForResult(
any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA));
}
@Test
public void onActivityResult_whenPickFromGalleryCanceled_finishesWithEmptyList() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_CANCELED, null);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals(0, pathListCapture.getValue().size());
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenPickFromGalleryCanceled_storesNothingInCache() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate = createDelegate();
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_CANCELED, null);
verify(cache, never()).saveResult(any(), any(), any());
}
@Test
public void
onActivityResult_whenImagePickedFromGallery_andNoResizeNeeded_finishesWithImagePath() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("originalPath", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenImagePickedFromGallery_nullUriFromGetData_andNoResizeNeeded_finishesWithImagePath() {
setupMockClipData();
when(mockIntent.getData()).thenReturn(null);
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("originalPath", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenVideoPickedFromGallery_nullUriFromGetData_finishesWithVideoPath() {
setupMockClipData();
when(mockIntent.getData()).thenReturn(null);
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(null, DEFAULT_VIDEO_OPTIONS);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("pathFromUri", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenImagePickedFromGallery_nullUri_andNoResizeNeeded_finishesWithNoValidUriError() {
setupMockClipDataNullUri();
when(mockIntent.getData()).thenReturn(null);
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("no_valid_image_uri", errorCaptor.getValue().code);
assertEquals("Cannot find the selected image.", errorCaptor.getValue().getMessage());
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenVideoPickedFromGallery_nullUri_finishesWithNoValidUriError() {
setupMockClipDataNullUri();
when(mockIntent.getData()).thenReturn(null);
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(null, DEFAULT_VIDEO_OPTIONS);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("no_valid_video_uri", errorCaptor.getValue().code);
assertEquals("Cannot find the selected video.", errorCaptor.getValue().getMessage());
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenImagePickedFromGallery_andNoResizeNeeded_storesImageInCache() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate = createDelegate();
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<ArrayList<String>> pathListCapture = ArgumentCaptor.forClass(ArrayList.class);
verify(cache, times(1)).saveResult(pathListCapture.capture(), any(), any());
assertEquals("pathFromUri", pathListCapture.getValue().get(0));
}
@Test
public void
onActivityResult_whenImagePickedFromGallery_andResizeNeeded_finishesWithScaledImagePath() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(RESIZE_TRIGGERING_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("scaledPath", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenVideoPickedFromGallery_andResizeParametersSupplied_finishesWithFilePath() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(RESIZE_TRIGGERING_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("pathFromUri", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenTakeImageWithCameraCanceled_finishesWithEmptyList() {
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_CANCELED, null);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals(0, pathListCapture.getValue().size());
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenImageTakenWithCamera_andNoResizeNeeded_finishesWithImagePath() {
when(cache.retrievePendingCameraMediaUriPath()).thenReturn("testString");
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(DEFAULT_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("originalPath", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenImageTakenWithCamera_andResizeNeeded_finishesWithScaledImagePath() {
when(cache.retrievePendingCameraMediaUriPath()).thenReturn("testString");
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(RESIZE_TRIGGERING_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("scaledPath", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenVideoTakenWithCamera_andResizeParametersSupplied_finishesWithFilePath() {
when(cache.retrievePendingCameraMediaUriPath()).thenReturn("testString");
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(RESIZE_TRIGGERING_IMAGE_OPTIONS, null);
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("pathFromUri", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void
onActivityResult_whenVideoTakenWithCamera_andMaxDurationParametersSupplied_finishesWithFilePath() {
when(cache.retrievePendingCameraMediaUriPath()).thenReturn("testString");
Mockito.doAnswer(
invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
})
.when(mockExecutor)
.execute(any(Runnable.class));
ImagePickerDelegate delegate =
createDelegateWithPendingResultAndOptions(
null, new VideoSelectionOptions.Builder().setMaxDurationSeconds(MAX_DURATION).build());
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA, Activity.RESULT_OK, mockIntent);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> pathListCapture = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(pathListCapture.capture());
assertEquals("pathFromUri", pathListCapture.getValue().get(0));
verifyNoMoreInteractions(mockResult);
}
@Test
public void onActivityResult_whenImagePickedFromGallery_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_whenMultipleImagesPickedFromGallery_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_whenMediaPickedFromGallery_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_MEDIA_FROM_GALLERY,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_whenVideoPickerFromGallery_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_whenImageTakenWithCamera_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_whenVideoTakenWithCamera_returnsTrue() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled =
delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA,
Activity.RESULT_OK,
mockIntent);
assertTrue(isHandled);
}
@Test
public void onActivityResult_withUnknownRequest_returnsFalse() {
ImagePickerDelegate delegate = createDelegate();
boolean isHandled = delegate.onActivityResult(314, Activity.RESULT_OK, mockIntent);
assertFalse(isHandled);
}
private ImagePickerDelegate createDelegate() {
return new ImagePickerDelegate(
mockActivity,
mockImageResizer,
null,
null,
null,
cache,
mockPermissionManager,
mockFileUriResolver,
mockFileUtils,
mockExecutor);
}
private ImagePickerDelegate createDelegateWithPendingResultAndOptions(
@Nullable ImageSelectionOptions imageOptions, @Nullable VideoSelectionOptions videoOptions) {
return new ImagePickerDelegate(
mockActivity,
mockImageResizer,
imageOptions,
videoOptions,
mockResult,
cache,
mockPermissionManager,
mockFileUriResolver,
mockFileUtils,
mockExecutor);
}
private void verifyFinishedWithAlreadyActiveError() {
ArgumentCaptor<FlutterError> errorCaptor = ArgumentCaptor.forClass(FlutterError.class);
verify(mockResult).error(errorCaptor.capture());
assertEquals("already_active", errorCaptor.getValue().code);
assertEquals("Image picker is already active", errorCaptor.getValue().getMessage());
}
private void setupMockClipData() {
ClipData mockClipData = mock(ClipData.class);
ClipData.Item mockItem = mock(ClipData.Item.class);
Uri mockUri = mock(Uri.class);
when(mockItem.getUri()).thenReturn(mockUri);
when(mockClipData.getItemCount()).thenReturn(1);
when(mockClipData.getItemAt(0)).thenReturn(mockItem);
when(mockIntent.getClipData()).thenReturn(mockClipData);
}
private void setupMockClipDataNullUri() {
ClipData mockClipData = mock(ClipData.class);
ClipData.Item mockItem = mock(ClipData.Item.class);
when(mockItem.getUri()).thenReturn(null);
when(mockClipData.getItemCount()).thenReturn(1);
when(mockClipData.getItemAt(0)).thenReturn(mockItem);
when(mockIntent.getClipData()).thenReturn(mockClipData);
}
}
| packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerDelegateTest.java/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerDelegateTest.java",
"repo_id": "packages",
"token_count": 12217
} | 1,048 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.imagepickerexample">
<!-- Flutter needs internet permission to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name=".ImagePickerTestActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
<activity
android:name=".DriverExtensionActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
<provider
android:authorities="dummy"
android:name=".DummyContentProvider"
android:exported="true"/>
</application>
</manifest>
| packages/packages/image_picker/image_picker_android/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 591
} | 1,049 |
// 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:convert';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_for_web/image_picker_for_web.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/web.dart' as web;
const String expectedStringContents = 'Hello, world!';
const String otherStringContents = 'Hello again, world!';
final Uint8List bytes = const Utf8Encoder().convert(expectedStringContents);
final Uint8List otherBytes = const Utf8Encoder().convert(otherStringContents);
// TODO(dit): When web:0.6.0 lands, move `type` to the [web.FilePropertyBag] constructor.
// See: https://github.com/dart-lang/web/pull/197
final web.FilePropertyBag options = web.FilePropertyBag(
lastModified: DateTime.utc(2017, 12, 13).millisecondsSinceEpoch,
)..type = 'text/plain';
final web.File textFile =
web.File(<JSUint8Array>[bytes.toJS].toJS, 'hello.txt', options);
final web.File secondTextFile =
web.File(<JSUint8Array>[otherBytes.toJS].toJS, 'secondFile.txt');
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Under test...
late ImagePickerPlugin plugin;
setUp(() {
plugin = ImagePickerPlugin();
});
testWidgets('getImageFromSource can select a file', (
WidgetTester _,
) async {
final web.HTMLInputElement mockInput = web.HTMLInputElement()
..type = 'file';
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <web.File>[textFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<XFile?> image = plugin.getImageFromSource(
source: ImageSource.camera,
);
expect(
web.document.querySelector('flt-image-picker-inputs')?.children.length,
isNonZero);
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(web.Event('change'));
// Now the file should be available
expect(image, completes);
// And readable
final XFile? file = await image;
expect(file, isNotNull);
expect(file!.readAsBytes(), completion(isNotEmpty));
expect(file.name, textFile.name);
expect(file.length(), completion(textFile.size));
expect(file.mimeType, textFile.type);
expect(
file.lastModified(),
completion(
DateTime.fromMillisecondsSinceEpoch(textFile.lastModified),
));
expect(
web.document.querySelector('flt-image-picker-inputs')?.children.length,
isZero);
});
testWidgets('getMultiImageWithOptions can select multiple files', (
WidgetTester _,
) async {
final web.HTMLInputElement mockInput = web.HTMLInputElement()
..type = 'file';
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput =
((_) => <web.File>[textFile, secondTextFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<List<XFile>> files = plugin.getMultiImageWithOptions();
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(web.Event('change'));
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
testWidgets('getMedia can select multiple files', (WidgetTester _) async {
final web.HTMLInputElement mockInput = web.HTMLInputElement()
..type = 'file';
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput =
((_) => <web.File>[textFile, secondTextFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<List<XFile>> files =
plugin.getMedia(options: const MediaOptions(allowMultiple: true));
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(web.Event('change'));
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
group('cancel event', () {
late web.HTMLInputElement mockInput;
late ImagePickerPluginTestOverrides overrides;
late ImagePickerPlugin plugin;
setUp(() {
mockInput = web.HTMLInputElement()..type = 'file';
overrides = ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <web.File>[textFile]);
plugin = ImagePickerPlugin(overrides: overrides);
});
void mockCancel() {
mockInput.dispatchEvent(web.Event('cancel'));
}
testWidgets('getFiles - returns empty list', (WidgetTester _) async {
final Future<List<XFile>> files = plugin.getFiles();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getMedia - returns empty list', (WidgetTester _) async {
final Future<List<XFile>?> files = plugin.getMedia(
options: const MediaOptions(
allowMultiple: true,
));
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getMultiImageWithOptions - returns empty list', (
WidgetTester _,
) async {
final Future<List<XFile>?> files = plugin.getMultiImageWithOptions();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getImageFromSource - returns null', (WidgetTester _) async {
final Future<XFile?> file = plugin.getImageFromSource(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
testWidgets('getVideo - returns null', (WidgetTester _) async {
final Future<XFile?> file = plugin.getVideo(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
});
testWidgets('computeCaptureAttribute', (WidgetTester tester) async {
expect(
plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.front),
isNull,
);
expect(
plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.rear),
isNull,
);
expect(
plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.front),
'user',
);
expect(
plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.rear),
'environment',
);
});
group('createInputElement', () {
testWidgets('accept: any, capture: null', (WidgetTester tester) async {
final web.Element input = plugin.createInputElement('any', null);
expect(input.getAttribute('accept'), 'any');
expect(input.hasAttribute('capture'), false);
expect(input.hasAttribute('multiple'), false);
});
testWidgets('accept: any, capture: something', (WidgetTester tester) async {
final web.Element input = plugin.createInputElement('any', 'something');
expect(input.getAttribute('accept'), 'any');
expect(input.getAttribute('capture'), 'something');
expect(input.hasAttribute('multiple'), false);
});
testWidgets('accept: any, capture: null, multi: true',
(WidgetTester tester) async {
final web.Element input =
plugin.createInputElement('any', null, multiple: true);
expect(input.getAttribute('accept'), 'any');
expect(input.hasAttribute('capture'), false);
expect(input.hasAttribute('multiple'), true);
});
testWidgets('accept: any, capture: something, multi: true',
(WidgetTester tester) async {
final web.Element input =
plugin.createInputElement('any', 'something', multiple: true);
expect(input.getAttribute('accept'), 'any');
expect(input.getAttribute('capture'), 'something');
expect(input.hasAttribute('multiple'), true);
});
});
group('Deprecated methods', () {
late web.HTMLInputElement mockInput;
late ImagePickerPluginTestOverrides overrides;
late ImagePickerPlugin plugin;
setUp(() {
mockInput = web.HTMLInputElement()..type = 'file';
overrides = ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <web.File>[textFile]);
plugin = ImagePickerPlugin(overrides: overrides);
});
void mockCancel() {
mockInput.dispatchEvent(web.Event('cancel'));
}
void mockChange() {
mockInput.dispatchEvent(web.Event('change'));
}
group('getImage', () {
testWidgets('can select a file', (WidgetTester _) async {
// ignore: deprecated_member_use
final Future<XFile?> image = plugin.getImage(
source: ImageSource.camera,
);
// Mock the browser behavior when selecting a file...
mockChange();
// Now the file should be available
expect(image, completes);
// And readable
final XFile? file = await image;
expect(file, isNotNull);
expect(file!.readAsBytes(), completion(isNotEmpty));
expect(file.name, textFile.name);
expect(file.length(), completion(textFile.size));
expect(file.mimeType, textFile.type);
expect(
file.lastModified(),
completion(
DateTime.fromMillisecondsSinceEpoch(textFile.lastModified),
));
});
testWidgets('returns null when canceled', (WidgetTester _) async {
// ignore: deprecated_member_use
final Future<XFile?> file = plugin.getImage(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
});
group('getMultiImage', () {
testWidgets('can select multiple files', (WidgetTester _) async {
// Override the returned files...
overrides.getMultipleFilesFromInput =
(_) => <web.File>[textFile, secondTextFile];
// ignore: deprecated_member_use
final Future<List<XFile>> files = plugin.getMultiImage();
// Mock the browser behavior of selecting a file...
mockChange();
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
testWidgets('returns an empty list when canceled', (
WidgetTester _,
) async {
// ignore: deprecated_member_use
final Future<List<XFile>?> files = plugin.getMultiImage();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
});
});
}
| packages/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart",
"repo_id": "packages",
"token_count": 4524
} | 1,050 |
// Mocks generated by Mockito 5.4.4 from annotations
// in image_picker_macos/test/image_picker_macos_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'
as _i2;
import 'package:mockito/mockito.dart' as _i1;
// 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 [FileSelectorPlatform].
///
/// See the documentation for Mockito's code generation for more information.
class MockFileSelectorPlatform extends _i1.Mock
implements _i2.FileSelectorPlatform {
MockFileSelectorPlatform() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<_i2.XFile?> openFile({
List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) =>
(super.noSuchMethod(
Invocation.method(
#openFile,
[],
{
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText,
},
),
returnValue: _i3.Future<_i2.XFile?>.value(),
) as _i3.Future<_i2.XFile?>);
@override
_i3.Future<List<_i2.XFile>> openFiles({
List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) =>
(super.noSuchMethod(
Invocation.method(
#openFiles,
[],
{
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText,
},
),
returnValue: _i3.Future<List<_i2.XFile>>.value(<_i2.XFile>[]),
) as _i3.Future<List<_i2.XFile>>);
@override
_i3.Future<String?> getSavePath({
List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) =>
(super.noSuchMethod(
Invocation.method(
#getSavePath,
[],
{
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#suggestedName: suggestedName,
#confirmButtonText: confirmButtonText,
},
),
returnValue: _i3.Future<String?>.value(),
) as _i3.Future<String?>);
@override
_i3.Future<_i2.FileSaveLocation?> getSaveLocation({
List<_i2.XTypeGroup>? acceptedTypeGroups,
_i2.SaveDialogOptions? options = const _i2.SaveDialogOptions(),
}) =>
(super.noSuchMethod(
Invocation.method(
#getSaveLocation,
[],
{
#acceptedTypeGroups: acceptedTypeGroups,
#options: options,
},
),
returnValue: _i3.Future<_i2.FileSaveLocation?>.value(),
) as _i3.Future<_i2.FileSaveLocation?>);
@override
_i3.Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) =>
(super.noSuchMethod(
Invocation.method(
#getDirectoryPath,
[],
{
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText,
},
),
returnValue: _i3.Future<String?>.value(),
) as _i3.Future<String?>);
@override
_i3.Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) =>
(super.noSuchMethod(
Invocation.method(
#getDirectoryPaths,
[],
{
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText,
},
),
returnValue: _i3.Future<List<String>>.value(<String>[]),
) as _i3.Future<List<String>>);
}
| packages/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart",
"repo_id": "packages",
"token_count": 1915
} | 1,051 |
// 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:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show immutable;
/// The interface for a PickedFile.
///
/// A PickedFile is a container that wraps the path of a selected
/// file by the user and (in some platforms, like web) the bytes
/// with the contents of the file.
///
/// This class is a very limited subset of dart:io [File], so all
/// the methods should seem familiar.
@immutable
abstract class PickedFileBase {
/// Construct a PickedFile
// ignore: avoid_unused_constructor_parameters
const PickedFileBase(String path);
/// Get the path of the picked file.
///
/// This should only be used as a backwards-compatibility clutch
/// for mobile apps, or cosmetic reasons only (to show the user
/// the path they've picked).
///
/// Accessing the data contained in the picked file by its path
/// is platform-dependant (and won't work on web), so use the
/// byte getters in the PickedFile instance instead.
String get path {
throw UnimplementedError('.path has not been implemented.');
}
/// Synchronously read the entire file contents as a string using the given [Encoding].
///
/// By default, `encoding` is [utf8].
///
/// Throws Exception if the operation fails.
Future<String> readAsString({Encoding encoding = utf8}) {
throw UnimplementedError('readAsString() has not been implemented.');
}
/// Synchronously read the entire file contents as a list of bytes.
///
/// Throws Exception if the operation fails.
Future<Uint8List> readAsBytes() {
throw UnimplementedError('readAsBytes() has not been implemented.');
}
/// Create a new independent [Stream] for the contents of this file.
///
/// If `start` is present, the file will be read from byte-offset `start`. Otherwise from the beginning (index 0).
///
/// If `end` is present, only up to byte-index `end` will be read. Otherwise, until end of file.
///
/// In order to make sure that system resources are freed, the stream must be read to completion or the subscription on the stream must be cancelled.
Stream<Uint8List> openRead([int? start, int? end]) {
throw UnimplementedError('openRead() has not been implemented.');
}
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/base.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/base.dart",
"repo_id": "packages",
"token_count": 670
} | 1,052 |
# In App Purchase Example
Demonstrates how to use the In App Purchase (IAP) Plugin.
## Getting Started
### Preparation
There's a significant amount of setup required for testing in app purchases
successfully, including registering new app IDs and store entries to use for
testing in both the Play Developer Console and App Store Connect. Both Google
Play and the App Store require developers to configure an app with in-app items
for purchase to call their in-app-purchase APIs. Both stores have extensive
documentation on how to do this, and we've also included a high level guide
below.
* [In-App Purchase (App Store)](https://developer.apple.com/in-app-purchase/)
* [Google Play Billing Overview](https://developer.android.com/google/play/billing/billing_overview)
### Android
1. Create a new app in the [Play Developer
Console](https://play.google.com/apps/publish/) (PDC).
2. Sign up for a merchant's account in the PDC.
3. Create IAPs in the PDC available for purchase in the app. The example assumes
the following SKU IDs exist:
- `consumable`: A managed product.
- `upgrade`: A managed product.
- `subscription_silver`: A lower level subscription.
- `subscription_gold`: A higher level subscription.
Make sure that all the products are set to `ACTIVE`.
4. Update `APP_ID` in `example/android/app/build.gradle` to match your package
ID in the PDC.
5. Create an `example/android/keystore.properties` file with all your signing
information. `keystore.example.properties` exists as an example to follow.
It's impossible to use any of the `BillingClient` APIs from an unsigned APK.
See
[here](https://developer.android.com/studio/publish/app-signing#secure-shared-keystore)
and [here](https://developer.android.com/studio/publish/app-signing#sign-apk)
for more information.
6. Build a signed apk. `flutter build apk` will work for this, the gradle files
in this project have been configured to sign even debug builds.
7. Upload the signed APK from step 6 to the PDC, and publish that to the alpha
test channel. Add your test account as an approved tester. The
`BillingClient` APIs won't work unless the app has been fully published to
the alpha channel and is being used by an authorized test account. See
[here](https://support.google.com/googleplay/android-developer/answer/3131213)
for more info.
8. Sign in to the test device with the test account from step #7. Then use
`flutter run` to install the app to the device and test like normal.
### iOS
When using Xcode 12 and iOS 14 or higher you can run the example in the simulator or on a device without
having to configure an App in App Store Connect. The example app is set up to use StoreKit Testing configured
in the `example/ios/Runner/Configuration.storekit` file (as documented in the article [Setting Up StoreKit Testing in Xcode](https://developer.apple.com/documentation/xcode/setting_up_storekit_testing_in_xcode?language=objc)).
To run the application take the following steps (note that it will only work when running from Xcode):
1. Open the example app with Xcode, `File > Open File` `example/ios/Runner.xcworkspace`;
2. Within Xcode edit the current scheme, `Product > Scheme > Edit Scheme...` (or press `Command + Shift + ,`);
3. Enable StoreKit testing:
a. Select the `Run` action;
b. Click `Options` in the action settings;
c. Select the `Configuration.storekit` for the StoreKit Configuration option.
4. Click the `Close` button to close the scheme editor;
5. Select the device you want to run the example App on;
6. Run the application using `Product > Run` (or hit the run button).
When testing on pre-iOS 14 you can't run the example app on a simulator and you will need to configure an app in App Store Connect. You can do so by following the steps below:
1. Follow ["Workflow for configuring in-app
purchases"](https://help.apple.com/app-store-connect/#/devb57be10e7), a
detailed guide on all the steps needed to enable IAPs for an app. Complete
steps 1 ("Sign a Paid Applications Agreement") and 2 ("Configure in-app
purchases").
For step #2, "Configure in-app purchases in App Store Connect," you'll want
to create the following products:
- A consumable with product ID `consumable`
- An upgrade with product ID `upgrade`
- An auto-renewing subscription with product ID `subscription_silver`
- An non-renewing subscription with product ID `subscription_gold`
2. In XCode, `File > Open File` `example/ios/Runner.xcworkspace`. Update the
Bundle ID to match the Bundle ID of the app created in step #1.
3. [Create a Sandbox tester
account](https://help.apple.com/app-store-connect/#/dev8b997bee1) to test the
in-app purchases with.
4. Use `flutter run` to install the app and test it. Note that you need to test
it on a real device instead of a simulator. Next click on one of the products
in the example App, this enables the "SANDBOX ACCOUNT" section in the iOS
settings. You will now be asked to sign in with your sandbox test account to
complete the purchase (no worries you won't be charged). If for some reason
you aren't asked to sign-in or the wrong user is listed, go into the iOS
settings ("Settings" -> "App Store" -> "SANDBOX ACCOUNT") and update your
sandbox account from there. This procedure is explained in great detail in
the [Testing In-App Purchases with Sandbox](https://developer.apple.com/documentation/storekit/in-app_purchase/testing_in-app_purchases_with_sandbox?language=objc) article.
**Important:** signing into any production service (including iTunes!) with the
sandbox test account will permanently invalidate it.
| packages/packages/in_app_purchase/in_app_purchase/example/README.md/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase/example/README.md",
"repo_id": "packages",
"token_count": 1612
} | 1,053 |
storePassword=???
keyPassword=???
keyAlias=???
storeFile=???
appId=io.flutter.plugins.inapppurchaseexample.DEFAULT_DO_NOT_USE
versionCode=1
versionName=0.0.1 | packages/packages/in_app_purchase/in_app_purchase/example/android/keystore.example.properties/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase/example/android/keystore.example.properties",
"repo_id": "packages",
"token_count": 58
} | 1,054 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
group('InAppPurchase', () {
final ProductDetails productDetails = ProductDetails(
id: 'id',
title: 'title',
description: 'description',
price: 'price',
rawPrice: 0.0,
currencyCode: 'currencyCode',
);
final PurchaseDetails purchaseDetails = PurchaseDetails(
productID: 'productID',
verificationData: PurchaseVerificationData(
localVerificationData: 'localVerificationData',
serverVerificationData: 'serverVerificationData',
source: 'source',
),
transactionDate: 'transactionDate',
status: PurchaseStatus.purchased,
);
late InAppPurchase inAppPurchase;
late MockInAppPurchasePlatform fakePlatform;
setUp(() {
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
fakePlatform = MockInAppPurchasePlatform();
InAppPurchasePlatform.instance = fakePlatform;
inAppPurchase = InAppPurchase.instance;
});
tearDown(() {
// Restore the default target platform
debugDefaultTargetPlatformOverride = null;
});
test('isAvailable', () async {
final bool isAvailable = await inAppPurchase.isAvailable();
expect(isAvailable, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('isAvailable', arguments: null),
]);
});
test('purchaseStream', () async {
final bool isEmptyStream = await inAppPurchase.purchaseStream.isEmpty;
expect(isEmptyStream, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('purchaseStream', arguments: null),
]);
});
test('queryProductDetails', () async {
final ProductDetailsResponse response =
await inAppPurchase.queryProductDetails(<String>{});
expect(response.notFoundIDs.isEmpty, true);
expect(response.productDetails.isEmpty, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('queryProductDetails', arguments: null),
]);
});
test('buyNonConsumable', () async {
final bool result = await inAppPurchase.buyNonConsumable(
purchaseParam: PurchaseParam(
productDetails: productDetails,
),
);
expect(result, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('buyNonConsumable', arguments: null),
]);
});
test('buyConsumable', () async {
final PurchaseParam purchaseParam =
PurchaseParam(productDetails: productDetails);
final bool result = await inAppPurchase.buyConsumable(
purchaseParam: purchaseParam,
);
expect(result, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('buyConsumable', arguments: <dynamic, dynamic>{
'purchaseParam': purchaseParam,
'autoConsume': true,
}),
]);
});
test('buyConsumable with autoConsume=false', () async {
final PurchaseParam purchaseParam =
PurchaseParam(productDetails: productDetails);
final bool result = await inAppPurchase.buyConsumable(
purchaseParam: purchaseParam,
autoConsume: false,
);
expect(result, true);
expect(fakePlatform.log, <Matcher>[
isMethodCall('buyConsumable', arguments: <dynamic, dynamic>{
'purchaseParam': purchaseParam,
'autoConsume': false,
}),
]);
});
test('completePurchase', () async {
await inAppPurchase.completePurchase(purchaseDetails);
expect(fakePlatform.log, <Matcher>[
isMethodCall('completePurchase', arguments: null),
]);
});
test('restorePurchases', () async {
await inAppPurchase.restorePurchases();
expect(fakePlatform.log, <Matcher>[
isMethodCall('restorePurchases', arguments: null),
]);
});
});
}
class MockInAppPurchasePlatform extends Fake
with MockPlatformInterfaceMixin
implements InAppPurchasePlatform {
final List<MethodCall> log = <MethodCall>[];
@override
Future<bool> isAvailable() {
log.add(const MethodCall('isAvailable'));
return Future<bool>.value(true);
}
@override
Stream<List<PurchaseDetails>> get purchaseStream {
log.add(const MethodCall('purchaseStream'));
return const Stream<List<PurchaseDetails>>.empty();
}
@override
Future<ProductDetailsResponse> queryProductDetails(Set<String> identifiers) {
log.add(const MethodCall('queryProductDetails'));
return Future<ProductDetailsResponse>.value(ProductDetailsResponse(
productDetails: <ProductDetails>[],
notFoundIDs: <String>[],
));
}
@override
Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) {
log.add(const MethodCall('buyNonConsumable'));
return Future<bool>.value(true);
}
@override
Future<bool> buyConsumable({
required PurchaseParam purchaseParam,
bool autoConsume = true,
}) {
log.add(MethodCall('buyConsumable', <String, Object?>{
'purchaseParam': purchaseParam,
'autoConsume': autoConsume,
}));
return Future<bool>.value(true);
}
@override
Future<void> completePurchase(PurchaseDetails purchase) {
log.add(const MethodCall('completePurchase'));
return Future<void>.value();
}
@override
Future<void> restorePurchases({String? applicationUserName}) {
log.add(const MethodCall('restorePurchases'));
return Future<void>.value();
}
}
| packages/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart",
"repo_id": "packages",
"token_count": 2121
} | 1,055 |
// 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.inapppurchase;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.PluginRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class InAppPurchasePluginTest {
static final String PROXY_PACKAGE_KEY = "PROXY_PACKAGE";
@SuppressWarnings("deprecation")
@Mock
PluginRegistry.Registrar mockRegistrar; // For v1 embedding
@Mock Activity activity;
@Mock Context context;
@Mock BinaryMessenger mockMessenger;
@Mock Application mockApplication;
@Mock Intent mockIntent;
@Mock ActivityPluginBinding activityPluginBinding;
@Mock FlutterPlugin.FlutterPluginBinding flutterPluginBinding;
AutoCloseable mockCloseable;
@Before
public void setUp() {
mockCloseable = MockitoAnnotations.openMocks(this);
when(mockRegistrar.activity()).thenReturn(activity);
when(mockRegistrar.messenger()).thenReturn(mockMessenger);
when(mockRegistrar.context()).thenReturn(context);
when(activity.getIntent()).thenReturn(mockIntent);
when(activityPluginBinding.getActivity()).thenReturn(activity);
when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mockMessenger);
when(flutterPluginBinding.getApplicationContext()).thenReturn(context);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void registerWith_doNotCrashWhenRegisterContextIsActivity_V1Embedding() {
when(mockRegistrar.context()).thenReturn(activity);
when(activity.getApplicationContext()).thenReturn(mockApplication);
InAppPurchasePlugin.registerWith(mockRegistrar);
}
// The PROXY_PACKAGE_KEY value of this test (io.flutter.plugins.inapppurchase) should never be changed.
// In case there's a strong reason to change it, please inform the current code owner of the plugin.
@Test
public void registerWith_proxyIsSet_V1Embedding() {
when(mockRegistrar.context()).thenReturn(activity);
when(activity.getApplicationContext()).thenReturn(mockApplication);
InAppPurchasePlugin.registerWith(mockRegistrar);
// The `PROXY_PACKAGE_KEY` value is hard coded in the plugin code as "io.flutter.plugins.inapppurchase".
// We cannot use `BuildConfig.LIBRARY_PACKAGE_NAME` directly in the plugin code because whether to read BuildConfig.APPLICATION_ID or LIBRARY_PACKAGE_NAME
// depends on the "APP's" Android Gradle plugin version. Newer versions of AGP use LIBRARY_PACKAGE_NAME, whereas older ones use BuildConfig.APPLICATION_ID.
Mockito.verify(mockIntent).putExtra(PROXY_PACKAGE_KEY, "io.flutter.plugins.inapppurchase");
assertEquals("io.flutter.plugins.inapppurchase", BuildConfig.LIBRARY_PACKAGE_NAME);
}
// The PROXY_PACKAGE_KEY value of this test (io.flutter.plugins.inapppurchase) should never be changed.
// In case there's a strong reason to change it, please inform the current code owner of the plugin.
@Test
public void attachToActivity_proxyIsSet_V2Embedding() {
InAppPurchasePlugin plugin = new InAppPurchasePlugin();
plugin.onAttachedToEngine(flutterPluginBinding);
plugin.onAttachedToActivity(activityPluginBinding);
// The `PROXY_PACKAGE_KEY` value is hard coded in the plugin code as "io.flutter.plugins.inapppurchase".
// We cannot use `BuildConfig.LIBRARY_PACKAGE_NAME` directly in the plugin code because whether to read BuildConfig.APPLICATION_ID or LIBRARY_PACKAGE_NAME
// depends on the "APP's" Android Gradle plugin version. Newer versions of AGP use LIBRARY_PACKAGE_NAME, whereas older ones use BuildConfig.APPLICATION_ID.
Mockito.verify(mockIntent).putExtra(PROXY_PACKAGE_KEY, "io.flutter.plugins.inapppurchase");
assertEquals("io.flutter.plugins.inapppurchase", BuildConfig.LIBRARY_PACKAGE_NAME);
}
}
// We cannot use `BuildConfig.LIBRARY_PACKAGE_NAME` directly in the plugin code because whether to read BuildConfig.APPLICATION_ID or LIBRARY_PACKAGE_NAME
// depends on the "APP's" Android Gradle plugin version. Newer versions of AGP use LIBRARY_PACKAGE_NAME, whereas older ones use BuildConfig.APPLICATION_ID.
| packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/InAppPurchasePluginTest.java/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/InAppPurchasePluginTest.java",
"repo_id": "packages",
"token_count": 1503
} | 1,056 |
# billing_client_wrappers
This exposes a way Dart endpoints through to [Google Play Billing
Library](https://developer.android.com/google/play/billing/billing_library_overview).
Can be used as an alternative to
[in_app_purchase](../in_app_purchase/README.md). | packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/README.md/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/README.md",
"repo_id": "packages",
"token_count": 80
} | 1,057 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:json_annotation/json_annotation.dart';
import '../../billing_client_wrappers.dart';
// WARNING: Changes to `@JsonSerializable` classes need to be reflected in the
// below generated file. Run `flutter packages pub run build_runner watch` to
// rebuild and watch for further changes.
part 'purchase_wrapper.g.dart';
/// Data structure representing a successful purchase.
///
/// All purchase information should also be verified manually, with your
/// server if at all possible. See ["Verify a
/// purchase"](https://developer.android.com/google/play/billing/billing_library_overview#Verify).
///
/// This wraps [`com.android.billlingclient.api.Purchase`](https://developer.android.com/reference/com/android/billingclient/api/Purchase)
@JsonSerializable()
@PurchaseStateConverter()
@immutable
class PurchaseWrapper {
/// Creates a purchase wrapper with the given purchase details.
@visibleForTesting
const PurchaseWrapper({
required this.orderId,
required this.packageName,
required this.purchaseTime,
required this.purchaseToken,
required this.signature,
required this.products,
required this.isAutoRenewing,
required this.originalJson,
this.developerPayload,
required this.isAcknowledged,
required this.purchaseState,
this.obfuscatedAccountId,
this.obfuscatedProfileId,
});
/// Factory for creating a [PurchaseWrapper] from a [Map] with the purchase details.
factory PurchaseWrapper.fromJson(Map<String, dynamic> map) =>
_$PurchaseWrapperFromJson(map);
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is PurchaseWrapper &&
other.orderId == orderId &&
other.packageName == packageName &&
other.purchaseTime == purchaseTime &&
other.purchaseToken == purchaseToken &&
other.signature == signature &&
listEquals(other.products, products) &&
other.isAutoRenewing == isAutoRenewing &&
other.originalJson == originalJson &&
other.isAcknowledged == isAcknowledged &&
other.purchaseState == purchaseState;
}
@override
int get hashCode => Object.hash(
orderId,
packageName,
purchaseTime,
purchaseToken,
signature,
products.hashCode,
isAutoRenewing,
originalJson,
isAcknowledged,
purchaseState);
/// The unique ID for this purchase. Corresponds to the Google Payments order
/// ID.
@JsonKey(defaultValue: '')
final String orderId;
/// The package name the purchase was made from.
@JsonKey(defaultValue: '')
final String packageName;
/// When the purchase was made, as an epoch timestamp.
@JsonKey(defaultValue: 0)
final int purchaseTime;
/// A unique ID for a given [ProductDetailsWrapper], user, and purchase.
@JsonKey(defaultValue: '')
final String purchaseToken;
/// Signature of purchase data, signed with the developer's private key. Uses
/// RSASSA-PKCS1-v1_5.
@JsonKey(defaultValue: '')
final String signature;
/// The product IDs of this purchase.
@JsonKey(defaultValue: <String>[])
final List<String> products;
/// True for subscriptions that renew automatically. Does not apply to
/// [ProductType.inapp] products.
///
/// For [ProductType.subs] this means that the subscription is canceled when it is
/// false.
///
/// The value is `false` for [ProductType.inapp] products.
final bool isAutoRenewing;
/// Details about this purchase, in JSON.
///
/// This can be used verify a purchase. See ["Verify a purchase on a
/// device"](https://developer.android.com/google/play/billing/billing_library_overview#Verify-purchase-device).
/// Note though that verifying a purchase locally is inherently insecure (see
/// the article for more details).
@JsonKey(defaultValue: '')
final String originalJson;
/// The payload specified by the developer when the purchase was acknowledged or consumed.
///
/// The value is `null` if it wasn't specified when the purchase was acknowledged or consumed.
/// The `developerPayload` is removed from [BillingClientWrapper.acknowledgePurchase], [BillingClientWrapper.consumeAsync], [InAppPurchaseConnection.completePurchase], [InAppPurchaseConnection.consumePurchase]
/// after plugin version `0.5.0`. As a result, this will be `null` for new purchases that happen after updating to `0.5.0`.
final String? developerPayload;
/// Whether the purchase has been acknowledged.
///
/// A successful purchase has to be acknowledged within 3 days after the purchase via [BillingClient.acknowledgePurchase].
/// * See also [BillingClient.acknowledgePurchase] for more details on acknowledging purchases.
@JsonKey(defaultValue: false)
final bool isAcknowledged;
/// Determines the current state of the purchase.
///
/// [BillingClient.acknowledgePurchase] should only be called when the `purchaseState` is [PurchaseStateWrapper.purchased].
/// * See also [BillingClient.acknowledgePurchase] for more details on acknowledging purchases.
final PurchaseStateWrapper purchaseState;
/// The obfuscatedAccountId specified when making a purchase.
///
/// The [obfuscatedAccountId] can either be set in
/// [PurchaseParam.applicationUserName] when using the [InAppPurchasePlatform]
/// or by setting the [accountId] in [BillingClient.launchBillingFlow].
final String? obfuscatedAccountId;
/// The obfuscatedProfileId can be used when there are multiple profiles
/// withing one account. The obfuscatedProfileId should be specified when
/// making a purchase. This property can only be set on a purchase by
/// directly calling [BillingClient.launchBillingFlow] and is not available
/// on the generic [InAppPurchasePlatform].
final String? obfuscatedProfileId;
}
/// Data structure representing a purchase history record.
///
/// This class includes a subset of fields in [PurchaseWrapper].
///
/// This wraps [`com.android.billlingclient.api.PurchaseHistoryRecord`](https://developer.android.com/reference/com/android/billingclient/api/PurchaseHistoryRecord)
///
/// * See also: [BillingClient.queryPurchaseHistory] for obtaining a [PurchaseHistoryRecordWrapper].
// We can optionally make [PurchaseWrapper] extend or implement [PurchaseHistoryRecordWrapper].
// For now, we keep them separated classes to be consistent with Android's BillingClient implementation.
@JsonSerializable()
@immutable
class PurchaseHistoryRecordWrapper {
/// Creates a [PurchaseHistoryRecordWrapper] with the given record details.
@visibleForTesting
const PurchaseHistoryRecordWrapper({
required this.purchaseTime,
required this.purchaseToken,
required this.signature,
required this.products,
required this.originalJson,
required this.developerPayload,
});
/// Factory for creating a [PurchaseHistoryRecordWrapper] from a [Map] with the record details.
factory PurchaseHistoryRecordWrapper.fromJson(Map<String, dynamic> map) =>
_$PurchaseHistoryRecordWrapperFromJson(map);
/// When the purchase was made, as an epoch timestamp.
@JsonKey(defaultValue: 0)
final int purchaseTime;
/// A unique ID for a given [ProductDetailsWrapper], user, and purchase.
@JsonKey(defaultValue: '')
final String purchaseToken;
/// Signature of purchase data, signed with the developer's private key. Uses
/// RSASSA-PKCS1-v1_5.
@JsonKey(defaultValue: '')
final String signature;
/// The product ID of this purchase.
@JsonKey(defaultValue: <String>[])
final List<String> products;
/// Details about this purchase, in JSON.
///
/// This can be used verify a purchase. See ["Verify a purchase on a
/// device"](https://developer.android.com/google/play/billing/billing_library_overview#Verify-purchase-device).
/// Note though that verifying a purchase locally is inherently insecure (see
/// the article for more details).
@JsonKey(defaultValue: '')
final String originalJson;
/// The payload specified by the developer when the purchase was acknowledged or consumed.
///
/// The value is `null` if it wasn't specified when the purchase was acknowledged or consumed.
final String? developerPayload;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is PurchaseHistoryRecordWrapper &&
other.purchaseTime == purchaseTime &&
other.purchaseToken == purchaseToken &&
other.signature == signature &&
listEquals(other.products, products) &&
other.originalJson == originalJson &&
other.developerPayload == developerPayload;
}
@override
int get hashCode => Object.hash(
purchaseTime,
purchaseToken,
signature,
products.hashCode,
originalJson,
developerPayload,
);
}
/// A data struct representing the result of a transaction.
///
/// Contains a potentially empty list of [PurchaseWrapper]s, a [BillingResultWrapper]
/// that contains a detailed description of the status and a
/// [BillingResponse] to signify the overall state of the transaction.
///
/// Wraps [`com.android.billingclient.api.Purchase.PurchasesResult`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchasesResult).
@JsonSerializable()
@BillingResponseConverter()
@immutable
class PurchasesResultWrapper implements HasBillingResponse {
/// Creates a [PurchasesResultWrapper] with the given purchase result details.
const PurchasesResultWrapper(
{required this.responseCode,
required this.billingResult,
required this.purchasesList});
/// Factory for creating a [PurchaseResultWrapper] from a [Map] with the result details.
factory PurchasesResultWrapper.fromJson(Map<String, dynamic> map) =>
_$PurchasesResultWrapperFromJson(map);
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is PurchasesResultWrapper &&
other.responseCode == responseCode &&
other.purchasesList == purchasesList &&
other.billingResult == billingResult;
}
@override
int get hashCode => Object.hash(billingResult, responseCode, purchasesList);
/// The detailed description of the status of the operation.
final BillingResultWrapper billingResult;
/// The status of the operation.
///
/// This can represent either the status of the "query purchase history" half
/// of the operation and the "user made purchases" transaction itself.
@override
final BillingResponse responseCode;
/// The list of successful purchases made in this transaction.
///
/// May be empty, especially if [responseCode] is not [BillingResponse.ok].
@JsonKey(defaultValue: <PurchaseWrapper>[])
final List<PurchaseWrapper> purchasesList;
}
/// A data struct representing the result of a purchase history.
///
/// Contains a potentially empty list of [PurchaseHistoryRecordWrapper]s and a [BillingResultWrapper]
/// that contains a detailed description of the status.
@JsonSerializable()
@BillingResponseConverter()
@immutable
class PurchasesHistoryResult implements HasBillingResponse {
/// Creates a [PurchasesHistoryResult] with the provided history.
const PurchasesHistoryResult(
{required this.billingResult, required this.purchaseHistoryRecordList});
/// Factory for creating a [PurchasesHistoryResult] from a [Map] with the history result details.
factory PurchasesHistoryResult.fromJson(Map<String, dynamic> map) =>
_$PurchasesHistoryResultFromJson(map);
@override
BillingResponse get responseCode => billingResult.responseCode;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is PurchasesHistoryResult &&
other.purchaseHistoryRecordList == purchaseHistoryRecordList &&
other.billingResult == billingResult;
}
@override
int get hashCode => Object.hash(billingResult, purchaseHistoryRecordList);
/// The detailed description of the status of the [BillingClient.queryPurchaseHistory].
final BillingResultWrapper billingResult;
/// The list of queried purchase history records.
///
/// May be empty, especially if [billingResult.responseCode] is not [BillingResponse.ok].
@JsonKey(defaultValue: <PurchaseHistoryRecordWrapper>[])
final List<PurchaseHistoryRecordWrapper> purchaseHistoryRecordList;
}
/// Possible state of a [PurchaseWrapper].
///
/// Wraps
/// [`BillingClient.api.Purchase.PurchaseState`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchaseState.html).
/// * See also: [PurchaseWrapper].
@JsonEnum(alwaysCreate: true)
enum PurchaseStateWrapper {
/// The state is unspecified.
///
/// No actions on the [PurchaseWrapper] should be performed on this state.
/// This is a catch-all. It should never be returned by the Play Billing Library.
@JsonValue(0)
unspecified_state,
/// The user has completed the purchase process.
///
/// The production should be delivered and then the purchase should be acknowledged.
/// * See also [BillingClient.acknowledgePurchase] for more details on acknowledging purchases.
@JsonValue(1)
purchased,
/// The user has started the purchase process.
///
/// The user should follow the instructions that were given to them by the Play
/// Billing Library to complete the purchase.
///
/// You can also choose to remind the user to complete the purchase if you detected a
/// [PurchaseWrapper] is still in the `pending` state in the future while calling [BillingClient.queryPurchases].
@JsonValue(2)
pending,
}
/// Serializer for [PurchaseStateWrapper].
///
/// Use these in `@JsonSerializable()` classes by annotating them with
/// `@PurchaseStateConverter()`.
class PurchaseStateConverter
implements JsonConverter<PurchaseStateWrapper, int?> {
/// Default const constructor.
const PurchaseStateConverter();
@override
PurchaseStateWrapper fromJson(int? json) {
if (json == null) {
return PurchaseStateWrapper.unspecified_state;
}
return $enumDecode(_$PurchaseStateWrapperEnumMap, json);
}
@override
int toJson(PurchaseStateWrapper object) =>
_$PurchaseStateWrapperEnumMap[object]!;
/// Converts the purchase state stored in `object` to a [PurchaseStatus].
///
/// [PurchaseStateWrapper.unspecified_state] is mapped to [PurchaseStatus.error].
PurchaseStatus toPurchaseStatus(PurchaseStateWrapper object) {
switch (object) {
case PurchaseStateWrapper.pending:
return PurchaseStatus.pending;
case PurchaseStateWrapper.purchased:
return PurchaseStatus.purchased;
case PurchaseStateWrapper.unspecified_state:
return PurchaseStatus.error;
}
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart",
"repo_id": "packages",
"token_count": 4574
} | 1,058 |
// 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 "Stubs.h"
@implementation SKProductSubscriptionPeriodStub
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
[self setValue:map[@"numberOfUnits"] ?: @(0) forKey:@"numberOfUnits"];
[self setValue:map[@"unit"] ?: @(0) forKey:@"unit"];
}
return self;
}
@end
@implementation SKProductDiscountStub
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
[self setValue:[[NSDecimalNumber alloc] initWithString:map[@"price"]] ?: [NSNull null]
forKey:@"price"];
NSLocale *locale = NSLocale.systemLocale;
[self setValue:locale ?: [NSNull null] forKey:@"priceLocale"];
[self setValue:map[@"numberOfPeriods"] ?: @(0) forKey:@"numberOfPeriods"];
SKProductSubscriptionPeriodStub *subscriptionPeriodSub =
[[SKProductSubscriptionPeriodStub alloc] initWithMap:map[@"subscriptionPeriod"]];
[self setValue:subscriptionPeriodSub forKey:@"subscriptionPeriod"];
[self setValue:map[@"paymentMode"] ?: @(0) forKey:@"paymentMode"];
if (@available(iOS 12.2, *)) {
[self setValue:map[@"identifier"] ?: [NSNull null] forKey:@"identifier"];
[self setValue:map[@"type"] ?: @(0) forKey:@"type"];
}
}
return self;
}
@end
@implementation SKProductStub
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
[self setValue:map[@"productIdentifier"] ?: [NSNull null] forKey:@"productIdentifier"];
[self setValue:map[@"localizedDescription"] ?: [NSNull null] forKey:@"localizedDescription"];
[self setValue:map[@"localizedTitle"] ?: [NSNull null] forKey:@"localizedTitle"];
[self setValue:map[@"downloadable"] ?: @NO forKey:@"downloadable"];
[self setValue:[[NSDecimalNumber alloc] initWithString:map[@"price"]] ?: [NSNull null]
forKey:@"price"];
NSLocale *locale = NSLocale.systemLocale;
[self setValue:locale ?: [NSNull null] forKey:@"priceLocale"];
[self setValue:map[@"downloadContentLengths"] ?: @(0) forKey:@"downloadContentLengths"];
SKProductSubscriptionPeriodStub *period =
[[SKProductSubscriptionPeriodStub alloc] initWithMap:map[@"subscriptionPeriod"]];
[self setValue:period ?: [NSNull null] forKey:@"subscriptionPeriod"];
SKProductDiscountStub *discount =
[[SKProductDiscountStub alloc] initWithMap:map[@"introductoryPrice"]];
[self setValue:discount ?: [NSNull null] forKey:@"introductoryPrice"];
[self setValue:map[@"subscriptionGroupIdentifier"] ?: [NSNull null]
forKey:@"subscriptionGroupIdentifier"];
if (@available(iOS 12.2, *)) {
NSMutableArray *discounts = [[NSMutableArray alloc] init];
for (NSDictionary *discountMap in map[@"discounts"]) {
[discounts addObject:[[SKProductDiscountStub alloc] initWithMap:discountMap]];
}
[self setValue:discounts forKey:@"discounts"];
}
}
return self;
}
- (instancetype)initWithProductID:(NSString *)productIdentifier {
self = [super init];
if (self) {
[self setValue:productIdentifier forKey:@"productIdentifier"];
}
return self;
}
@end
@interface SKProductRequestStub ()
@property(strong, nonatomic) NSSet *identifers;
@property(strong, nonatomic) NSError *error;
@end
@implementation SKProductRequestStub
- (instancetype)initWithProductIdentifiers:(NSSet<NSString *> *)productIdentifiers {
self = [super initWithProductIdentifiers:productIdentifiers];
self.identifers = productIdentifiers;
return self;
}
- (instancetype)initWithFailureError:(NSError *)error {
self = [super init];
self.error = error;
return self;
}
- (void)start {
NSMutableArray *productArray = [NSMutableArray new];
for (NSString *identifier in self.identifers) {
[productArray addObject:@{@"productIdentifier" : identifier}];
}
SKProductsResponseStub *response;
if (self.returnError) {
response = nil;
} else {
response = [[SKProductsResponseStub alloc] initWithMap:@{@"products" : productArray}];
}
if (self.error) {
[self.delegate request:self didFailWithError:self.error];
} else {
[self.delegate productsRequest:self didReceiveResponse:response];
}
}
@end
@implementation SKProductsResponseStub
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
NSMutableArray *products = [NSMutableArray new];
for (NSDictionary *productMap in map[@"products"]) {
SKProductStub *product = [[SKProductStub alloc] initWithMap:productMap];
[products addObject:product];
}
[self setValue:products forKey:@"products"];
}
return self;
}
@end
@interface InAppPurchasePluginStub ()
@end
@implementation InAppPurchasePluginStub
- (SKProductRequestStub *)getProductRequestWithIdentifiers:(NSSet *)identifiers {
return [[SKProductRequestStub alloc] initWithProductIdentifiers:identifiers];
}
- (SKProduct *)getProduct:(NSString *)productID {
if ([productID isEqualToString:@""]) {
return nil;
}
return [[SKProductStub alloc] initWithProductID:productID];
}
- (SKReceiptRefreshRequestStub *)getRefreshReceiptRequest:(NSDictionary *)properties {
return [[SKReceiptRefreshRequestStub alloc] initWithReceiptProperties:properties];
}
@end
@interface SKPaymentQueueStub ()
@end
@implementation SKPaymentQueueStub
- (void)addTransactionObserver:(id<SKPaymentTransactionObserver>)observer {
self.observer = observer;
}
- (void)removeTransactionObserver:(id<SKPaymentTransactionObserver>)observer {
self.observer = nil;
}
- (void)addPayment:(SKPayment *)payment {
SKPaymentTransactionStub *transaction =
[[SKPaymentTransactionStub alloc] initWithState:self.testState payment:payment];
[self.observer paymentQueue:self updatedTransactions:@[ transaction ]];
}
- (void)restoreCompletedTransactions {
if ([self.observer
respondsToSelector:@selector(paymentQueueRestoreCompletedTransactionsFinished:)]) {
[self.observer paymentQueueRestoreCompletedTransactionsFinished:self];
}
}
- (void)finishTransaction:(SKPaymentTransaction *)transaction {
if ([self.observer respondsToSelector:@selector(paymentQueue:removedTransactions:)]) {
[self.observer paymentQueue:self removedTransactions:@[ transaction ]];
}
}
@end
@implementation SKPaymentTransactionStub {
SKPayment *_payment;
}
- (instancetype)initWithID:(NSString *)identifier {
self = [super init];
if (self) {
[self setValue:identifier forKey:@"transactionIdentifier"];
}
return self;
}
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
[self setValue:map[@"transactionIdentifier"] forKey:@"transactionIdentifier"];
[self setValue:map[@"transactionState"] forKey:@"transactionState"];
if (![map[@"originalTransaction"] isKindOfClass:[NSNull class]] &&
map[@"originalTransaction"]) {
[self setValue:[[SKPaymentTransactionStub alloc] initWithMap:map[@"originalTransaction"]]
forKey:@"originalTransaction"];
}
[self setValue:map[@"error"] ? [[NSErrorStub alloc] initWithMap:map[@"error"]] : [NSNull null]
forKey:@"error"];
[self setValue:[NSDate dateWithTimeIntervalSince1970:[map[@"transactionTimeStamp"] doubleValue]]
forKey:@"transactionDate"];
}
return self;
}
- (instancetype)initWithState:(SKPaymentTransactionState)state {
self = [super init];
if (self) {
// Only purchased and restored transactions have transactionIdentifier:
// https://developer.apple.com/documentation/storekit/skpaymenttransaction/1411288-transactionidentifier?language=objc
if (state == SKPaymentTransactionStatePurchased || state == SKPaymentTransactionStateRestored) {
[self setValue:@"fakeID" forKey:@"transactionIdentifier"];
}
[self setValue:@(state) forKey:@"transactionState"];
}
return self;
}
- (instancetype)initWithState:(SKPaymentTransactionState)state payment:(SKPayment *)payment {
self = [super init];
if (self) {
// Only purchased and restored transactions have transactionIdentifier:
// https://developer.apple.com/documentation/storekit/skpaymenttransaction/1411288-transactionidentifier?language=objc
if (state == SKPaymentTransactionStatePurchased || state == SKPaymentTransactionStateRestored) {
[self setValue:@"fakeID" forKey:@"transactionIdentifier"];
}
[self setValue:@(state) forKey:@"transactionState"];
_payment = payment;
}
return self;
}
- (SKPayment *)payment {
return _payment;
}
@end
@implementation NSErrorStub
- (instancetype)initWithMap:(NSDictionary *)map {
return [self initWithDomain:[map objectForKey:@"domain"]
code:[[map objectForKey:@"code"] integerValue]
userInfo:[map objectForKey:@"userInfo"]];
}
@end
@implementation FIAPReceiptManagerStub : FIAPReceiptManager
- (NSData *)getReceiptData:(NSURL *)url error:(NSError **)error {
if (self.returnError) {
*error = [NSError errorWithDomain:@"test"
code:1
userInfo:@{
@"name" : @"test",
@"houseNr" : @5,
@"error" : [[NSError alloc] initWithDomain:@"internalTestDomain"
code:99
userInfo:nil]
}];
return nil;
}
NSString *originalString = [NSString stringWithFormat:@"test"];
return [[NSData alloc] initWithBase64EncodedString:originalString options:kNilOptions];
}
@end
@implementation SKReceiptRefreshRequestStub {
NSError *_error;
}
- (instancetype)initWithReceiptProperties:(NSDictionary<NSString *, id> *)properties {
self = [super initWithReceiptProperties:properties];
return self;
}
- (instancetype)initWithFailureError:(NSError *)error {
self = [super init];
_error = error;
return self;
}
- (void)start {
if (_error) {
[self.delegate request:self didFailWithError:_error];
} else {
[self.delegate requestDidFinish:self];
}
}
@end
@implementation SKStorefrontStub
- (instancetype)initWithMap:(NSDictionary *)map {
self = [super init];
if (self) {
// Set stub values
[self setValue:map[@"countryCode"] forKey:@"countryCode"];
[self setValue:map[@"identifier"] forKey:@"identifier"];
}
return self;
}
@end
| packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/Stubs.m/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/Stubs.m",
"repo_id": "packages",
"token_count": 4090
} | 1,059 |
// 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:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import '../messages.g.dart';
import 'enum_converters.dart';
// WARNING: Changes to `@JsonSerializable` classes need to be reflected in the
// below generated file. Run `flutter packages pub run build_runner watch` to
// rebuild and watch for further changes.
part 'sk_product_wrapper.g.dart';
/// Dart wrapper around StoreKit's [SKProductsResponse](https://developer.apple.com/documentation/storekit/skproductsresponse?language=objc).
///
/// Represents the response object returned by [SKRequestMaker.startProductRequest].
/// Contains information about a list of products and a list of invalid product identifiers.
@JsonSerializable()
@immutable
class SkProductResponseWrapper {
/// Creates an [SkProductResponseWrapper] with the given product details.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SkProductResponseWrapper(
{required this.products, required this.invalidProductIdentifiers});
/// Constructing an instance from a map from the Objective-C layer.
///
/// This method should only be used with `map` values returned by [SKRequestMaker.startProductRequest].
factory SkProductResponseWrapper.fromJson(Map<String, dynamic> map) {
return _$SkProductResponseWrapperFromJson(map);
}
/// Stores all matching successfully found products.
///
/// One product in this list matches one valid product identifier passed to the [SKRequestMaker.startProductRequest].
/// Will be empty if the [SKRequestMaker.startProductRequest] method does not pass any correct product identifier.
@JsonKey(defaultValue: <SKProductWrapper>[])
final List<SKProductWrapper> products;
/// Stores product identifiers in the `productIdentifiers` from [SKRequestMaker.startProductRequest] that are not recognized by the App Store.
///
/// The App Store will not recognize a product identifier unless certain criteria are met. A detailed list of the criteria can be
/// found here https://developer.apple.com/documentation/storekit/skproductsresponse/1505985-invalidproductidentifiers?language=objc.
/// Will be empty if all the product identifiers are valid.
@JsonKey(defaultValue: <String>[])
final List<String> invalidProductIdentifiers;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SkProductResponseWrapper &&
const DeepCollectionEquality().equals(other.products, products) &&
const DeepCollectionEquality()
.equals(other.invalidProductIdentifiers, invalidProductIdentifiers);
}
@override
int get hashCode => Object.hash(products, invalidProductIdentifiers);
/// Convert from [SkProductResponseMessage] to [SkProductResponseWrapper]
static SkProductResponseWrapper convertFromPigeon(
SKProductsResponseMessage msg) {
return SkProductResponseWrapper(
products: msg.products!
.map((SKProductMessage? e) => SKProductWrapper.convertFromPigeon(e!))
.toList(),
invalidProductIdentifiers: msg.invalidProductIdentifiers != null
? msg.invalidProductIdentifiers!.cast<String>()
: <String>[],
);
}
/// Convert from [SkProductResponseWrapper] to [SkProductResponseWrapper]
@visibleForTesting
static SKProductsResponseMessage convertToPigeon(
SkProductResponseWrapper wrapper) {
return SKProductsResponseMessage(
products: wrapper.products
.map((SKProductWrapper? e) => SKProductWrapper.convertToPigeon(e!))
.toList(),
invalidProductIdentifiers:
wrapper.invalidProductIdentifiers.cast<String>());
}
}
/// Dart wrapper around StoreKit's [SKProductPeriodUnit](https://developer.apple.com/documentation/storekit/skproductperiodunit?language=objc).
///
/// Used as a property in the [SKProductSubscriptionPeriodWrapper]. Minimum is a day and maximum is a year.
// The values of the enum options are matching the [SKProductPeriodUnit]'s values. Should there be an update or addition
// in the [SKProductPeriodUnit], this need to be updated to match.
enum SKSubscriptionPeriodUnit {
/// An interval lasting one day.
@JsonValue(0)
day,
/// An interval lasting one month.
@JsonValue(1)
/// An interval lasting one week.
week,
@JsonValue(2)
/// An interval lasting one month.
month,
/// An interval lasting one year.
@JsonValue(3)
year;
/// Convert from [SKSubscriptionPeriodUnitMessage] to [SKSubscriptionPeriodUnit]
static SKSubscriptionPeriodUnit convertFromPigeon(
SKSubscriptionPeriodUnitMessage msg) {
switch (msg) {
case SKSubscriptionPeriodUnitMessage.day:
return SKSubscriptionPeriodUnit.day;
case SKSubscriptionPeriodUnitMessage.week:
return SKSubscriptionPeriodUnit.week;
case SKSubscriptionPeriodUnitMessage.month:
return SKSubscriptionPeriodUnit.month;
case SKSubscriptionPeriodUnitMessage.year:
return SKSubscriptionPeriodUnit.year;
}
}
/// Convert from [SKSubscriptionPeriodUnit] to [SKSubscriptionPeriodUnitMessage]
@visibleForTesting
static SKSubscriptionPeriodUnitMessage convertToPigeon(
SKSubscriptionPeriodUnit msg) {
switch (msg) {
case SKSubscriptionPeriodUnit.day:
return SKSubscriptionPeriodUnitMessage.day;
case SKSubscriptionPeriodUnit.week:
return SKSubscriptionPeriodUnitMessage.week;
case SKSubscriptionPeriodUnit.month:
return SKSubscriptionPeriodUnitMessage.month;
case SKSubscriptionPeriodUnit.year:
return SKSubscriptionPeriodUnitMessage.year;
}
}
}
/// Dart wrapper around StoreKit's [SKProductSubscriptionPeriod](https://developer.apple.com/documentation/storekit/skproductsubscriptionperiod?language=objc).
///
/// A period is defined by a [numberOfUnits] and a [unit], e.g for a 3 months period [numberOfUnits] is 3 and [unit] is a month.
/// It is used as a property in [SKProductDiscountWrapper] and [SKProductWrapper].
@JsonSerializable()
@immutable
class SKProductSubscriptionPeriodWrapper {
/// Creates an [SKProductSubscriptionPeriodWrapper] for a `numberOfUnits`x`unit` period.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SKProductSubscriptionPeriodWrapper(
{required this.numberOfUnits, required this.unit});
/// Constructing an instance from a map from the Objective-C layer.
///
/// This method should only be used with `map` values returned by [SKProductDiscountWrapper.fromJson] or [SKProductWrapper.fromJson].
factory SKProductSubscriptionPeriodWrapper.fromJson(
Map<String, dynamic>? map) {
if (map == null) {
return SKProductSubscriptionPeriodWrapper(
numberOfUnits: 0, unit: SKSubscriptionPeriodUnit.day);
}
return _$SKProductSubscriptionPeriodWrapperFromJson(map);
}
/// The number of [unit] units in this period.
///
/// Must be greater than 0 if the object is valid.
@JsonKey(defaultValue: 0)
final int numberOfUnits;
/// The time unit used to specify the length of this period.
@SKSubscriptionPeriodUnitConverter()
final SKSubscriptionPeriodUnit unit;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SKProductSubscriptionPeriodWrapper &&
other.numberOfUnits == numberOfUnits &&
other.unit == unit;
}
@override
int get hashCode => Object.hash(numberOfUnits, unit);
/// Convert from [SKProductSubscriptionPeriodMessage] to [SKProductSubscriptionPeriodWrapper]
static SKProductSubscriptionPeriodWrapper convertFromPigeon(
SKProductSubscriptionPeriodMessage msg) {
return SKProductSubscriptionPeriodWrapper(
numberOfUnits: msg.numberOfUnits,
unit: SKSubscriptionPeriodUnit.convertFromPigeon(msg.unit));
}
/// Convert from [SKProductSubscriptionPeriodWrapper] to [SKProductSubscriptionPeriodMessage]
@visibleForTesting
static SKProductSubscriptionPeriodMessage convertToPigeon(
SKProductSubscriptionPeriodWrapper wrapper) {
return SKProductSubscriptionPeriodMessage(
numberOfUnits: wrapper.numberOfUnits,
unit: SKSubscriptionPeriodUnit.convertToPigeon(wrapper.unit));
}
}
/// Dart wrapper around StoreKit's [SKProductDiscountPaymentMode](https://developer.apple.com/documentation/storekit/skproductdiscountpaymentmode?language=objc).
///
/// This is used as a property in the [SKProductDiscountWrapper].
// The values of the enum options are matching the [SKProductDiscountPaymentMode]'s values. Should there be an update or addition
// in the [SKProductDiscountPaymentMode], this need to be updated to match.
enum SKProductDiscountPaymentMode {
/// Allows user to pay the discounted price at each payment period.
@JsonValue(0)
payAsYouGo,
/// Allows user to pay the discounted price upfront and receive the product for the rest of time that was paid for.
@JsonValue(1)
payUpFront,
/// User pays nothing during the discounted period.
@JsonValue(2)
freeTrail,
/// Unspecified mode.
@JsonValue(-1)
unspecified;
/// Convert from [SKProductDiscountPaymentModeMessage] to [SKProductDiscountPaymentModeWrapper]
static SKProductDiscountPaymentMode convertFromPigeon(
SKProductDiscountPaymentModeMessage msg) {
switch (msg) {
case SKProductDiscountPaymentModeMessage.payAsYouGo:
return SKProductDiscountPaymentMode.payAsYouGo;
case SKProductDiscountPaymentModeMessage.payUpFront:
return SKProductDiscountPaymentMode.payUpFront;
case SKProductDiscountPaymentModeMessage.freeTrial:
return SKProductDiscountPaymentMode.freeTrail;
case SKProductDiscountPaymentModeMessage.unspecified:
return SKProductDiscountPaymentMode.unspecified;
}
}
/// Convert from [SKProductDiscountPaymentModeMessage] to [SKProductDiscountPaymentMode]
@visibleForTesting
static SKProductDiscountPaymentModeMessage convertToPigeon(
SKProductDiscountPaymentMode wrapper) {
switch (wrapper) {
case SKProductDiscountPaymentMode.payAsYouGo:
return SKProductDiscountPaymentModeMessage.payAsYouGo;
case SKProductDiscountPaymentMode.payUpFront:
return SKProductDiscountPaymentModeMessage.payUpFront;
case SKProductDiscountPaymentMode.freeTrail:
return SKProductDiscountPaymentModeMessage.freeTrial;
case SKProductDiscountPaymentMode.unspecified:
return SKProductDiscountPaymentModeMessage.unspecified;
}
}
}
/// Dart wrapper around StoreKit's [SKProductDiscountType]
/// (https://developer.apple.com/documentation/storekit/skproductdiscounttype?language=objc)
///
/// This is used as a property in the [SKProductDiscountWrapper].
/// The values of the enum options are matching the [SKProductDiscountType]'s
/// values.
///
/// Values representing the types of discount offers an app can present.
enum SKProductDiscountType {
/// A constant indicating the discount type is an introductory offer.
@JsonValue(0)
introductory,
/// A constant indicating the discount type is a promotional offer.
@JsonValue(1)
subscription;
/// Convert from [SKProductDiscountTypeMessage] to [SKProductDiscountType]
static SKProductDiscountType convertFromPigeon(
SKProductDiscountTypeMessage msg) {
switch (msg) {
case SKProductDiscountTypeMessage.introductory:
return SKProductDiscountType.introductory;
case SKProductDiscountTypeMessage.subscription:
return SKProductDiscountType.subscription;
}
}
/// Convert from [SKProductDiscountType] to [SKProductDiscountTypeMessage]
@visibleForTesting
static SKProductDiscountTypeMessage convertToPigeon(
SKProductDiscountType wrapper) {
switch (wrapper) {
case SKProductDiscountType.introductory:
return SKProductDiscountTypeMessage.introductory;
case SKProductDiscountType.subscription:
return SKProductDiscountTypeMessage.subscription;
}
}
}
/// Dart wrapper around StoreKit's [SKProductDiscount](https://developer.apple.com/documentation/storekit/skproductdiscount?language=objc).
///
/// It is used as a property in [SKProductWrapper].
@JsonSerializable()
@immutable
class SKProductDiscountWrapper {
/// Creates an [SKProductDiscountWrapper] with the given discount details.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SKProductDiscountWrapper(
{required this.price,
required this.priceLocale,
required this.numberOfPeriods,
required this.paymentMode,
required this.subscriptionPeriod,
required this.identifier,
required this.type});
/// Constructing an instance from a map from the Objective-C layer.
///
/// This method should only be used with `map` values returned by [SKProductWrapper.fromJson].
factory SKProductDiscountWrapper.fromJson(Map<String, dynamic> map) {
return _$SKProductDiscountWrapperFromJson(map);
}
/// The discounted price, in the currency that is defined in [priceLocale].
@JsonKey(defaultValue: '')
final String price;
/// Includes locale information about the price, e.g. `$` as the currency symbol for US locale.
final SKPriceLocaleWrapper priceLocale;
/// The object represent the discount period length.
///
/// The value must be >= 0 if the object is valid.
@JsonKey(defaultValue: 0)
final int numberOfPeriods;
/// The object indicates how the discount price is charged.
@SKProductDiscountPaymentModeConverter()
final SKProductDiscountPaymentMode paymentMode;
/// The object represents the duration of single subscription period for the discount.
///
/// The [subscriptionPeriod] of the discount is independent of the product's [subscriptionPeriod],
/// and their units and duration do not have to be matched.
final SKProductSubscriptionPeriodWrapper subscriptionPeriod;
/// A string used to uniquely identify a discount offer for a product.
///
/// You set up offers and their identifiers in App Store Connect.
@JsonKey(defaultValue: null)
final String? identifier;
/// Values representing the types of discount offers an app can present.
@SKProductDiscountTypeConverter()
final SKProductDiscountType type;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SKProductDiscountWrapper &&
other.price == price &&
other.priceLocale == priceLocale &&
other.numberOfPeriods == numberOfPeriods &&
other.paymentMode == paymentMode &&
other.subscriptionPeriod == subscriptionPeriod &&
other.identifier == identifier &&
other.type == type;
}
@override
int get hashCode => Object.hash(price, priceLocale, numberOfPeriods,
paymentMode, subscriptionPeriod, identifier, type);
/// Convert from [SKProductDiscountMessage] to [SKProductDiscountWrapper]
static SKProductDiscountWrapper convertFromPigeon(
SKProductDiscountMessage msg) {
return SKProductDiscountWrapper(
price: msg.price,
priceLocale: SKPriceLocaleWrapper.convertFromPigeon(msg.priceLocale),
numberOfPeriods: msg.numberOfPeriods,
paymentMode:
SKProductDiscountPaymentMode.convertFromPigeon(msg.paymentMode),
subscriptionPeriod:
SKProductSubscriptionPeriodWrapper.convertFromPigeon(
msg.subscriptionPeriod),
identifier: msg.identifier,
type: SKProductDiscountType.convertFromPigeon(msg.type));
}
/// Convert from [SKProductDiscountWrapper] to [SKProductDiscountMessage]
@visibleForTesting
static SKProductDiscountMessage convertToPigeon(
SKProductDiscountWrapper wrapper) {
return SKProductDiscountMessage(
price: wrapper.price,
priceLocale: SKPriceLocaleWrapper.convertToPigeon(wrapper.priceLocale),
numberOfPeriods: wrapper.numberOfPeriods,
paymentMode:
SKProductDiscountPaymentMode.convertToPigeon(wrapper.paymentMode),
subscriptionPeriod: SKProductSubscriptionPeriodWrapper.convertToPigeon(
wrapper.subscriptionPeriod),
identifier: wrapper.identifier,
type: SKProductDiscountType.convertToPigeon(wrapper.type));
}
}
/// Dart wrapper around StoreKit's [SKProduct](https://developer.apple.com/documentation/storekit/skproduct?language=objc).
///
/// A list of [SKProductWrapper] is returned in the [SKRequestMaker.startProductRequest] method, and
/// should be stored for use when making a payment.
@JsonSerializable()
@immutable
class SKProductWrapper {
/// Creates an [SKProductWrapper] with the given product details.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SKProductWrapper({
required this.productIdentifier,
required this.localizedTitle,
required this.localizedDescription,
required this.priceLocale,
this.subscriptionGroupIdentifier,
required this.price,
this.subscriptionPeriod,
this.introductoryPrice,
this.discounts = const <SKProductDiscountWrapper>[],
});
/// Constructing an instance from a map from the Objective-C layer.
///
/// This method should only be used with `map` values returned by [SkProductResponseWrapper.fromJson].
factory SKProductWrapper.fromJson(Map<String, dynamic> map) {
return _$SKProductWrapperFromJson(map);
}
/// The unique identifier of the product.
@JsonKey(defaultValue: '')
final String productIdentifier;
/// The localizedTitle of the product.
///
/// It is localized based on the current locale.
@JsonKey(defaultValue: '')
final String localizedTitle;
/// The localized description of the product.
///
/// It is localized based on the current locale.
@JsonKey(defaultValue: '')
final String localizedDescription;
/// Includes locale information about the price, e.g. `$` as the currency symbol for US locale.
final SKPriceLocaleWrapper priceLocale;
/// The subscription group identifier.
///
/// If the product is not a subscription, the value is `null`.
///
/// A subscription group is a collection of subscription products.
/// Check [SubscriptionGroup](https://developer.apple.com/app-store/subscriptions/) for more details about subscription group.
final String? subscriptionGroupIdentifier;
/// The price of the product, in the currency that is defined in [priceLocale].
@JsonKey(defaultValue: '')
final String price;
/// The object represents the subscription period of the product.
///
/// Can be [null] is the product is not a subscription.
final SKProductSubscriptionPeriodWrapper? subscriptionPeriod;
/// The object represents the duration of single subscription period.
///
/// This is only available if you set up the introductory price in the App Store Connect, otherwise the value is `null`.
/// Programmer is also responsible to determine if the user is eligible to receive it. See https://developer.apple.com/documentation/storekit/in-app_purchase/offering_introductory_pricing_in_your_app?language=objc
/// for more details.
/// The [subscriptionPeriod] of the discount is independent of the product's [subscriptionPeriod],
/// and their units and duration do not have to be matched.
final SKProductDiscountWrapper? introductoryPrice;
/// An array of subscription offers available for the auto-renewable subscription (available on iOS 12.2 and higher).
///
/// This property lists all promotional offers set up in App Store Connect. If
/// no promotional offers have been set up, this field returns an empty list.
/// Each [subscriptionPeriod] of individual discounts are independent of the
/// product's [subscriptionPeriod] and their units and duration do not have to
/// be matched.
@JsonKey(defaultValue: <SKProductDiscountWrapper>[])
final List<SKProductDiscountWrapper> discounts;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SKProductWrapper &&
other.productIdentifier == productIdentifier &&
other.localizedTitle == localizedTitle &&
other.localizedDescription == localizedDescription &&
other.priceLocale == priceLocale &&
other.subscriptionGroupIdentifier == subscriptionGroupIdentifier &&
other.price == price &&
other.subscriptionPeriod == subscriptionPeriod &&
other.introductoryPrice == introductoryPrice &&
const DeepCollectionEquality().equals(other.discounts, discounts);
}
@override
int get hashCode => Object.hash(
productIdentifier,
localizedTitle,
localizedDescription,
priceLocale,
subscriptionGroupIdentifier,
price,
subscriptionPeriod,
introductoryPrice,
discounts);
/// Convert from [SKProductMessage] to [SKProductWrapper]
static SKProductWrapper convertFromPigeon(SKProductMessage msg) {
return SKProductWrapper(
productIdentifier: msg.productIdentifier,
localizedTitle: msg.localizedTitle,
localizedDescription: msg.localizedDescription,
priceLocale: SKPriceLocaleWrapper.convertFromPigeon(msg.priceLocale),
price: msg.price,
subscriptionGroupIdentifier: msg.subscriptionGroupIdentifier,
subscriptionPeriod: msg.subscriptionPeriod != null
? SKProductSubscriptionPeriodWrapper.convertFromPigeon(
msg.subscriptionPeriod!)
: null,
introductoryPrice: msg.introductoryPrice != null
? SKProductDiscountWrapper.convertFromPigeon(msg.introductoryPrice!)
: null,
discounts: msg.discounts != null
? msg.discounts!
.map((SKProductDiscountMessage? e) =>
SKProductDiscountWrapper.convertFromPigeon(e!))
.toList()
: <SKProductDiscountWrapper>[]);
}
/// Convert from [SKProductWrapper] to [SKProductMessage]
static SKProductMessage convertToPigeon(SKProductWrapper wrapper) {
return SKProductMessage(
productIdentifier: wrapper.productIdentifier,
localizedTitle: wrapper.localizedTitle,
localizedDescription: wrapper.localizedDescription,
priceLocale: SKPriceLocaleWrapper.convertToPigeon(wrapper.priceLocale),
price: wrapper.price,
subscriptionGroupIdentifier: wrapper.subscriptionGroupIdentifier,
subscriptionPeriod: wrapper.subscriptionPeriod != null
? SKProductSubscriptionPeriodWrapper.convertToPigeon(
wrapper.subscriptionPeriod!)
: null,
introductoryPrice: wrapper.introductoryPrice != null
? SKProductDiscountWrapper.convertToPigeon(
wrapper.introductoryPrice!)
: null,
discounts: wrapper.discounts
.map((SKProductDiscountWrapper? e) =>
SKProductDiscountWrapper.convertToPigeon(e!))
.toList());
}
}
/// Object that indicates the locale of the price
///
/// It is a thin wrapper of [NSLocale](https://developer.apple.com/documentation/foundation/nslocale?language=objc).
// TODO(cyanglaz): NSLocale is a complex object, want to see the actual need of getting this expanded.
// Matching android to only get the currencySymbol for now.
// https://github.com/flutter/flutter/issues/26610
@JsonSerializable()
@immutable
class SKPriceLocaleWrapper {
/// Creates a new price locale for `currencySymbol` and `currencyCode`.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SKPriceLocaleWrapper({
required this.currencySymbol,
required this.currencyCode,
required this.countryCode,
});
/// Constructing an instance from a map from the Objective-C layer.
///
/// This method should only be used with `map` values returned by [SKProductWrapper.fromJson] and [SKProductDiscountWrapper.fromJson].
factory SKPriceLocaleWrapper.fromJson(Map<String, dynamic>? map) {
if (map == null) {
return SKPriceLocaleWrapper(
currencyCode: '', currencySymbol: '', countryCode: '');
}
return _$SKPriceLocaleWrapperFromJson(map);
}
///The currency symbol for the locale, e.g. $ for US locale.
@JsonKey(defaultValue: '')
final String currencySymbol;
///The currency code for the locale, e.g. USD for US locale.
@JsonKey(defaultValue: '')
final String currencyCode;
///The country code for the locale, e.g. US for US locale.
@JsonKey(defaultValue: '')
final String countryCode;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SKPriceLocaleWrapper &&
other.currencySymbol == currencySymbol &&
other.currencyCode == currencyCode;
}
@override
int get hashCode => Object.hash(currencySymbol, currencyCode);
/// Convert from [SKPriceLocaleMessage] to [SKPriceLocaleWrapper]
static SKPriceLocaleWrapper convertFromPigeon(SKPriceLocaleMessage msg) {
return SKPriceLocaleWrapper(
currencySymbol: msg.currencySymbol,
currencyCode: msg.currencyCode,
countryCode: msg.countryCode);
}
/// Convert from [SKPriceLocaleWrapper] to [SKPriceLocaleMessage]
@visibleForTesting
static SKPriceLocaleMessage convertToPigeon(SKPriceLocaleWrapper msg) {
return SKPriceLocaleMessage(
currencySymbol: msg.currencySymbol,
currencyCode: msg.currencyCode,
countryCode: msg.countryCode);
}
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart",
"repo_id": "packages",
"token_count": 8609
} | 1,060 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/src/store_kit_wrappers/enum_converters.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'fakes/fake_storekit_platform.dart';
import 'store_kit_wrappers/sk_test_stub_objects.dart';
import 'test_api.g.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
late InAppPurchaseStoreKitPlatform iapStoreKitPlatform;
setUpAll(() {
TestInAppPurchaseApi.setup(fakeStoreKitPlatform);
});
setUp(() {
InAppPurchaseStoreKitPlatform.registerPlatform();
iapStoreKitPlatform =
InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform;
fakeStoreKitPlatform.reset();
});
tearDown(() => fakeStoreKitPlatform.reset());
group('isAvailable', () {
test('true', () async {
expect(await iapStoreKitPlatform.isAvailable(), isTrue);
});
});
group('query product list', () {
test('should get product list and correct invalid identifiers', () async {
final InAppPurchaseStoreKitPlatform connection =
InAppPurchaseStoreKitPlatform();
final ProductDetailsResponse response =
await connection.queryProductDetails(<String>{'123', '456', '789'});
final List<ProductDetails> products = response.productDetails;
expect(products.first.id, '123');
expect(products[1].id, '456');
expect(response.notFoundIDs, <String>['789']);
expect(response.error, isNull);
expect(response.productDetails.first.currencySymbol, r'$');
expect(response.productDetails[1].currencySymbol, 'EUR');
});
test(
'if query products throws error, should get error object in the response',
() async {
fakeStoreKitPlatform.queryProductException = PlatformException(
code: 'error_code',
message: 'error_message',
details: <Object, Object>{'info': 'error_info'});
final InAppPurchaseStoreKitPlatform connection =
InAppPurchaseStoreKitPlatform();
final ProductDetailsResponse response =
await connection.queryProductDetails(<String>{'123', '456', '789'});
expect(response.productDetails, <ProductDetails>[]);
expect(response.notFoundIDs, <String>['123', '456', '789']);
expect(response.error, isNotNull);
expect(response.error!.source, kIAPSource);
expect(response.error!.code, 'error_code');
expect(response.error!.message, 'error_message');
expect(response.error!.details, <Object, Object>{'info': 'error_info'});
});
});
group('restore purchases', () {
test('should emit restored transactions on purchase stream', () async {
fakeStoreKitPlatform.transactionList.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactionList.insert(
1, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList.first.status == PurchaseStatus.restored) {
subscription.cancel();
completer.complete(purchaseDetailsList);
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
expect(details.length, 2);
for (int i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactionList[i];
final PurchaseDetails actual = details[i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(actual.status, PurchaseStatus.restored);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test(
'should emit empty transaction list on purchase stream when there is nothing to restore',
() async {
fakeStoreKitPlatform.testRestoredTransactionsNull = true;
final Completer<List<PurchaseDetails>?> completer =
Completer<List<PurchaseDetails>?>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
expect(purchaseDetailsList.isEmpty, true);
subscription.cancel();
completer.complete();
});
await iapStoreKitPlatform.restorePurchases();
await completer.future;
});
test('should not block transaction updates', () async {
fakeStoreKitPlatform.transactionList.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactionList.insert(
1, fakeStoreKitPlatform.createPurchasedTransaction('foo', 'bar'));
fakeStoreKitPlatform.transactionList.insert(
2, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList[1].status == PurchaseStatus.purchased) {
completer.complete(purchaseDetailsList);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
expect(details.length, 3);
for (int i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactionList[i];
final PurchaseDetails actual = details[i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(
actual.status,
const SKTransactionStatusConverter()
.toPurchaseStatus(expected.transactionState, expected.error),
);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test(
'should emit empty transaction if transactions array does not contain a transaction with PurchaseStatus.restored status.',
() async {
fakeStoreKitPlatform.transactionList.insert(
0, fakeStoreKitPlatform.createPurchasedTransaction('foo', 'bar'));
final Completer<List<List<PurchaseDetails>>> completer =
Completer<List<List<PurchaseDetails>>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
final List<List<PurchaseDetails>> purchaseDetails =
<List<PurchaseDetails>>[];
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
purchaseDetails.add(purchaseDetailsList);
if (purchaseDetails.length == 2) {
completer.complete(purchaseDetails);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<List<PurchaseDetails>> details = await completer.future;
expect(details.length, 2);
expect(details[0], <List<PurchaseDetails>>[]);
for (int i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactionList[i];
final PurchaseDetails actual = details[1][i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(
actual.status,
const SKTransactionStatusConverter()
.toPurchaseStatus(expected.transactionState, expected.error),
);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test('receipt error should populate null to verificationData.data',
() async {
fakeStoreKitPlatform.transactionList.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactionList.insert(
1, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
fakeStoreKitPlatform.receiptData = null;
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList.first.status == PurchaseStatus.restored) {
completer.complete(purchaseDetailsList);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
for (final PurchaseDetails purchase in details) {
expect(purchase.verificationData.localVerificationData, isEmpty);
expect(purchase.verificationData.serverVerificationData, isEmpty);
}
});
test('test restore error', () {
fakeStoreKitPlatform.testRestoredError = const SKError(
code: 123,
domain: 'error_test',
userInfo: <String, dynamic>{'message': 'errorMessage'});
expect(
() => iapStoreKitPlatform.restorePurchases(),
throwsA(
isA<SKError>()
.having((SKError error) => error.code, 'code', 123)
.having((SKError error) => error.domain, 'domain', 'error_test')
.having((SKError error) => error.userInfo, 'userInfo',
<String, dynamic>{'message': 'errorMessage'}),
));
});
});
group('make payment', () {
test(
'buying non consumable, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
});
test(
'buying consumable, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
});
test('buying consumable, should throw when autoConsume is false', () async {
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
expect(
() => iapStoreKitPlatform.buyConsumable(
purchaseParam: purchaseParam, autoConsume: false),
throwsA(isInstanceOf<AssertionError>()));
});
test('should get failed purchase status', () async {
fakeStoreKitPlatform.testTransactionFail = true;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<IAPError> completer = Completer<IAPError>();
late IAPError error;
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.error) {
error = purchaseDetails.error!;
completer.complete(error);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final IAPError completerError = await completer.future;
expect(completerError.code, 'purchase_error');
expect(completerError.source, kIAPSource);
expect(completerError.message, 'ios_domain');
expect(completerError.details,
<Object, Object>{'message': 'an error message'});
});
test(
'should get canceled purchase status when error code is SKErrorPaymentCancelled',
() async {
fakeStoreKitPlatform.testTransactionCancel = 2;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<PurchaseStatus> completer = Completer<PurchaseStatus>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.canceled) {
completer.complete(purchaseDetails.status);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final PurchaseStatus purchaseStatus = await completer.future;
expect(purchaseStatus, PurchaseStatus.canceled);
});
test(
'should get canceled purchase status when error code is SKErrorOverlayCancelled',
() async {
fakeStoreKitPlatform.testTransactionCancel = 15;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<PurchaseStatus> completer = Completer<PurchaseStatus>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.canceled) {
completer.complete(purchaseDetails.status);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final PurchaseStatus purchaseStatus = await completer.future;
expect(purchaseStatus, PurchaseStatus.canceled);
});
test(
'buying non consumable, should be able to purchase multiple quantity of one product',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStoreProductDetails productDetails =
AppStoreProductDetails.fromSKProduct(dummyProductWrapper);
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails: productDetails,
quantity: 5,
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
await completer.future;
expect(
fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5);
});
test(
'buying consumable, should be able to purchase multiple quantity of one product',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStoreProductDetails productDetails =
AppStoreProductDetails.fromSKProduct(dummyProductWrapper);
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails: productDetails,
quantity: 5,
applicationUserName: 'appName');
await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam);
await completer.future;
expect(
fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5);
});
test(
'buying non consumable with discount, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'userWithDiscount',
discount: dummyPaymentDiscountWrapper,
);
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
expect(fakeStoreKitPlatform.discountReceived,
dummyPaymentDiscountWrapper.toMap());
});
});
group('complete purchase', () {
test('should complete purchase', () async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
expect(fakeStoreKitPlatform.finishedTransactions.length, 1);
});
});
group('purchase stream', () {
test('Should only have active queue when purchaseStream has listeners', () {
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
expect(fakeStoreKitPlatform.queueIsActive, false);
final StreamSubscription<List<PurchaseDetails>> subscription1 =
stream.listen((List<PurchaseDetails> event) {});
expect(fakeStoreKitPlatform.queueIsActive, true);
final StreamSubscription<List<PurchaseDetails>> subscription2 =
stream.listen((List<PurchaseDetails> event) {});
expect(fakeStoreKitPlatform.queueIsActive, true);
subscription1.cancel();
expect(fakeStoreKitPlatform.queueIsActive, true);
subscription2.cancel();
expect(fakeStoreKitPlatform.queueIsActive, false);
});
});
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart",
"repo_id": "packages",
"token_count": 9035
} | 1,061 |
# ios_platform_images_example
Demonstrates how to use the ios_platform_images plugin.
| packages/packages/ios_platform_images/example/README.md/0 | {
"file_path": "packages/packages/ios_platform_images/example/README.md",
"repo_id": "packages",
"token_count": 27
} | 1,062 |
// 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 ios_platform_images;
@import XCTest;
// The tests test the UIImage extension which is a public API intended for use from native code
// outside of the plugin (see package README). Any change that requires changing existing tests
// in this file (unless it's just to reflect changes to the test assets) is a BREAKING CHANGE for
// the package.
@interface UIImageExtensionTests : XCTestCase
@end
@implementation UIImageExtensionTests
- (void)testMultiResolutionImageUsesBest {
UIImage *image = [UIImage flutterImageWithName:@"assets/multisize.png"];
XCTAssertNotNil(image);
const double height1x = 125; // The height of assets/multisize.png.
const double height2x = 250; // The height of assets/2.0x/multisize.png.
// Loading assets should get the best available asset for the screen scale when resolution-aware
// assets are available (and the example app has 1x and 2x for this asset). See
// https://docs.flutter.dev/ui/assets/assets-and-images#resolution-aware
if (UIScreen.mainScreen.scale > 1.0) {
XCTAssertEqualWithAccuracy(image.size.height, height2x, 0.00001);
} else {
XCTAssertEqualWithAccuracy(image.size.height, height1x, 0.00001);
}
}
- (void)testSingleResolutionFindsImage {
// When there is no resolution-aware asset, the main asset should be used.
UIImage *image = [UIImage flutterImageWithName:@"assets/monosize.png"];
XCTAssertNotNil(image);
}
- (void)testMissingImageReturnsNil {
UIImage *image = [UIImage flutterImageWithName:@"assets/no_such_image.png"];
XCTAssertNil(image);
}
@end
| packages/packages/ios_platform_images/example/ios/RunnerTests/UIImage+ios_platform_imagesTests.m/0 | {
"file_path": "packages/packages/ios_platform_images/example/ios/RunnerTests/UIImage+ios_platform_imagesTests.m",
"repo_id": "packages",
"token_count": 547
} | 1,063 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:ios_platform_images/ios_platform_images.dart';
import 'package:ios_platform_images/src/messages.g.dart';
void main() {
late FakePlatformImagesApi fakeApi;
setUp(() {
fakeApi = FakePlatformImagesApi();
setPlatformImageHostApi(fakeApi);
});
test('resolveURL passes arguments', () async {
const String name = 'a name';
const String extension = '.extension';
await IosPlatformImages.resolveURL(name, extension: extension);
expect(fakeApi.passedName, name);
expect(fakeApi.passedExtension, extension);
});
test('resolveURL returns null', () async {
expect(await IosPlatformImages.resolveURL('foobar'), null);
});
test('resolveURL returns result', () async {
const String result = 'a result';
fakeApi.resolutionResult = result;
expect(await IosPlatformImages.resolveURL('foobar'), result);
});
test('loadImage passes argument', () async {
fakeApi.loadResult = PlatformImageData(data: Uint8List(1), scale: 1.0);
const String name = 'a name';
IosPlatformImages.load(name);
expect(fakeApi.passedName, name);
});
}
class FakePlatformImagesApi implements PlatformImagesApi {
String? passedName;
String? passedExtension;
String? resolutionResult;
PlatformImageData? loadResult;
@override
Future<PlatformImageData?> loadImage(String name) async {
passedName = name;
return loadResult;
}
@override
Future<String?> resolveUrl(String name, String? extension) async {
passedName = name;
passedExtension = extension;
return resolutionResult;
}
}
| packages/packages/ios_platform_images/test/ios_platform_images_test.dart/0 | {
"file_path": "packages/packages/ios_platform_images/test/ios_platform_images_test.dart",
"repo_id": "packages",
"token_count": 596
} | 1,064 |
// 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 "FLALocalAuthPlugin.h"
#import "FLALocalAuthPlugin_Test.h"
#import <LocalAuthentication/LocalAuthentication.h>
typedef void (^FLADAuthCompletion)(FLADAuthResultDetails *_Nullable, FlutterError *_Nullable);
/// A default context factory that wraps standard LAContext allocation.
@interface FLADefaultAuthContextFactory : NSObject <FLADAuthContextFactory>
@end
@implementation FLADefaultAuthContextFactory
- (LAContext *)createAuthContext {
return [[LAContext alloc] init];
}
@end
#pragma mark -
/// A data container for sticky auth state.
@interface FLAStickyAuthState : NSObject
@property(nonatomic, strong, nonnull) FLADAuthOptions *options;
@property(nonatomic, strong, nonnull) FLADAuthStrings *strings;
@property(nonatomic, copy, nonnull) FLADAuthCompletion resultHandler;
- (instancetype)initWithOptions:(nonnull FLADAuthOptions *)options
strings:(nonnull FLADAuthStrings *)strings
resultHandler:(nonnull FLADAuthCompletion)resultHandler;
@end
@implementation FLAStickyAuthState
- (instancetype)initWithOptions:(nonnull FLADAuthOptions *)options
strings:(nonnull FLADAuthStrings *)strings
resultHandler:(nonnull FLADAuthCompletion)resultHandler {
self = [super init];
if (self) {
_options = options;
_strings = strings;
_resultHandler = resultHandler;
}
return self;
}
@end
#pragma mark -
@interface FLALocalAuthPlugin ()
@property(nonatomic, strong, nullable) FLAStickyAuthState *lastCallState;
@property(nonatomic, strong) NSObject<FLADAuthContextFactory> *authContextFactory;
@end
@implementation FLALocalAuthPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FLALocalAuthPlugin *instance = [[FLALocalAuthPlugin alloc] init];
[registrar addApplicationDelegate:instance];
SetUpFLADLocalAuthApi([registrar messenger], instance);
}
- (instancetype)init {
return [self initWithContextFactory:[[FLADefaultAuthContextFactory alloc] init]];
}
- (instancetype)initWithContextFactory:(NSObject<FLADAuthContextFactory> *)factory {
self = [super init];
if (self) {
_authContextFactory = factory;
}
return self;
}
#pragma mark FLADLocalAuthApi
- (void)authenticateWithOptions:(nonnull FLADAuthOptions *)options
strings:(nonnull FLADAuthStrings *)strings
completion:(nonnull void (^)(FLADAuthResultDetails *_Nullable,
FlutterError *_Nullable))completion {
LAContext *context = [self.authContextFactory createAuthContext];
NSError *authError = nil;
self.lastCallState = nil;
context.localizedFallbackTitle = strings.localizedFallbackTitle;
LAPolicy policy = options.biometricOnly ? LAPolicyDeviceOwnerAuthenticationWithBiometrics
: LAPolicyDeviceOwnerAuthentication;
if ([context canEvaluatePolicy:policy error:&authError]) {
[context evaluatePolicy:policy
localizedReason:strings.reason
reply:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self handleAuthReplyWithSuccess:success
error:error
options:options
strings:strings
completion:completion];
});
}];
} else {
[self handleError:authError withOptions:options strings:strings completion:completion];
}
}
- (nullable NSNumber *)deviceCanSupportBiometricsWithError:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
LAContext *context = [self.authContextFactory createAuthContext];
NSError *authError = nil;
// Check if authentication with biometrics is possible.
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
error:&authError]) {
if (authError == nil) {
return @YES;
}
}
// If not, check if it is because no biometrics are enrolled (but still present).
if (authError != nil) {
if (authError.code == LAErrorBiometryNotEnrolled) {
return @YES;
}
}
return @NO;
}
- (nullable NSArray<FLADAuthBiometricWrapper *> *)getEnrolledBiometricsWithError:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
LAContext *context = [self.authContextFactory createAuthContext];
NSError *authError = nil;
NSMutableArray<FLADAuthBiometricWrapper *> *biometrics = [[NSMutableArray alloc] init];
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
error:&authError]) {
if (authError == nil) {
if (context.biometryType == LABiometryTypeFaceID) {
[biometrics addObject:[FLADAuthBiometricWrapper makeWithValue:FLADAuthBiometricFace]];
} else if (context.biometryType == LABiometryTypeTouchID) {
[biometrics
addObject:[FLADAuthBiometricWrapper makeWithValue:FLADAuthBiometricFingerprint]];
}
}
}
return biometrics;
}
- (nullable NSNumber *)isDeviceSupportedWithError:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
LAContext *context = [self.authContextFactory createAuthContext];
return @([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:NULL]);
}
#pragma mark Private Methods
- (void)showAlertWithMessage:(NSString *)message
dismissButtonTitle:(NSString *)dismissButtonTitle
openSettingsButtonTitle:(NSString *)openSettingsButtonTitle
completion:(FLADAuthCompletion)completion {
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:@""
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:dismissButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[self handleSucceeded:NO
withCompletion:completion];
}];
[alert addAction:defaultAction];
if (openSettingsButtonTitle != nil) {
UIAlertAction *additionalAction = [UIAlertAction
actionWithTitle:openSettingsButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:NULL];
[self handleSucceeded:NO withCompletion:completion];
}];
[alert addAction:additionalAction];
}
[[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alert
animated:YES
completion:nil];
}
- (void)handleAuthReplyWithSuccess:(BOOL)success
error:(NSError *)error
options:(FLADAuthOptions *)options
strings:(FLADAuthStrings *)strings
completion:(nonnull FLADAuthCompletion)completion {
NSAssert([NSThread isMainThread], @"Response handling must be done on the main thread.");
if (success) {
[self handleSucceeded:YES withCompletion:completion];
} else {
switch (error.code) {
case LAErrorBiometryNotAvailable:
case LAErrorBiometryNotEnrolled:
case LAErrorBiometryLockout:
case LAErrorUserFallback:
case LAErrorPasscodeNotSet:
case LAErrorAuthenticationFailed:
[self handleError:error withOptions:options strings:strings completion:completion];
return;
case LAErrorSystemCancel:
if (options.sticky) {
_lastCallState = [[FLAStickyAuthState alloc] initWithOptions:options
strings:strings
resultHandler:completion];
} else {
[self handleSucceeded:NO withCompletion:completion];
}
return;
}
[self handleError:error withOptions:options strings:strings completion:completion];
}
}
- (void)handleSucceeded:(BOOL)succeeded withCompletion:(nonnull FLADAuthCompletion)completion {
completion([FLADAuthResultDetails
makeWithResult:(succeeded ? FLADAuthResultSuccess : FLADAuthResultFailure)
errorMessage:nil
errorDetails:nil],
nil);
}
- (void)handleError:(NSError *)authError
withOptions:(FLADAuthOptions *)options
strings:(FLADAuthStrings *)strings
completion:(nonnull FLADAuthCompletion)completion {
FLADAuthResult result = FLADAuthResultErrorNotAvailable;
switch (authError.code) {
case LAErrorPasscodeNotSet:
case LAErrorBiometryNotEnrolled:
if (options.useErrorDialogs) {
[self showAlertWithMessage:strings.goToSettingsDescription
dismissButtonTitle:strings.cancelButton
openSettingsButtonTitle:strings.goToSettingsButton
completion:completion];
return;
}
result = authError.code == LAErrorPasscodeNotSet ? FLADAuthResultErrorPasscodeNotSet
: FLADAuthResultErrorNotEnrolled;
break;
case LAErrorBiometryLockout:
[self showAlertWithMessage:strings.lockOut
dismissButtonTitle:strings.cancelButton
openSettingsButtonTitle:nil
completion:completion];
return;
}
completion([FLADAuthResultDetails makeWithResult:result
errorMessage:authError.localizedDescription
errorDetails:authError.domain],
nil);
}
#pragma mark - AppDelegate
- (void)applicationDidBecomeActive:(UIApplication *)application {
if (self.lastCallState != nil) {
[self authenticateWithOptions:_lastCallState.options
strings:_lastCallState.strings
completion:_lastCallState.resultHandler];
}
}
@end
| packages/packages/local_auth/local_auth_darwin/darwin/Classes/FLALocalAuthPlugin.m/0 | {
"file_path": "packages/packages/local_auth/local_auth_darwin/darwin/Classes/FLALocalAuthPlugin.m",
"repo_id": "packages",
"token_count": 4815
} | 1,065 |
name: local_auth_darwin
description: iOS implementation of the local_auth plugin.
repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_darwin
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
version: 1.2.2
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: local_auth
platforms:
ios:
pluginClass: FLALocalAuthPlugin
dartPluginClass: LocalAuthDarwin
sharedDarwinSource: true
dependencies:
flutter:
sdk: flutter
intl: ">=0.17.0 <0.20.0"
local_auth_platform_interface: ^1.0.1
dev_dependencies:
build_runner: ^2.3.3
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^13.0.0
topics:
- authentication
- biometrics
- local-auth
| packages/packages/local_auth/local_auth_darwin/pubspec.yaml/0 | {
"file_path": "packages/packages/local_auth/local_auth_darwin/pubspec.yaml",
"repo_id": "packages",
"token_count": 350
} | 1,066 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 1.0.10
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 1.0.9
* Updates to Pigeon 10.0.
* Fixes stale ignore: prefer_const_constructors.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 1.0.8
* Sets a cmake_policy compatibility version to fix build warnings.
## 1.0.7
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 1.0.6
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 1.0.5
* Switches internal implementation to Pigeon.
## 1.0.4
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 1.0.3
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 1.0.2
* Updates `local_auth_platform_interface` constraint to the correct minimum
version.
## 1.0.1
* Updates references to the obsolete master branch.
## 1.0.0
* Initial release of Windows support.
| packages/packages/local_auth/local_auth_windows/CHANGELOG.md/0 | {
"file_path": "packages/packages/local_auth/local_auth_windows/CHANGELOG.md",
"repo_id": "packages",
"token_count": 360
} | 1,067 |
// 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_test/flutter_test.dart';
import 'package:local_auth_windows/local_auth_windows.dart';
import 'package:local_auth_windows/src/messages.g.dart';
void main() {
group('authenticate', () {
late _FakeLocalAuthApi api;
late LocalAuthWindows plugin;
setUp(() {
api = _FakeLocalAuthApi();
plugin = LocalAuthWindows(api: api);
});
test('authenticate handles success', () async {
api.returnValue = true;
final bool result = await plugin.authenticate(
authMessages: <AuthMessages>[const WindowsAuthMessages()],
localizedReason: 'My localized reason');
expect(result, true);
expect(api.passedReason, 'My localized reason');
});
test('authenticate handles failure', () async {
api.returnValue = false;
final bool result = await plugin.authenticate(
authMessages: <AuthMessages>[const WindowsAuthMessages()],
localizedReason: 'My localized reason');
expect(result, false);
expect(api.passedReason, 'My localized reason');
});
test('authenticate throws for biometricOnly', () async {
expect(
plugin.authenticate(
authMessages: <AuthMessages>[const WindowsAuthMessages()],
localizedReason: 'My localized reason',
options: const AuthenticationOptions(biometricOnly: true)),
throwsA(isUnsupportedError));
});
test('isDeviceSupported handles supported', () async {
api.returnValue = true;
final bool result = await plugin.isDeviceSupported();
expect(result, true);
});
test('isDeviceSupported handles unsupported', () async {
api.returnValue = false;
final bool result = await plugin.isDeviceSupported();
expect(result, false);
});
test('deviceSupportsBiometrics handles supported', () async {
api.returnValue = true;
final bool result = await plugin.deviceSupportsBiometrics();
expect(result, true);
});
test('deviceSupportsBiometrics handles unsupported', () async {
api.returnValue = false;
final bool result = await plugin.deviceSupportsBiometrics();
expect(result, false);
});
test('getEnrolledBiometrics returns expected values when supported',
() async {
api.returnValue = true;
final List<BiometricType> result = await plugin.getEnrolledBiometrics();
expect(result, <BiometricType>[BiometricType.weak, BiometricType.strong]);
});
test('getEnrolledBiometrics returns nothing when unsupported', () async {
api.returnValue = false;
final List<BiometricType> result = await plugin.getEnrolledBiometrics();
expect(result, isEmpty);
});
test('stopAuthentication returns false', () async {
final bool result = await plugin.stopAuthentication();
expect(result, false);
});
});
}
class _FakeLocalAuthApi implements LocalAuthApi {
/// The return value for [isDeviceSupported] and [authenticate].
bool returnValue = false;
/// The argument that was passed to [authenticate].
String? passedReason;
@override
Future<bool> authenticate(String localizedReason) async {
passedReason = localizedReason;
return returnValue;
}
@override
Future<bool> isDeviceSupported() async {
return returnValue;
}
}
| packages/packages/local_auth/local_auth_windows/test/local_auth_test.dart/0 | {
"file_path": "packages/packages/local_auth/local_auth_windows/test/local_auth_test.dart",
"repo_id": "packages",
"token_count": 1191
} | 1,068 |
// 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:convert';
import 'dart:io';
import 'common.dart';
// This will be used in many of our unit tests.
void expectSetMatch<T>(Iterable<T> actual, Iterable<T> expected) {
expect(Set<T>.from(actual), equals(Set<T>.from(expected)));
}
// May return null if the credentials file doesn't exist.
Map<String, dynamic>? getTestGcpCredentialsJson() {
final File f = File('secret/test_gcp_credentials.json');
if (!f.existsSync()) {
return null;
}
return jsonDecode(File('secret/test_gcp_credentials.json').readAsStringSync())
as Map<String, dynamic>?;
}
| packages/packages/metrics_center/test/utility.dart/0 | {
"file_path": "packages/packages/metrics_center/test/utility.dart",
"repo_id": "packages",
"token_count": 249
} | 1,069 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:multicast_dns/multicast_dns.dart';
import 'package:test/fake.dart';
import 'package:test/test.dart';
void main() {
test('Can inject datagram socket factory and configure mdns port', () async {
late int lastPort;
final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket();
final MDnsClient client = MDnsClient(rawDatagramSocketFactory:
(dynamic host, int port,
{bool reuseAddress = true,
bool reusePort = true,
int ttl = 1}) async {
lastPort = port;
return datagramSocket;
});
await client.start(
mDnsPort: 1234,
interfacesFactory: (InternetAddressType type) async =>
<NetworkInterface>[]);
expect(lastPort, 1234);
});
test('Closes IPv4 sockets', () async {
final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket();
final MDnsClient client = MDnsClient(rawDatagramSocketFactory:
(dynamic host, int port,
{bool reuseAddress = true,
bool reusePort = true,
int ttl = 1}) async {
return datagramSocket;
});
await client.start(
mDnsPort: 1234,
interfacesFactory: (InternetAddressType type) async =>
<NetworkInterface>[]);
expect(datagramSocket.closed, false);
client.stop();
expect(datagramSocket.closed, true);
});
test('Closes IPv6 sockets', () async {
final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket();
datagramSocket.address = InternetAddress.anyIPv6;
final MDnsClient client = MDnsClient(rawDatagramSocketFactory:
(dynamic host, int port,
{bool reuseAddress = true,
bool reusePort = true,
int ttl = 1}) async {
return datagramSocket;
});
await client.start(
mDnsPort: 1234,
interfacesFactory: (InternetAddressType type) async =>
<NetworkInterface>[]);
expect(datagramSocket.closed, false);
client.stop();
expect(datagramSocket.closed, true);
});
test('start() is idempotent', () async {
final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket();
datagramSocket.address = InternetAddress.anyIPv4;
final MDnsClient client = MDnsClient(rawDatagramSocketFactory:
(dynamic host, int port,
{bool reuseAddress = true,
bool reusePort = true,
int ttl = 1}) async {
return datagramSocket;
});
await client.start(
interfacesFactory: (InternetAddressType type) async =>
<NetworkInterface>[]);
await client.start();
await client.lookup(ResourceRecordQuery.serverPointer('_')).toList();
});
}
class FakeRawDatagramSocket extends Fake implements RawDatagramSocket {
@override
InternetAddress address = InternetAddress.anyIPv4;
@override
StreamSubscription<RawSocketEvent> listen(
void Function(RawSocketEvent event)? onData,
{Function? onError,
void Function()? onDone,
bool? cancelOnError}) {
return const Stream<RawSocketEvent>.empty().listen(onData,
onError: onError, cancelOnError: cancelOnError, onDone: onDone);
}
bool closed = false;
@override
void close() {
closed = true;
}
@override
int send(List<int> buffer, InternetAddress address, int port) {
return buffer.length;
}
}
| packages/packages/multicast_dns/test/client_test.dart/0 | {
"file_path": "packages/packages/multicast_dns/test/client_test.dart",
"repo_id": "packages",
"token_count": 1332
} | 1,070 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="image_colors"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in @style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| packages/packages/palette_generator/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/palette_generator/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 740
} | 1,071 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
namespace 'io.flutter.plugins.pathproviderexample'
compileSdk flutter.compileSdkVersion
defaultConfig {
applicationId "io.flutter.plugins.pathproviderexample"
minSdkVersion flutter.minSdkVersion
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
lint {
disable 'InvalidPackage'
}
}
flutter {
source '../..'
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
| packages/packages/path_provider/path_provider/example/android/app/build.gradle/0 | {
"file_path": "packages/packages/path_provider/path_provider/example/android/app/build.gradle",
"repo_id": "packages",
"token_count": 739
} | 1,072 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// Runs example code for README.md.
Future<List<Directory?>> readmeSnippets() async {
// #docregion Example
final Directory tempDir = await getTemporaryDirectory();
final Directory appDocumentsDir = await getApplicationDocumentsDirectory();
final Directory? downloadsDir = await getDownloadsDirectory();
// #enddocregion Example
return <Directory?>[tempDir, appDocumentsDir, downloadsDir];
}
| packages/packages/path_provider/path_provider/example/lib/readme_excerpts.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider/example/lib/readme_excerpts.dart",
"repo_id": "packages",
"token_count": 172
} | 1,073 |
// 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 (v9.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package io.flutter.plugins.pathprovider;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.util.ArrayList;
import java.util.List;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})
public class Messages {
/** Error class for passing custom error details to Flutter via a thrown PlatformException. */
public static class FlutterError extends RuntimeException {
/** The error code. */
public final String code;
/** The error details. Must be a datatype supported by the api codec. */
public final Object details;
public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) {
super(message);
this.code = code;
this.details = details;
}
}
@NonNull
protected static ArrayList<Object> wrapError(@NonNull Throwable exception) {
ArrayList<Object> errorList = new ArrayList<Object>(3);
if (exception instanceof FlutterError) {
FlutterError error = (FlutterError) exception;
errorList.add(error.code);
errorList.add(error.getMessage());
errorList.add(error.details);
} else {
errorList.add(exception.toString());
errorList.add(exception.getClass().getSimpleName());
errorList.add(
"Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
}
return errorList;
}
public enum StorageDirectory {
ROOT(0),
MUSIC(1),
PODCASTS(2),
RINGTONES(3),
ALARMS(4),
NOTIFICATIONS(5),
PICTURES(6),
MOVIES(7),
DOWNLOADS(8),
DCIM(9),
DOCUMENTS(10);
final int index;
private StorageDirectory(final int index) {
this.index = index;
}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface PathProviderApi {
@Nullable
String getTemporaryPath();
@Nullable
String getApplicationSupportPath();
@Nullable
String getApplicationDocumentsPath();
@Nullable
String getApplicationCachePath();
@Nullable
String getExternalStoragePath();
@NonNull
List<String> getExternalCachePaths();
@NonNull
List<String> getExternalStoragePaths(@NonNull StorageDirectory directory);
/** The codec used by PathProviderApi. */
static @NonNull MessageCodec<Object> getCodec() {
return new StandardMessageCodec();
}
/**
* Sets up an instance of `PathProviderApi` to handle messages through the `binaryMessenger`.
*/
static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable PathProviderApi api) {
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getTemporaryPath",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getTemporaryPath();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getApplicationSupportPath",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getApplicationSupportPath();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getApplicationDocumentsPath",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getApplicationDocumentsPath();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getApplicationCachePath",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getApplicationCachePath();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getExternalStoragePath",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getExternalStoragePath();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getExternalCachePaths",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
List<String> output = api.getExternalCachePaths();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
StorageDirectory directoryArg =
args.get(0) == null ? null : StorageDirectory.values()[(int) args.get(0)];
try {
List<String> output = api.getExternalStoragePaths(directoryArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
}
| packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/Messages.java/0 | {
"file_path": "packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/Messages.java",
"repo_id": "packages",
"token_count": 4666
} | 1,074 |
// 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, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
enum DirectoryType {
applicationDocuments,
applicationSupport,
downloads,
library,
temp,
applicationCache,
}
class PathProviderApi {
/// Constructor for [PathProviderApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
PathProviderApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<String?> getDirectoryPath(DirectoryType arg_type) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getDirectoryPath', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_type.index]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<String?> getContainerPath(String arg_appGroupIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getContainerPath', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_appGroupIdentifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
}
| packages/packages/path_provider/path_provider_foundation/lib/messages.g.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_foundation/lib/messages.g.dart",
"repo_id": "packages",
"token_count": 1007
} | 1,075 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:xdg_directories/xdg_directories.dart' as xdg;
import 'get_application_id.dart';
/// The linux implementation of [PathProviderPlatform]
///
/// This class implements the `package:path_provider` functionality for Linux.
class PathProviderLinux extends PathProviderPlatform {
/// Constructs an instance of [PathProviderLinux]
PathProviderLinux() : _environment = Platform.environment;
/// Constructs an instance of [PathProviderLinux] with the given [environment]
@visibleForTesting
PathProviderLinux.private(
{Map<String, String> environment = const <String, String>{},
String? executableName,
String? applicationId})
: _environment = environment,
_executableName = executableName,
_applicationId = applicationId;
final Map<String, String> _environment;
String? _executableName;
String? _applicationId;
/// Registers this class as the default instance of [PathProviderPlatform]
static void registerWith() {
PathProviderPlatform.instance = PathProviderLinux();
}
@override
Future<String?> getTemporaryPath() {
final String environmentTmpDir = _environment['TMPDIR'] ?? '';
return Future<String?>.value(
environmentTmpDir.isEmpty ? '/tmp' : environmentTmpDir,
);
}
@override
Future<String?> getApplicationSupportPath() async {
final Directory directory =
Directory(path.join(xdg.dataHome.path, await _getId()));
if (directory.existsSync()) {
return directory.path;
}
// This plugin originally used the executable name as a directory.
// Use that if it exists for backwards compatibility.
final Directory legacyDirectory =
Directory(path.join(xdg.dataHome.path, await _getExecutableName()));
if (legacyDirectory.existsSync()) {
return legacyDirectory.path;
}
// Create the directory, because mobile implementations assume the directory exists.
await directory.create(recursive: true);
return directory.path;
}
@override
Future<String?> getApplicationDocumentsPath() {
return Future<String?>.value(xdg.getUserDirectory('DOCUMENTS')?.path);
}
@override
Future<String?> getApplicationCachePath() async {
final Directory directory =
Directory(path.join(xdg.cacheHome.path, await _getId()));
if (!directory.existsSync()) {
await directory.create(recursive: true);
}
return directory.path;
}
@override
Future<String?> getDownloadsPath() {
return Future<String?>.value(xdg.getUserDirectory('DOWNLOAD')?.path);
}
// Gets the name of this executable.
Future<String> _getExecutableName() async {
_executableName ??= path.basenameWithoutExtension(
await File('/proc/self/exe').resolveSymbolicLinks());
return _executableName!;
}
// Gets the unique ID for this application.
Future<String> _getId() async {
_applicationId ??= getApplicationId();
// If no application ID then fall back to using the executable name.
return _applicationId ?? await _getExecutableName();
}
}
| packages/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart",
"repo_id": "packages",
"token_count": 1066
} | 1,076 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.2.1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.2.0
* Adds getApplicationCachePath() for storing app-specific cache files.
## 2.1.7
* Adds compatibility with `win32` 5.x.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 2.1.6
* Adds compatibility with `win32` 4.x.
## 2.1.5
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 2.1.4
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.1.3
* Updates minimum Flutter version to 2.10.
* Adds compatibility with `package:win32` 3.x.
## 2.1.2
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.1.1
* Updates dependency version of `package:win32` to 2.1.0.
## 2.1.0
* Upgrades `package:ffi` dependency to 2.0.0.
* Added support for unicode encoded VERSIONINFO.
* Minor fixes for new analysis options.
## 2.0.6
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.5
* Removes dependency on `meta`.
## 2.0.4
* Removed obsolete `pluginClass: none` from pubpsec.
## 2.0.3
* Updated installation instructions in README.
## 2.0.2
* Add `implements` to pubspec.yaml.
* Add `registerWith()` to the Dart main class.
## 2.0.1
* Fix a crash when a known folder can't be located.
## 2.0.0
* Migrate to null safety
## 0.0.4+4
* Update Flutter SDK constraint.
## 0.0.4+3
* Remove unused `test` dependency.
* Update Dart SDK constraint in example.
## 0.0.4+2
* Check in windows/ directory for example/
## 0.0.4+1
* Add getPath to the stub, so that the analyzer won't complain about
fakes that override it.
* export 'folders.dart' rather than importing it, since it's intended to be
public.
## 0.0.4
* Move the actual implementation behind a conditional import, exporting
a stub for platforms that don't support FFI. Fixes web builds in
projects with transitive dependencies on path_provider.
## 0.0.3
* Add missing `pluginClass: none` for compatibilty with stable channel.
## 0.0.2
* README update for endorsement.
* Changed getApplicationSupportPath location.
* Removed getLibraryPath.
## 0.0.1+2
* The initial implementation of path_provider for Windows
* Implements getTemporaryPath, getApplicationSupportPath, getLibraryPath,
getApplicationDocumentsPath and getDownloadsPath.
| packages/packages/path_provider/path_provider_windows/CHANGELOG.md/0 | {
"file_path": "packages/packages/path_provider/path_provider_windows/CHANGELOG.md",
"repo_id": "packages",
"token_count": 847
} | 1,077 |
// 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:path_provider_platform_interface/path_provider_platform_interface.dart';
/// A stub implementation to satisfy compilation of multi-platform packages that
/// depend on path_provider_windows. This should never actually be created.
///
/// Notably, because path_provider needs to manually register
/// path_provider_windows, anything with a transitive dependency on
/// path_provider will also depend on path_provider_windows, not just at the
/// pubspec level but the code level.
class PathProviderWindows extends PathProviderPlatform {
/// Errors on attempted instantiation of the stub. It exists only to satisfy
/// compile-time dependencies, and should never actually be created.
PathProviderWindows() : assert(false);
/// Registers the Windows implementation.
static void registerWith() {
PathProviderPlatform.instance = PathProviderWindows();
}
/// Stub; see comment on VersionInfoQuerier.
VersionInfoQuerier versionInfoQuerier = VersionInfoQuerier();
/// Match PathProviderWindows so that the analyzer won't report invalid
/// overrides if tests provide fake PathProviderWindows implementations.
Future<String> getPath(String folderID) async => '';
}
/// Stub to satisfy the analyzer, which doesn't seem to handle conditional
/// exports correctly.
class VersionInfoQuerier {}
| packages/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_stub.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_stub.dart",
"repo_id": "packages",
"token_count": 362
} | 1,078 |
<?code-excerpt path-base="app"?>
# Pigeon Examples
The examples here will cover basic usage. For a more thorough set of examples,
check the [core_tests pigeon file](../pigeons/core_tests.dart) and
[platform test folder](../platform_tests/) ([shared_test_plugin_code](../platform_tests/shared_test_plugin_code/) and [alternate_language_test_plugin](../platform_tests/alternate_language_test_plugin/) especially).
## Invocation
Begin by configuring pigeon at the top of the `.dart` input file.
In actual use, you would include only the languages
needed for your project.
<?code-excerpt "pigeons/messages.dart (config)"?>
```dart
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartOptions: DartOptions(),
cppOptions: CppOptions(namespace: 'pigeon_example'),
cppHeaderOut: 'windows/runner/messages.g.h',
cppSourceOut: 'windows/runner/messages.g.cpp',
kotlinOut:
'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt',
kotlinOptions: KotlinOptions(),
javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java',
javaOptions: JavaOptions(),
swiftOut: 'ios/Runner/Messages.g.swift',
swiftOptions: SwiftOptions(),
objcHeaderOut: 'macos/Runner/messages.g.h',
objcSourceOut: 'macos/Runner/messages.g.m',
// Set this to a unique prefix for your plugin or application, per Objective-C naming conventions.
objcOptions: ObjcOptions(prefix: 'PGN'),
copyrightHeader: 'pigeons/copyright.txt',
dartPackageName: 'pigeon_example_package',
))
```
Then make a simple call to run pigeon on the Dart file containing your definitions.
```sh
flutter pub run pigeon --input path/to/input.dart
```
## HostApi Example
This example gives an overview of how to use Pigeon to call into the
host platform from Flutter.
### Dart input
This is the Pigeon file that describes the interface that will be used to call
from Flutter to the host-platform.
<?code-excerpt "pigeons/messages.dart (host-definitions)"?>
```dart
enum Code { one, two }
class MessageData {
MessageData({required this.code, required this.data});
String? name;
String? description;
Code code;
Map<String?, String?> data;
}
@HostApi()
abstract class ExampleHostApi {
String getHostLanguage();
// These annotations create more idiomatic naming of methods in Objc and Swift.
@ObjCSelector('addNumber:toNumber:')
@SwiftFunction('add(_:to:)')
int add(int a, int b);
@async
bool sendMessage(MessageData message);
}
```
### Dart
This is the code that will use the generated Dart code to make calls from Flutter to
the host platform.
<?code-excerpt "lib/main.dart (main-dart)"?>
```dart
final ExampleHostApi _api = ExampleHostApi();
/// Calls host method `add` with provided arguments.
Future<int> add(int a, int b) async {
try {
return await _api.add(a, b);
} catch (e) {
// handle error.
return 0;
}
}
/// Sends message through host api using `MessageData` class
/// and api `sendMessage` method.
Future<bool> sendMessage(String messageText) {
final MessageData message = MessageData(
code: Code.one,
data: <String?, String?>{'header': 'this is a header'},
description: 'uri text',
);
try {
return _api.sendMessage(message);
} catch (e) {
// handle error.
return Future<bool>(() => true);
}
}
```
### Swift
This is the code that will use the generated Swift code to receive calls from Flutter.
packages/pigeon/example/app/ios/Runner/AppDelegate.swift
<?code-excerpt "ios/Runner/AppDelegate.swift (swift-class)"?>
```swift
// This extension of Error is required to do use FlutterError in any Swift code.
extension FlutterError: Error {}
private class PigeonApiImplementation: ExampleHostApi {
func getHostLanguage() throws -> String {
return "Swift"
}
func add(_ a: Int64, to b: Int64) throws -> Int64 {
if a < 0 || b < 0 {
throw FlutterError(code: "code", message: "message", details: "details")
}
return a + b
}
func sendMessage(message: MessageData, completion: @escaping (Result<Bool, Error>) -> Void) {
if message.code == Code.one {
completion(.failure(FlutterError(code: "code", message: "message", details: "details")))
return
}
completion(.success(true))
}
}
```
### Kotlin
<?code-excerpt "android/app/src/main/kotlin/dev/flutter/pigeon_example_app/MainActivity.kt (kotlin-class)"?>
```kotlin
private class PigeonApiImplementation : ExampleHostApi {
override fun getHostLanguage(): String {
return "Kotlin"
}
override fun add(a: Long, b: Long): Long {
if (a < 0L || b < 0L) {
throw FlutterError("code", "message", "details")
}
return a + b
}
override fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit) {
if (message.code == Code.ONE) {
callback(Result.failure(FlutterError("code", "message", "details")))
return
}
callback(Result.success(true))
}
}
```
### C++
<?code-excerpt "windows/runner/flutter_window.cpp (cpp-class)"?>
```c++
class PigeonApiImplementation : public ExampleHostApi {
public:
PigeonApiImplementation() {}
virtual ~PigeonApiImplementation() {}
ErrorOr<std::string> GetHostLanguage() override { return "C++"; }
ErrorOr<int64_t> Add(int64_t a, int64_t b) {
if (a < 0 || b < 0) {
return FlutterError("code", "message", "details");
}
return a + b;
}
void SendMessage(const MessageData& message,
std::function<void(ErrorOr<bool> reply)> result) {
if (message.code == Code.one) {
result(FlutterError("code", "message", "details"));
return;
}
result(true);
}
};
```
## FlutterApi Example
This example gives an overview of how to use Pigeon to call into the Flutter
app from the host platform.
### Dart input
<?code-excerpt "pigeons/messages.dart (flutter-definitions)"?>
```dart
@FlutterApi()
abstract class MessageFlutterApi {
String flutterMethod(String? aString);
}
```
### Dart
This is the code that will use the generated Dart code to handle calls made to
Flutter from the host platform.
<?code-excerpt "lib/main.dart (main-dart-flutter)"?>
```dart
class _ExampleFlutterApi implements MessageFlutterApi {
@override
String flutterMethod(String? aString) {
return aString ?? '';
}
}
// ···
MessageFlutterApi.setup(_ExampleFlutterApi());
```
### Swift
<?code-excerpt "ios/Runner/AppDelegate.swift (swift-class-flutter)"?>
```swift
private class PigeonFlutterApi {
var flutterAPI: MessageFlutterApi
init(binaryMessenger: FlutterBinaryMessenger) {
flutterAPI = MessageFlutterApi(binaryMessenger: binaryMessenger)
}
func callFlutterMethod(
aString aStringArg: String?, completion: @escaping (Result<String, Error>) -> Void
) {
flutterAPI.flutterMethod(aString: aStringArg) {
completion(.success($0))
}
}
}
```
### Kotlin
<?code-excerpt "android/app/src/main/kotlin/dev/flutter/pigeon_example_app/MainActivity.kt (kotlin-class-flutter)"?>
```kotlin
private class PigeonFlutterApi {
var flutterApi: MessageFlutterApi? = null
constructor(binding: FlutterPlugin.FlutterPluginBinding) {
flutterApi = MessageFlutterApi(binding.getBinaryMessenger())
}
fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) {
flutterApi!!.flutterMethod(aString) { echo -> callback(Result.success(echo)) }
}
}
```
### C++
<?code-excerpt "windows/runner/flutter_window.cpp (cpp-method-flutter)"?>
```c++
void TestPlugin::CallFlutterMethod(
String aString, std::function<void(ErrorOr<int64_t> reply)> result) {
MessageFlutterApi->FlutterMethod(
aString, [result](String echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
```
## Swift / Kotlin Plugin Example
A downloadable example of using Pigeon to create a Flutter Plugin with Swift and
Kotlin can be found at
[gaaclarke/flutter_plugin_example](https://github.com/gaaclarke/pigeon_plugin_example).
## Swift / Kotlin Add-to-app Example
A full example of using Pigeon for add-to-app with Swift on iOS can be found at
[samples/add_to_app/books](https://github.com/flutter/samples/tree/master/add_to_app/books).
## Video player plugin
A full real-world example can also be found in the
[video_player plugin](https://github.com/flutter/packages/tree/main/packages/video_player).
| packages/packages/pigeon/example/README.md/0 | {
"file_path": "packages/packages/pigeon/example/README.md",
"repo_id": "packages",
"token_count": 2921
} | 1,079 |
// 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, do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger;
@protocol FlutterMessageCodec;
@class FlutterError;
@class FlutterStandardTypedData;
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, PGNCode) {
PGNCodeOne = 0,
PGNCodeTwo = 1,
};
/// Wrapper for PGNCode to allow for nullability.
@interface PGNCodeBox : NSObject
@property(nonatomic, assign) PGNCode value;
- (instancetype)initWithValue:(PGNCode)value;
@end
@class PGNMessageData;
@interface PGNMessageData : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithName:(nullable NSString *)name
description:(nullable NSString *)description
code:(PGNCode)code
data:(NSDictionary<NSString *, NSString *> *)data;
@property(nonatomic, copy, nullable) NSString *name;
@property(nonatomic, copy, nullable) NSString *description;
@property(nonatomic, assign) PGNCode code;
@property(nonatomic, copy) NSDictionary<NSString *, NSString *> *data;
@end
/// The codec used by PGNExampleHostApi.
NSObject<FlutterMessageCodec> *PGNExampleHostApiGetCodec(void);
@protocol PGNExampleHostApi
/// @return `nil` only when `error != nil`.
- (nullable NSString *)getHostLanguageWithError:(FlutterError *_Nullable *_Nonnull)error;
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)addNumber:(NSInteger)a
toNumber:(NSInteger)b
error:(FlutterError *_Nullable *_Nonnull)error;
- (void)sendMessageMessage:(PGNMessageData *)message
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
@end
extern void SetUpPGNExampleHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<PGNExampleHostApi> *_Nullable api);
/// The codec used by PGNMessageFlutterApi.
NSObject<FlutterMessageCodec> *PGNMessageFlutterApiGetCodec(void);
@interface PGNMessageFlutterApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
- (void)flutterMethodAString:(nullable NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
@end
NS_ASSUME_NONNULL_END
| packages/packages/pigeon/example/app/macos/Runner/messages.g.h/0 | {
"file_path": "packages/packages/pigeon/example/app/macos/Runner/messages.g.h",
"repo_id": "packages",
"token_count": 969
} | 1,080 |
// 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, do not edit directly.
// See also: https://pub.dev/packages/pigeon
#ifndef PIGEON_MESSAGES_G_H_
#define PIGEON_MESSAGES_G_H_
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace pigeon_example {
// Generated class from Pigeon.
class FlutterError {
public:
explicit FlutterError(const std::string& code) : code_(code) {}
explicit FlutterError(const std::string& code, const std::string& message)
: code_(code), message_(message) {}
explicit FlutterError(const std::string& code, const std::string& message,
const flutter::EncodableValue& details)
: code_(code), message_(message), details_(details) {}
const std::string& code() const { return code_; }
const std::string& message() const { return message_; }
const flutter::EncodableValue& details() const { return details_; }
private:
std::string code_;
std::string message_;
flutter::EncodableValue details_;
};
template <class T>
class ErrorOr {
public:
ErrorOr(const T& rhs) : v_(rhs) {}
ErrorOr(const T&& rhs) : v_(std::move(rhs)) {}
ErrorOr(const FlutterError& rhs) : v_(rhs) {}
ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {}
bool has_error() const { return std::holds_alternative<FlutterError>(v_); }
const T& value() const { return std::get<T>(v_); };
const FlutterError& error() const { return std::get<FlutterError>(v_); };
private:
friend class ExampleHostApi;
friend class MessageFlutterApi;
ErrorOr() = default;
T TakeValue() && { return std::get<T>(std::move(v_)); }
std::variant<T, FlutterError> v_;
};
enum class Code { one = 0, two = 1 };
// Generated class from Pigeon that represents data sent in messages.
class MessageData {
public:
// Constructs an object setting all non-nullable fields.
explicit MessageData(const Code& code, const flutter::EncodableMap& data);
// Constructs an object setting all fields.
explicit MessageData(const std::string* name, const std::string* description,
const Code& code, const flutter::EncodableMap& data);
const std::string* name() const;
void set_name(const std::string_view* value_arg);
void set_name(std::string_view value_arg);
const std::string* description() const;
void set_description(const std::string_view* value_arg);
void set_description(std::string_view value_arg);
const Code& code() const;
void set_code(const Code& value_arg);
const flutter::EncodableMap& data() const;
void set_data(const flutter::EncodableMap& value_arg);
private:
static MessageData FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class ExampleHostApi;
friend class ExampleHostApiCodecSerializer;
friend class MessageFlutterApi;
friend class MessageFlutterApiCodecSerializer;
std::optional<std::string> name_;
std::optional<std::string> description_;
Code code_;
flutter::EncodableMap data_;
};
class ExampleHostApiCodecSerializer : public flutter::StandardCodecSerializer {
public:
ExampleHostApiCodecSerializer();
inline static ExampleHostApiCodecSerializer& GetInstance() {
static ExampleHostApiCodecSerializer sInstance;
return sInstance;
}
void WriteValue(const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const override;
protected:
flutter::EncodableValue ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const override;
};
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class ExampleHostApi {
public:
ExampleHostApi(const ExampleHostApi&) = delete;
ExampleHostApi& operator=(const ExampleHostApi&) = delete;
virtual ~ExampleHostApi() {}
virtual ErrorOr<std::string> GetHostLanguage() = 0;
virtual ErrorOr<int64_t> Add(int64_t a, int64_t b) = 0;
virtual void SendMessage(const MessageData& message,
std::function<void(ErrorOr<bool> reply)> result) = 0;
// The codec used by ExampleHostApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `ExampleHostApi` to handle messages through the
// `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
ExampleHostApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
ExampleHostApi() = default;
};
// Generated class from Pigeon that represents Flutter messages that can be
// called from C++.
class MessageFlutterApi {
public:
MessageFlutterApi(flutter::BinaryMessenger* binary_messenger);
static const flutter::StandardMessageCodec& GetCodec();
void FlutterMethod(const std::string* a_string,
std::function<void(const std::string&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
private:
flutter::BinaryMessenger* binary_messenger_;
};
} // namespace pigeon_example
#endif // PIGEON_MESSAGES_G_H_
| packages/packages/pigeon/example/app/windows/runner/messages.g.h/0 | {
"file_path": "packages/packages/pigeon/example/app/windows/runner/messages.g.h",
"repo_id": "packages",
"token_count": 1831
} | 1,081 |
// 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 'ast.dart';
import 'generator_tools.dart';
/// An abstract base class of generators.
///
/// This provides the structure that is common across generators for different languages.
abstract class Generator<T> {
/// Constructor.
const Generator();
/// Generates files for specified language with specified [generatorOptions]
void generate(
T generatorOptions,
Root root,
StringSink sink, {
required String dartPackageName,
});
}
/// An abstract base class that enforces code generation across platforms.
abstract class StructuredGenerator<T> extends Generator<T> {
/// Constructor.
const StructuredGenerator();
@override
void generate(
T generatorOptions,
Root root,
StringSink sink, {
required String dartPackageName,
}) {
final Indent indent = Indent(sink);
writeFilePrologue(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeFileImports(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeOpenNamespace(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeGeneralUtilities(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
if (root.apis.any((Api api) => api is AstProxyApi)) {
writeInstanceManager(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeInstanceManagerApi(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeProxyApiBaseCodec(generatorOptions, root, indent);
}
writeEnums(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeDataClasses(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeApis(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
writeCloseNamespace(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
}
/// Adds specified headers to [indent].
void writeFilePrologue(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
});
/// Writes specified imports to [indent].
void writeFileImports(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
});
/// Writes code to [indent] that opens file namespace if needed.
///
/// This method is not required, and does not need to be overridden.
void writeOpenNamespace(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {}
/// Writes code to [indent] that closes file namespace if needed.
///
/// This method is not required, and does not need to be overridden.
void writeCloseNamespace(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {}
/// Writes any necessary helper utilities to [indent] if needed.
///
/// This method is not required, and does not need to be overridden.
void writeGeneralUtilities(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {}
/// Writes all enums to [indent].
///
/// Can be overridden to add extra code before/after enums.
void writeEnums(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
for (final Enum anEnum in root.enums) {
writeEnum(
generatorOptions,
root,
indent,
anEnum,
dartPackageName: dartPackageName,
);
}
}
/// Writes a single Enum to [indent]. This is needed in most generators.
void writeEnum(
T generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {}
/// Writes all data classes to [indent].
///
/// Can be overridden to add extra code before/after apis.
void writeDataClasses(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
for (final Class classDefinition in root.classes) {
writeDataClass(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
}
}
/// Writes a single data class to [indent].
void writeDataClass(
T generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
});
/// Writes a single class encode method to [indent].
void writeClassEncode(
T generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {}
/// Writes a single class decode method to [indent].
void writeClassDecode(
T generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {}
/// Writes all apis to [indent].
///
/// Can be overridden to add extra code before/after classes.
void writeApis(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
for (final Api api in root.apis) {
switch (api) {
case AstHostApi():
writeHostApi(
generatorOptions,
root,
indent,
api,
dartPackageName: dartPackageName,
);
case AstFlutterApi():
writeFlutterApi(
generatorOptions,
root,
indent,
api,
dartPackageName: dartPackageName,
);
case AstProxyApi():
writeProxyApi(
generatorOptions,
root,
indent,
api,
dartPackageName: dartPackageName,
);
}
}
}
/// Writes a single Flutter Api to [indent].
void writeFlutterApi(
T generatorOptions,
Root root,
Indent indent,
AstFlutterApi api, {
required String dartPackageName,
});
/// Writes a single Host Api to [indent].
void writeHostApi(
T generatorOptions,
Root root,
Indent indent,
AstHostApi api, {
required String dartPackageName,
});
/// Writes the implementation of an `InstanceManager` to [indent].
void writeInstanceManager(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {}
/// Writes the implementation of the API for the `InstanceManager` to
/// [indent].
void writeInstanceManagerApi(
T generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {}
/// Writes the base codec to be used by all ProxyApis.
///
/// This codec should use `128` as the identifier for objects that exist in
/// an `InstanceManager`. The write implementation should convert an instance
/// to an identifier. The read implementation should covert the identifier
/// to an instance.
///
/// This will serve as the default codec for all ProxyApis. If a ProxyApi
/// needs to create its own codec (it has methods/fields/constructor that use
/// a data class) it should extend this codec and not `StandardMessageCodec`.
void writeProxyApiBaseCodec(
T generatorOptions,
Root root,
Indent indent,
) {}
/// Writes a single Proxy Api to [indent].
void writeProxyApi(
T generatorOptions,
Root root,
Indent indent,
AstProxyApi api, {
required String dartPackageName,
}) {}
}
| packages/packages/pigeon/lib/generator.dart/0 | {
"file_path": "packages/packages/pigeon/lib/generator.dart",
"repo_id": "packages",
"token_count": 2894
} | 1,082 |
// 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 an example pigeon file that is used in compilation, unit, mock
// handler, and e2e tests.
import 'package:pigeon/pigeon.dart';
@HostApi()
abstract class MultipleArityHostApi {
int subtract(int x, int y);
}
@FlutterApi()
abstract class MultipleArityFlutterApi {
int subtract(int x, int y);
}
| packages/packages/pigeon/pigeons/multiple_arity.dart/0 | {
"file_path": "packages/packages/pigeon/pigeons/multiple_arity.dart",
"repo_id": "packages",
"token_count": 151
} | 1,083 |
// 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, do not edit directly.
// See also: https://pub.dev/packages/pigeon
package com.example.alternate_language_test_plugin;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.io.ByteArrayOutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})
public class CoreTests {
/** Error class for passing custom error details to Flutter via a thrown PlatformException. */
public static class FlutterError extends RuntimeException {
/** The error code. */
public final String code;
/** The error details. Must be a datatype supported by the api codec. */
public final Object details;
public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) {
super(message);
this.code = code;
this.details = details;
}
}
@NonNull
protected static ArrayList<Object> wrapError(@NonNull Throwable exception) {
ArrayList<Object> errorList = new ArrayList<Object>(3);
if (exception instanceof FlutterError) {
FlutterError error = (FlutterError) exception;
errorList.add(error.code);
errorList.add(error.getMessage());
errorList.add(error.details);
} else {
errorList.add(exception.toString());
errorList.add(exception.getClass().getSimpleName());
errorList.add(
"Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
}
return errorList;
}
@NonNull
protected static FlutterError createConnectionError(@NonNull String channelName) {
return new FlutterError(
"channel-error", "Unable to establish connection on channel: " + channelName + ".", "");
}
@Target(METHOD)
@Retention(CLASS)
@interface CanIgnoreReturnValue {}
public enum AnEnum {
ONE(0),
TWO(1),
THREE(2),
FORTY_TWO(3),
FOUR_HUNDRED_TWENTY_TWO(4);
final int index;
private AnEnum(final int index) {
this.index = index;
}
}
/**
* A class containing all supported types.
*
* <p>Generated class from Pigeon that represents data sent in messages.
*/
public static final class AllTypes {
private @NonNull Boolean aBool;
public @NonNull Boolean getABool() {
return aBool;
}
public void setABool(@NonNull Boolean setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aBool\" is null.");
}
this.aBool = setterArg;
}
private @NonNull Long anInt;
public @NonNull Long getAnInt() {
return anInt;
}
public void setAnInt(@NonNull Long setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"anInt\" is null.");
}
this.anInt = setterArg;
}
private @NonNull Long anInt64;
public @NonNull Long getAnInt64() {
return anInt64;
}
public void setAnInt64(@NonNull Long setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"anInt64\" is null.");
}
this.anInt64 = setterArg;
}
private @NonNull Double aDouble;
public @NonNull Double getADouble() {
return aDouble;
}
public void setADouble(@NonNull Double setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aDouble\" is null.");
}
this.aDouble = setterArg;
}
private @NonNull byte[] aByteArray;
public @NonNull byte[] getAByteArray() {
return aByteArray;
}
public void setAByteArray(@NonNull byte[] setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aByteArray\" is null.");
}
this.aByteArray = setterArg;
}
private @NonNull int[] a4ByteArray;
public @NonNull int[] getA4ByteArray() {
return a4ByteArray;
}
public void setA4ByteArray(@NonNull int[] setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"a4ByteArray\" is null.");
}
this.a4ByteArray = setterArg;
}
private @NonNull long[] a8ByteArray;
public @NonNull long[] getA8ByteArray() {
return a8ByteArray;
}
public void setA8ByteArray(@NonNull long[] setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"a8ByteArray\" is null.");
}
this.a8ByteArray = setterArg;
}
private @NonNull double[] aFloatArray;
public @NonNull double[] getAFloatArray() {
return aFloatArray;
}
public void setAFloatArray(@NonNull double[] setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aFloatArray\" is null.");
}
this.aFloatArray = setterArg;
}
private @NonNull List<Object> aList;
public @NonNull List<Object> getAList() {
return aList;
}
public void setAList(@NonNull List<Object> setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aList\" is null.");
}
this.aList = setterArg;
}
private @NonNull Map<Object, Object> aMap;
public @NonNull Map<Object, Object> getAMap() {
return aMap;
}
public void setAMap(@NonNull Map<Object, Object> setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aMap\" is null.");
}
this.aMap = setterArg;
}
private @NonNull AnEnum anEnum;
public @NonNull AnEnum getAnEnum() {
return anEnum;
}
public void setAnEnum(@NonNull AnEnum setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"anEnum\" is null.");
}
this.anEnum = setterArg;
}
private @NonNull String aString;
public @NonNull String getAString() {
return aString;
}
public void setAString(@NonNull String setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"aString\" is null.");
}
this.aString = setterArg;
}
private @NonNull Object anObject;
public @NonNull Object getAnObject() {
return anObject;
}
public void setAnObject(@NonNull Object setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"anObject\" is null.");
}
this.anObject = setterArg;
}
/** Constructor is non-public to enforce null safety; use Builder. */
AllTypes() {}
public static final class Builder {
private @Nullable Boolean aBool;
@CanIgnoreReturnValue
public @NonNull Builder setABool(@NonNull Boolean setterArg) {
this.aBool = setterArg;
return this;
}
private @Nullable Long anInt;
@CanIgnoreReturnValue
public @NonNull Builder setAnInt(@NonNull Long setterArg) {
this.anInt = setterArg;
return this;
}
private @Nullable Long anInt64;
@CanIgnoreReturnValue
public @NonNull Builder setAnInt64(@NonNull Long setterArg) {
this.anInt64 = setterArg;
return this;
}
private @Nullable Double aDouble;
@CanIgnoreReturnValue
public @NonNull Builder setADouble(@NonNull Double setterArg) {
this.aDouble = setterArg;
return this;
}
private @Nullable byte[] aByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setAByteArray(@NonNull byte[] setterArg) {
this.aByteArray = setterArg;
return this;
}
private @Nullable int[] a4ByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setA4ByteArray(@NonNull int[] setterArg) {
this.a4ByteArray = setterArg;
return this;
}
private @Nullable long[] a8ByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setA8ByteArray(@NonNull long[] setterArg) {
this.a8ByteArray = setterArg;
return this;
}
private @Nullable double[] aFloatArray;
@CanIgnoreReturnValue
public @NonNull Builder setAFloatArray(@NonNull double[] setterArg) {
this.aFloatArray = setterArg;
return this;
}
private @Nullable List<Object> aList;
@CanIgnoreReturnValue
public @NonNull Builder setAList(@NonNull List<Object> setterArg) {
this.aList = setterArg;
return this;
}
private @Nullable Map<Object, Object> aMap;
@CanIgnoreReturnValue
public @NonNull Builder setAMap(@NonNull Map<Object, Object> setterArg) {
this.aMap = setterArg;
return this;
}
private @Nullable AnEnum anEnum;
@CanIgnoreReturnValue
public @NonNull Builder setAnEnum(@NonNull AnEnum setterArg) {
this.anEnum = setterArg;
return this;
}
private @Nullable String aString;
@CanIgnoreReturnValue
public @NonNull Builder setAString(@NonNull String setterArg) {
this.aString = setterArg;
return this;
}
private @Nullable Object anObject;
@CanIgnoreReturnValue
public @NonNull Builder setAnObject(@NonNull Object setterArg) {
this.anObject = setterArg;
return this;
}
public @NonNull AllTypes build() {
AllTypes pigeonReturn = new AllTypes();
pigeonReturn.setABool(aBool);
pigeonReturn.setAnInt(anInt);
pigeonReturn.setAnInt64(anInt64);
pigeonReturn.setADouble(aDouble);
pigeonReturn.setAByteArray(aByteArray);
pigeonReturn.setA4ByteArray(a4ByteArray);
pigeonReturn.setA8ByteArray(a8ByteArray);
pigeonReturn.setAFloatArray(aFloatArray);
pigeonReturn.setAList(aList);
pigeonReturn.setAMap(aMap);
pigeonReturn.setAnEnum(anEnum);
pigeonReturn.setAString(aString);
pigeonReturn.setAnObject(anObject);
return pigeonReturn;
}
}
@NonNull
ArrayList<Object> toList() {
ArrayList<Object> toListResult = new ArrayList<Object>(13);
toListResult.add(aBool);
toListResult.add(anInt);
toListResult.add(anInt64);
toListResult.add(aDouble);
toListResult.add(aByteArray);
toListResult.add(a4ByteArray);
toListResult.add(a8ByteArray);
toListResult.add(aFloatArray);
toListResult.add(aList);
toListResult.add(aMap);
toListResult.add(anEnum == null ? null : anEnum.index);
toListResult.add(aString);
toListResult.add(anObject);
return toListResult;
}
static @NonNull AllTypes fromList(@NonNull ArrayList<Object> list) {
AllTypes pigeonResult = new AllTypes();
Object aBool = list.get(0);
pigeonResult.setABool((Boolean) aBool);
Object anInt = list.get(1);
pigeonResult.setAnInt(
(anInt == null) ? null : ((anInt instanceof Integer) ? (Integer) anInt : (Long) anInt));
Object anInt64 = list.get(2);
pigeonResult.setAnInt64(
(anInt64 == null)
? null
: ((anInt64 instanceof Integer) ? (Integer) anInt64 : (Long) anInt64));
Object aDouble = list.get(3);
pigeonResult.setADouble((Double) aDouble);
Object aByteArray = list.get(4);
pigeonResult.setAByteArray((byte[]) aByteArray);
Object a4ByteArray = list.get(5);
pigeonResult.setA4ByteArray((int[]) a4ByteArray);
Object a8ByteArray = list.get(6);
pigeonResult.setA8ByteArray((long[]) a8ByteArray);
Object aFloatArray = list.get(7);
pigeonResult.setAFloatArray((double[]) aFloatArray);
Object aList = list.get(8);
pigeonResult.setAList((List<Object>) aList);
Object aMap = list.get(9);
pigeonResult.setAMap((Map<Object, Object>) aMap);
Object anEnum = list.get(10);
pigeonResult.setAnEnum(AnEnum.values()[(int) anEnum]);
Object aString = list.get(11);
pigeonResult.setAString((String) aString);
Object anObject = list.get(12);
pigeonResult.setAnObject(anObject);
return pigeonResult;
}
}
/**
* A class containing all supported nullable types.
*
* <p>Generated class from Pigeon that represents data sent in messages.
*/
public static final class AllNullableTypes {
private @Nullable Boolean aNullableBool;
public @Nullable Boolean getANullableBool() {
return aNullableBool;
}
public void setANullableBool(@Nullable Boolean setterArg) {
this.aNullableBool = setterArg;
}
private @Nullable Long aNullableInt;
public @Nullable Long getANullableInt() {
return aNullableInt;
}
public void setANullableInt(@Nullable Long setterArg) {
this.aNullableInt = setterArg;
}
private @Nullable Long aNullableInt64;
public @Nullable Long getANullableInt64() {
return aNullableInt64;
}
public void setANullableInt64(@Nullable Long setterArg) {
this.aNullableInt64 = setterArg;
}
private @Nullable Double aNullableDouble;
public @Nullable Double getANullableDouble() {
return aNullableDouble;
}
public void setANullableDouble(@Nullable Double setterArg) {
this.aNullableDouble = setterArg;
}
private @Nullable byte[] aNullableByteArray;
public @Nullable byte[] getANullableByteArray() {
return aNullableByteArray;
}
public void setANullableByteArray(@Nullable byte[] setterArg) {
this.aNullableByteArray = setterArg;
}
private @Nullable int[] aNullable4ByteArray;
public @Nullable int[] getANullable4ByteArray() {
return aNullable4ByteArray;
}
public void setANullable4ByteArray(@Nullable int[] setterArg) {
this.aNullable4ByteArray = setterArg;
}
private @Nullable long[] aNullable8ByteArray;
public @Nullable long[] getANullable8ByteArray() {
return aNullable8ByteArray;
}
public void setANullable8ByteArray(@Nullable long[] setterArg) {
this.aNullable8ByteArray = setterArg;
}
private @Nullable double[] aNullableFloatArray;
public @Nullable double[] getANullableFloatArray() {
return aNullableFloatArray;
}
public void setANullableFloatArray(@Nullable double[] setterArg) {
this.aNullableFloatArray = setterArg;
}
private @Nullable List<Object> aNullableList;
public @Nullable List<Object> getANullableList() {
return aNullableList;
}
public void setANullableList(@Nullable List<Object> setterArg) {
this.aNullableList = setterArg;
}
private @Nullable Map<Object, Object> aNullableMap;
public @Nullable Map<Object, Object> getANullableMap() {
return aNullableMap;
}
public void setANullableMap(@Nullable Map<Object, Object> setterArg) {
this.aNullableMap = setterArg;
}
private @Nullable List<List<Boolean>> nullableNestedList;
public @Nullable List<List<Boolean>> getNullableNestedList() {
return nullableNestedList;
}
public void setNullableNestedList(@Nullable List<List<Boolean>> setterArg) {
this.nullableNestedList = setterArg;
}
private @Nullable Map<String, String> nullableMapWithAnnotations;
public @Nullable Map<String, String> getNullableMapWithAnnotations() {
return nullableMapWithAnnotations;
}
public void setNullableMapWithAnnotations(@Nullable Map<String, String> setterArg) {
this.nullableMapWithAnnotations = setterArg;
}
private @Nullable Map<String, Object> nullableMapWithObject;
public @Nullable Map<String, Object> getNullableMapWithObject() {
return nullableMapWithObject;
}
public void setNullableMapWithObject(@Nullable Map<String, Object> setterArg) {
this.nullableMapWithObject = setterArg;
}
private @Nullable AnEnum aNullableEnum;
public @Nullable AnEnum getANullableEnum() {
return aNullableEnum;
}
public void setANullableEnum(@Nullable AnEnum setterArg) {
this.aNullableEnum = setterArg;
}
private @Nullable String aNullableString;
public @Nullable String getANullableString() {
return aNullableString;
}
public void setANullableString(@Nullable String setterArg) {
this.aNullableString = setterArg;
}
private @Nullable Object aNullableObject;
public @Nullable Object getANullableObject() {
return aNullableObject;
}
public void setANullableObject(@Nullable Object setterArg) {
this.aNullableObject = setterArg;
}
public static final class Builder {
private @Nullable Boolean aNullableBool;
@CanIgnoreReturnValue
public @NonNull Builder setANullableBool(@Nullable Boolean setterArg) {
this.aNullableBool = setterArg;
return this;
}
private @Nullable Long aNullableInt;
@CanIgnoreReturnValue
public @NonNull Builder setANullableInt(@Nullable Long setterArg) {
this.aNullableInt = setterArg;
return this;
}
private @Nullable Long aNullableInt64;
@CanIgnoreReturnValue
public @NonNull Builder setANullableInt64(@Nullable Long setterArg) {
this.aNullableInt64 = setterArg;
return this;
}
private @Nullable Double aNullableDouble;
@CanIgnoreReturnValue
public @NonNull Builder setANullableDouble(@Nullable Double setterArg) {
this.aNullableDouble = setterArg;
return this;
}
private @Nullable byte[] aNullableByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setANullableByteArray(@Nullable byte[] setterArg) {
this.aNullableByteArray = setterArg;
return this;
}
private @Nullable int[] aNullable4ByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setANullable4ByteArray(@Nullable int[] setterArg) {
this.aNullable4ByteArray = setterArg;
return this;
}
private @Nullable long[] aNullable8ByteArray;
@CanIgnoreReturnValue
public @NonNull Builder setANullable8ByteArray(@Nullable long[] setterArg) {
this.aNullable8ByteArray = setterArg;
return this;
}
private @Nullable double[] aNullableFloatArray;
@CanIgnoreReturnValue
public @NonNull Builder setANullableFloatArray(@Nullable double[] setterArg) {
this.aNullableFloatArray = setterArg;
return this;
}
private @Nullable List<Object> aNullableList;
@CanIgnoreReturnValue
public @NonNull Builder setANullableList(@Nullable List<Object> setterArg) {
this.aNullableList = setterArg;
return this;
}
private @Nullable Map<Object, Object> aNullableMap;
@CanIgnoreReturnValue
public @NonNull Builder setANullableMap(@Nullable Map<Object, Object> setterArg) {
this.aNullableMap = setterArg;
return this;
}
private @Nullable List<List<Boolean>> nullableNestedList;
@CanIgnoreReturnValue
public @NonNull Builder setNullableNestedList(@Nullable List<List<Boolean>> setterArg) {
this.nullableNestedList = setterArg;
return this;
}
private @Nullable Map<String, String> nullableMapWithAnnotations;
@CanIgnoreReturnValue
public @NonNull Builder setNullableMapWithAnnotations(
@Nullable Map<String, String> setterArg) {
this.nullableMapWithAnnotations = setterArg;
return this;
}
private @Nullable Map<String, Object> nullableMapWithObject;
@CanIgnoreReturnValue
public @NonNull Builder setNullableMapWithObject(@Nullable Map<String, Object> setterArg) {
this.nullableMapWithObject = setterArg;
return this;
}
private @Nullable AnEnum aNullableEnum;
@CanIgnoreReturnValue
public @NonNull Builder setANullableEnum(@Nullable AnEnum setterArg) {
this.aNullableEnum = setterArg;
return this;
}
private @Nullable String aNullableString;
@CanIgnoreReturnValue
public @NonNull Builder setANullableString(@Nullable String setterArg) {
this.aNullableString = setterArg;
return this;
}
private @Nullable Object aNullableObject;
@CanIgnoreReturnValue
public @NonNull Builder setANullableObject(@Nullable Object setterArg) {
this.aNullableObject = setterArg;
return this;
}
public @NonNull AllNullableTypes build() {
AllNullableTypes pigeonReturn = new AllNullableTypes();
pigeonReturn.setANullableBool(aNullableBool);
pigeonReturn.setANullableInt(aNullableInt);
pigeonReturn.setANullableInt64(aNullableInt64);
pigeonReturn.setANullableDouble(aNullableDouble);
pigeonReturn.setANullableByteArray(aNullableByteArray);
pigeonReturn.setANullable4ByteArray(aNullable4ByteArray);
pigeonReturn.setANullable8ByteArray(aNullable8ByteArray);
pigeonReturn.setANullableFloatArray(aNullableFloatArray);
pigeonReturn.setANullableList(aNullableList);
pigeonReturn.setANullableMap(aNullableMap);
pigeonReturn.setNullableNestedList(nullableNestedList);
pigeonReturn.setNullableMapWithAnnotations(nullableMapWithAnnotations);
pigeonReturn.setNullableMapWithObject(nullableMapWithObject);
pigeonReturn.setANullableEnum(aNullableEnum);
pigeonReturn.setANullableString(aNullableString);
pigeonReturn.setANullableObject(aNullableObject);
return pigeonReturn;
}
}
@NonNull
ArrayList<Object> toList() {
ArrayList<Object> toListResult = new ArrayList<Object>(16);
toListResult.add(aNullableBool);
toListResult.add(aNullableInt);
toListResult.add(aNullableInt64);
toListResult.add(aNullableDouble);
toListResult.add(aNullableByteArray);
toListResult.add(aNullable4ByteArray);
toListResult.add(aNullable8ByteArray);
toListResult.add(aNullableFloatArray);
toListResult.add(aNullableList);
toListResult.add(aNullableMap);
toListResult.add(nullableNestedList);
toListResult.add(nullableMapWithAnnotations);
toListResult.add(nullableMapWithObject);
toListResult.add(aNullableEnum == null ? null : aNullableEnum.index);
toListResult.add(aNullableString);
toListResult.add(aNullableObject);
return toListResult;
}
static @NonNull AllNullableTypes fromList(@NonNull ArrayList<Object> list) {
AllNullableTypes pigeonResult = new AllNullableTypes();
Object aNullableBool = list.get(0);
pigeonResult.setANullableBool((Boolean) aNullableBool);
Object aNullableInt = list.get(1);
pigeonResult.setANullableInt(
(aNullableInt == null)
? null
: ((aNullableInt instanceof Integer) ? (Integer) aNullableInt : (Long) aNullableInt));
Object aNullableInt64 = list.get(2);
pigeonResult.setANullableInt64(
(aNullableInt64 == null)
? null
: ((aNullableInt64 instanceof Integer)
? (Integer) aNullableInt64
: (Long) aNullableInt64));
Object aNullableDouble = list.get(3);
pigeonResult.setANullableDouble((Double) aNullableDouble);
Object aNullableByteArray = list.get(4);
pigeonResult.setANullableByteArray((byte[]) aNullableByteArray);
Object aNullable4ByteArray = list.get(5);
pigeonResult.setANullable4ByteArray((int[]) aNullable4ByteArray);
Object aNullable8ByteArray = list.get(6);
pigeonResult.setANullable8ByteArray((long[]) aNullable8ByteArray);
Object aNullableFloatArray = list.get(7);
pigeonResult.setANullableFloatArray((double[]) aNullableFloatArray);
Object aNullableList = list.get(8);
pigeonResult.setANullableList((List<Object>) aNullableList);
Object aNullableMap = list.get(9);
pigeonResult.setANullableMap((Map<Object, Object>) aNullableMap);
Object nullableNestedList = list.get(10);
pigeonResult.setNullableNestedList((List<List<Boolean>>) nullableNestedList);
Object nullableMapWithAnnotations = list.get(11);
pigeonResult.setNullableMapWithAnnotations((Map<String, String>) nullableMapWithAnnotations);
Object nullableMapWithObject = list.get(12);
pigeonResult.setNullableMapWithObject((Map<String, Object>) nullableMapWithObject);
Object aNullableEnum = list.get(13);
pigeonResult.setANullableEnum(
aNullableEnum == null ? null : AnEnum.values()[(int) aNullableEnum]);
Object aNullableString = list.get(14);
pigeonResult.setANullableString((String) aNullableString);
Object aNullableObject = list.get(15);
pigeonResult.setANullableObject(aNullableObject);
return pigeonResult;
}
}
/**
* A class for testing nested class handling.
*
* <p>This is needed to test nested nullable and non-nullable classes, `AllNullableTypes` is
* non-nullable here as it is easier to instantiate than `AllTypes` when testing doesn't require
* both (ie. testing null classes).
*
* <p>Generated class from Pigeon that represents data sent in messages.
*/
public static final class AllClassesWrapper {
private @NonNull AllNullableTypes allNullableTypes;
public @NonNull AllNullableTypes getAllNullableTypes() {
return allNullableTypes;
}
public void setAllNullableTypes(@NonNull AllNullableTypes setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"allNullableTypes\" is null.");
}
this.allNullableTypes = setterArg;
}
private @Nullable AllTypes allTypes;
public @Nullable AllTypes getAllTypes() {
return allTypes;
}
public void setAllTypes(@Nullable AllTypes setterArg) {
this.allTypes = setterArg;
}
/** Constructor is non-public to enforce null safety; use Builder. */
AllClassesWrapper() {}
public static final class Builder {
private @Nullable AllNullableTypes allNullableTypes;
@CanIgnoreReturnValue
public @NonNull Builder setAllNullableTypes(@NonNull AllNullableTypes setterArg) {
this.allNullableTypes = setterArg;
return this;
}
private @Nullable AllTypes allTypes;
@CanIgnoreReturnValue
public @NonNull Builder setAllTypes(@Nullable AllTypes setterArg) {
this.allTypes = setterArg;
return this;
}
public @NonNull AllClassesWrapper build() {
AllClassesWrapper pigeonReturn = new AllClassesWrapper();
pigeonReturn.setAllNullableTypes(allNullableTypes);
pigeonReturn.setAllTypes(allTypes);
return pigeonReturn;
}
}
@NonNull
ArrayList<Object> toList() {
ArrayList<Object> toListResult = new ArrayList<Object>(2);
toListResult.add((allNullableTypes == null) ? null : allNullableTypes.toList());
toListResult.add((allTypes == null) ? null : allTypes.toList());
return toListResult;
}
static @NonNull AllClassesWrapper fromList(@NonNull ArrayList<Object> list) {
AllClassesWrapper pigeonResult = new AllClassesWrapper();
Object allNullableTypes = list.get(0);
pigeonResult.setAllNullableTypes(
(allNullableTypes == null)
? null
: AllNullableTypes.fromList((ArrayList<Object>) allNullableTypes));
Object allTypes = list.get(1);
pigeonResult.setAllTypes(
(allTypes == null) ? null : AllTypes.fromList((ArrayList<Object>) allTypes));
return pigeonResult;
}
}
/**
* A data class containing a List, used in unit tests.
*
* <p>Generated class from Pigeon that represents data sent in messages.
*/
public static final class TestMessage {
private @Nullable List<Object> testList;
public @Nullable List<Object> getTestList() {
return testList;
}
public void setTestList(@Nullable List<Object> setterArg) {
this.testList = setterArg;
}
public static final class Builder {
private @Nullable List<Object> testList;
@CanIgnoreReturnValue
public @NonNull Builder setTestList(@Nullable List<Object> setterArg) {
this.testList = setterArg;
return this;
}
public @NonNull TestMessage build() {
TestMessage pigeonReturn = new TestMessage();
pigeonReturn.setTestList(testList);
return pigeonReturn;
}
}
@NonNull
ArrayList<Object> toList() {
ArrayList<Object> toListResult = new ArrayList<Object>(1);
toListResult.add(testList);
return toListResult;
}
static @NonNull TestMessage fromList(@NonNull ArrayList<Object> list) {
TestMessage pigeonResult = new TestMessage();
Object testList = list.get(0);
pigeonResult.setTestList((List<Object>) testList);
return pigeonResult;
}
}
/** Asynchronous error handling return type for non-nullable API method returns. */
public interface Result<T> {
/** Success case callback method for handling returns. */
void success(@NonNull T result);
/** Failure case callback method for handling errors. */
void error(@NonNull Throwable error);
}
/** Asynchronous error handling return type for nullable API method returns. */
public interface NullableResult<T> {
/** Success case callback method for handling returns. */
void success(@Nullable T result);
/** Failure case callback method for handling errors. */
void error(@NonNull Throwable error);
}
/** Asynchronous error handling return type for void API method returns. */
public interface VoidResult {
/** Success case callback method for handling returns. */
void success();
/** Failure case callback method for handling errors. */
void error(@NonNull Throwable error);
}
private static class HostIntegrationCoreApiCodec extends StandardMessageCodec {
public static final HostIntegrationCoreApiCodec INSTANCE = new HostIntegrationCoreApiCodec();
private HostIntegrationCoreApiCodec() {}
@Override
protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {
switch (type) {
case (byte) 128:
return AllClassesWrapper.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 129:
return AllNullableTypes.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 130:
return AllTypes.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 131:
return TestMessage.fromList((ArrayList<Object>) readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) {
if (value instanceof AllClassesWrapper) {
stream.write(128);
writeValue(stream, ((AllClassesWrapper) value).toList());
} else if (value instanceof AllNullableTypes) {
stream.write(129);
writeValue(stream, ((AllNullableTypes) value).toList());
} else if (value instanceof AllTypes) {
stream.write(130);
writeValue(stream, ((AllTypes) value).toList());
} else if (value instanceof TestMessage) {
stream.write(131);
writeValue(stream, ((TestMessage) value).toList());
} else {
super.writeValue(stream, value);
}
}
}
/**
* The core interface that each host language plugin must implement in platform_test integration
* tests.
*
* <p>Generated interface from Pigeon that represents a handler of messages from Flutter.
*/
public interface HostIntegrationCoreApi {
/**
* A no-op function taking no arguments and returning no value, to sanity test basic calling.
*/
void noop();
/** Returns the passed object, to test serialization and deserialization. */
@NonNull
AllTypes echoAllTypes(@NonNull AllTypes everything);
/** Returns an error, to test error handling. */
@Nullable
Object throwError();
/** Returns an error from a void function, to test error handling. */
void throwErrorFromVoid();
/** Returns a Flutter error, to test error handling. */
@Nullable
Object throwFlutterError();
/** Returns passed in int. */
@NonNull
Long echoInt(@NonNull Long anInt);
/** Returns passed in double. */
@NonNull
Double echoDouble(@NonNull Double aDouble);
/** Returns the passed in boolean. */
@NonNull
Boolean echoBool(@NonNull Boolean aBool);
/** Returns the passed in string. */
@NonNull
String echoString(@NonNull String aString);
/** Returns the passed in Uint8List. */
@NonNull
byte[] echoUint8List(@NonNull byte[] aUint8List);
/** Returns the passed in generic Object. */
@NonNull
Object echoObject(@NonNull Object anObject);
/** Returns the passed list, to test serialization and deserialization. */
@NonNull
List<Object> echoList(@NonNull List<Object> aList);
/** Returns the passed map, to test serialization and deserialization. */
@NonNull
Map<String, Object> echoMap(@NonNull Map<String, Object> aMap);
/** Returns the passed map to test nested class serialization and deserialization. */
@NonNull
AllClassesWrapper echoClassWrapper(@NonNull AllClassesWrapper wrapper);
/** Returns the passed enum to test serialization and deserialization. */
@NonNull
AnEnum echoEnum(@NonNull AnEnum anEnum);
/** Returns the default string. */
@NonNull
String echoNamedDefaultString(@NonNull String aString);
/** Returns passed in double. */
@NonNull
Double echoOptionalDefaultDouble(@NonNull Double aDouble);
/** Returns passed in int. */
@NonNull
Long echoRequiredInt(@NonNull Long anInt);
/** Returns the passed object, to test serialization and deserialization. */
@Nullable
AllNullableTypes echoAllNullableTypes(@Nullable AllNullableTypes everything);
/**
* Returns the inner `aString` value from the wrapped object, to test sending of nested objects.
*/
@Nullable
String extractNestedNullableString(@NonNull AllClassesWrapper wrapper);
/**
* Returns the inner `aString` value from the wrapped object, to test sending of nested objects.
*/
@NonNull
AllClassesWrapper createNestedNullableString(@Nullable String nullableString);
/** Returns passed in arguments of multiple types. */
@NonNull
AllNullableTypes sendMultipleNullableTypes(
@Nullable Boolean aNullableBool,
@Nullable Long aNullableInt,
@Nullable String aNullableString);
/** Returns passed in int. */
@Nullable
Long echoNullableInt(@Nullable Long aNullableInt);
/** Returns passed in double. */
@Nullable
Double echoNullableDouble(@Nullable Double aNullableDouble);
/** Returns the passed in boolean. */
@Nullable
Boolean echoNullableBool(@Nullable Boolean aNullableBool);
/** Returns the passed in string. */
@Nullable
String echoNullableString(@Nullable String aNullableString);
/** Returns the passed in Uint8List. */
@Nullable
byte[] echoNullableUint8List(@Nullable byte[] aNullableUint8List);
/** Returns the passed in generic Object. */
@Nullable
Object echoNullableObject(@Nullable Object aNullableObject);
/** Returns the passed list, to test serialization and deserialization. */
@Nullable
List<Object> echoNullableList(@Nullable List<Object> aNullableList);
/** Returns the passed map, to test serialization and deserialization. */
@Nullable
Map<String, Object> echoNullableMap(@Nullable Map<String, Object> aNullableMap);
@Nullable
AnEnum echoNullableEnum(@Nullable AnEnum anEnum);
/** Returns passed in int. */
@Nullable
Long echoOptionalNullableInt(@Nullable Long aNullableInt);
/** Returns the passed in string. */
@Nullable
String echoNamedNullableString(@Nullable String aNullableString);
/**
* A no-op function taking no arguments and returning no value, to sanity test basic
* asynchronous calling.
*/
void noopAsync(@NonNull VoidResult result);
/** Returns passed in int asynchronously. */
void echoAsyncInt(@NonNull Long anInt, @NonNull Result<Long> result);
/** Returns passed in double asynchronously. */
void echoAsyncDouble(@NonNull Double aDouble, @NonNull Result<Double> result);
/** Returns the passed in boolean asynchronously. */
void echoAsyncBool(@NonNull Boolean aBool, @NonNull Result<Boolean> result);
/** Returns the passed string asynchronously. */
void echoAsyncString(@NonNull String aString, @NonNull Result<String> result);
/** Returns the passed in Uint8List asynchronously. */
void echoAsyncUint8List(@NonNull byte[] aUint8List, @NonNull Result<byte[]> result);
/** Returns the passed in generic Object asynchronously. */
void echoAsyncObject(@NonNull Object anObject, @NonNull Result<Object> result);
/** Returns the passed list, to test asynchronous serialization and deserialization. */
void echoAsyncList(@NonNull List<Object> aList, @NonNull Result<List<Object>> result);
/** Returns the passed map, to test asynchronous serialization and deserialization. */
void echoAsyncMap(
@NonNull Map<String, Object> aMap, @NonNull Result<Map<String, Object>> result);
/** Returns the passed enum, to test asynchronous serialization and deserialization. */
void echoAsyncEnum(@NonNull AnEnum anEnum, @NonNull Result<AnEnum> result);
/** Responds with an error from an async function returning a value. */
void throwAsyncError(@NonNull NullableResult<Object> result);
/** Responds with an error from an async void function. */
void throwAsyncErrorFromVoid(@NonNull VoidResult result);
/** Responds with a Flutter error from an async function returning a value. */
void throwAsyncFlutterError(@NonNull NullableResult<Object> result);
/** Returns the passed object, to test async serialization and deserialization. */
void echoAsyncAllTypes(@NonNull AllTypes everything, @NonNull Result<AllTypes> result);
/** Returns the passed object, to test serialization and deserialization. */
void echoAsyncNullableAllNullableTypes(
@Nullable AllNullableTypes everything, @NonNull NullableResult<AllNullableTypes> result);
/** Returns passed in int asynchronously. */
void echoAsyncNullableInt(@Nullable Long anInt, @NonNull NullableResult<Long> result);
/** Returns passed in double asynchronously. */
void echoAsyncNullableDouble(@Nullable Double aDouble, @NonNull NullableResult<Double> result);
/** Returns the passed in boolean asynchronously. */
void echoAsyncNullableBool(@Nullable Boolean aBool, @NonNull NullableResult<Boolean> result);
/** Returns the passed string asynchronously. */
void echoAsyncNullableString(@Nullable String aString, @NonNull NullableResult<String> result);
/** Returns the passed in Uint8List asynchronously. */
void echoAsyncNullableUint8List(
@Nullable byte[] aUint8List, @NonNull NullableResult<byte[]> result);
/** Returns the passed in generic Object asynchronously. */
void echoAsyncNullableObject(@Nullable Object anObject, @NonNull NullableResult<Object> result);
/** Returns the passed list, to test asynchronous serialization and deserialization. */
void echoAsyncNullableList(
@Nullable List<Object> aList, @NonNull NullableResult<List<Object>> result);
/** Returns the passed map, to test asynchronous serialization and deserialization. */
void echoAsyncNullableMap(
@Nullable Map<String, Object> aMap, @NonNull NullableResult<Map<String, Object>> result);
/** Returns the passed enum, to test asynchronous serialization and deserialization. */
void echoAsyncNullableEnum(@Nullable AnEnum anEnum, @NonNull NullableResult<AnEnum> result);
void callFlutterNoop(@NonNull VoidResult result);
void callFlutterThrowError(@NonNull NullableResult<Object> result);
void callFlutterThrowErrorFromVoid(@NonNull VoidResult result);
void callFlutterEchoAllTypes(@NonNull AllTypes everything, @NonNull Result<AllTypes> result);
void callFlutterEchoAllNullableTypes(
@Nullable AllNullableTypes everything, @NonNull NullableResult<AllNullableTypes> result);
void callFlutterSendMultipleNullableTypes(
@Nullable Boolean aNullableBool,
@Nullable Long aNullableInt,
@Nullable String aNullableString,
@NonNull Result<AllNullableTypes> result);
void callFlutterEchoBool(@NonNull Boolean aBool, @NonNull Result<Boolean> result);
void callFlutterEchoInt(@NonNull Long anInt, @NonNull Result<Long> result);
void callFlutterEchoDouble(@NonNull Double aDouble, @NonNull Result<Double> result);
void callFlutterEchoString(@NonNull String aString, @NonNull Result<String> result);
void callFlutterEchoUint8List(@NonNull byte[] aList, @NonNull Result<byte[]> result);
void callFlutterEchoList(@NonNull List<Object> aList, @NonNull Result<List<Object>> result);
void callFlutterEchoMap(
@NonNull Map<String, Object> aMap, @NonNull Result<Map<String, Object>> result);
void callFlutterEchoEnum(@NonNull AnEnum anEnum, @NonNull Result<AnEnum> result);
void callFlutterEchoNullableBool(
@Nullable Boolean aBool, @NonNull NullableResult<Boolean> result);
void callFlutterEchoNullableInt(@Nullable Long anInt, @NonNull NullableResult<Long> result);
void callFlutterEchoNullableDouble(
@Nullable Double aDouble, @NonNull NullableResult<Double> result);
void callFlutterEchoNullableString(
@Nullable String aString, @NonNull NullableResult<String> result);
void callFlutterEchoNullableUint8List(
@Nullable byte[] aList, @NonNull NullableResult<byte[]> result);
void callFlutterEchoNullableList(
@Nullable List<Object> aList, @NonNull NullableResult<List<Object>> result);
void callFlutterEchoNullableMap(
@Nullable Map<String, Object> aMap, @NonNull NullableResult<Map<String, Object>> result);
void callFlutterEchoNullableEnum(
@Nullable AnEnum anEnum, @NonNull NullableResult<AnEnum> result);
/** The codec used by HostIntegrationCoreApi. */
static @NonNull MessageCodec<Object> getCodec() {
return HostIntegrationCoreApiCodec.INSTANCE;
}
/**
* Sets up an instance of `HostIntegrationCoreApi` to handle messages through the
* `binaryMessenger`.
*/
static void setUp(
@NonNull BinaryMessenger binaryMessenger, @Nullable HostIntegrationCoreApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
api.noop();
wrapped.add(0, null);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllTypes everythingArg = (AllTypes) args.get(0);
try {
AllTypes output = api.echoAllTypes(everythingArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
Object output = api.throwError();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwErrorFromVoid",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
api.throwErrorFromVoid();
wrapped.add(0, null);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwFlutterError",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
Object output = api.throwFlutterError();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
try {
Long output = api.echoInt((anIntArg == null) ? null : anIntArg.longValue());
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
try {
Double output = api.echoDouble(aDoubleArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aBoolArg = (Boolean) args.get(0);
try {
Boolean output = api.echoBool(aBoolArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
try {
String output = api.echoString(aStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aUint8ListArg = (byte[]) args.get(0);
try {
byte[] output = api.echoUint8List(aUint8ListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Object anObjectArg = args.get(0);
try {
Object output = api.echoObject(anObjectArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aListArg = (List<Object>) args.get(0);
try {
List<Object> output = api.echoList(aListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aMapArg = (Map<String, Object>) args.get(0);
try {
Map<String, Object> output = api.echoMap(aMapArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassWrapper",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllClassesWrapper wrapperArg = (AllClassesWrapper) args.get(0);
try {
AllClassesWrapper output = api.echoClassWrapper(wrapperArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = AnEnum.values()[(int) args.get(0)];
try {
AnEnum output = api.echoEnum(anEnumArg);
wrapped.add(0, output.index);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedDefaultString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
try {
String output = api.echoNamedDefaultString(aStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalDefaultDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
try {
Double output = api.echoOptionalDefaultDouble(aDoubleArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
try {
Long output =
api.echoRequiredInt((anIntArg == null) ? null : anIntArg.longValue());
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllNullableTypes everythingArg = (AllNullableTypes) args.get(0);
try {
AllNullableTypes output = api.echoAllNullableTypes(everythingArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.extractNestedNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllClassesWrapper wrapperArg = (AllClassesWrapper) args.get(0);
try {
String output = api.extractNestedNullableString(wrapperArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.createNestedNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String nullableStringArg = (String) args.get(0);
try {
AllClassesWrapper output = api.createNestedNullableString(nullableStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aNullableBoolArg = (Boolean) args.get(0);
Number aNullableIntArg = (Number) args.get(1);
String aNullableStringArg = (String) args.get(2);
try {
AllNullableTypes output =
api.sendMultipleNullableTypes(
aNullableBoolArg,
(aNullableIntArg == null) ? null : aNullableIntArg.longValue(),
aNullableStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number aNullableIntArg = (Number) args.get(0);
try {
Long output =
api.echoNullableInt(
(aNullableIntArg == null) ? null : aNullableIntArg.longValue());
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aNullableDoubleArg = (Double) args.get(0);
try {
Double output = api.echoNullableDouble(aNullableDoubleArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aNullableBoolArg = (Boolean) args.get(0);
try {
Boolean output = api.echoNullableBool(aNullableBoolArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aNullableStringArg = (String) args.get(0);
try {
String output = api.echoNullableString(aNullableStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aNullableUint8ListArg = (byte[]) args.get(0);
try {
byte[] output = api.echoNullableUint8List(aNullableUint8ListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableObject",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Object aNullableObjectArg = args.get(0);
try {
Object output = api.echoNullableObject(aNullableObjectArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aNullableListArg = (List<Object>) args.get(0);
try {
List<Object> output = api.echoNullableList(aNullableListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aNullableMapArg = (Map<String, Object>) args.get(0);
try {
Map<String, Object> output = api.echoNullableMap(aNullableMapArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = args.get(0) == null ? null : AnEnum.values()[(int) args.get(0)];
try {
AnEnum output = api.echoNullableEnum(anEnumArg);
wrapped.add(0, output == null ? null : output.index);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalNullableInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number aNullableIntArg = (Number) args.get(0);
try {
Long output =
api.echoOptionalNullableInt(
(aNullableIntArg == null) ? null : aNullableIntArg.longValue());
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aNullableStringArg = (String) args.get(0);
try {
String output = api.echoNamedNullableString(aNullableStringArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.noopAsync(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
Result<Long> resultCallback =
new Result<Long>() {
public void success(Long result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncInt((anIntArg == null) ? null : anIntArg.longValue(), resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
Result<Double> resultCallback =
new Result<Double>() {
public void success(Double result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncDouble(aDoubleArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aBoolArg = (Boolean) args.get(0);
Result<Boolean> resultCallback =
new Result<Boolean>() {
public void success(Boolean result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncBool(aBoolArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
Result<String> resultCallback =
new Result<String>() {
public void success(String result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncString(aStringArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aUint8ListArg = (byte[]) args.get(0);
Result<byte[]> resultCallback =
new Result<byte[]>() {
public void success(byte[] result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncUint8List(aUint8ListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Object anObjectArg = args.get(0);
Result<Object> resultCallback =
new Result<Object>() {
public void success(Object result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncObject(anObjectArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aListArg = (List<Object>) args.get(0);
Result<List<Object>> resultCallback =
new Result<List<Object>>() {
public void success(List<Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncList(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aMapArg = (Map<String, Object>) args.get(0);
Result<Map<String, Object>> resultCallback =
new Result<Map<String, Object>>() {
public void success(Map<String, Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncMap(aMapArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = AnEnum.values()[(int) args.get(0)];
Result<AnEnum> resultCallback =
new Result<AnEnum>() {
public void success(AnEnum result) {
wrapped.add(0, result.index);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncEnum(anEnumArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
NullableResult<Object> resultCallback =
new NullableResult<Object>() {
public void success(Object result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.throwAsyncError(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncErrorFromVoid",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.throwAsyncErrorFromVoid(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncFlutterError",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
NullableResult<Object> resultCallback =
new NullableResult<Object>() {
public void success(Object result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.throwAsyncFlutterError(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncAllTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllTypes everythingArg = (AllTypes) args.get(0);
Result<AllTypes> resultCallback =
new Result<AllTypes>() {
public void success(AllTypes result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncAllTypes(everythingArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllNullableTypes everythingArg = (AllNullableTypes) args.get(0);
NullableResult<AllNullableTypes> resultCallback =
new NullableResult<AllNullableTypes>() {
public void success(AllNullableTypes result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableAllNullableTypes(everythingArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
NullableResult<Long> resultCallback =
new NullableResult<Long>() {
public void success(Long result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableInt(
(anIntArg == null) ? null : anIntArg.longValue(), resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
NullableResult<Double> resultCallback =
new NullableResult<Double>() {
public void success(Double result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableDouble(aDoubleArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aBoolArg = (Boolean) args.get(0);
NullableResult<Boolean> resultCallback =
new NullableResult<Boolean>() {
public void success(Boolean result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableBool(aBoolArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
NullableResult<String> resultCallback =
new NullableResult<String>() {
public void success(String result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableString(aStringArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aUint8ListArg = (byte[]) args.get(0);
NullableResult<byte[]> resultCallback =
new NullableResult<byte[]>() {
public void success(byte[] result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableUint8List(aUint8ListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableObject",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Object anObjectArg = args.get(0);
NullableResult<Object> resultCallback =
new NullableResult<Object>() {
public void success(Object result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableObject(anObjectArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aListArg = (List<Object>) args.get(0);
NullableResult<List<Object>> resultCallback =
new NullableResult<List<Object>>() {
public void success(List<Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableList(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aMapArg = (Map<String, Object>) args.get(0);
NullableResult<Map<String, Object>> resultCallback =
new NullableResult<Map<String, Object>>() {
public void success(Map<String, Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableMap(aMapArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = args.get(0) == null ? null : AnEnum.values()[(int) args.get(0)];
NullableResult<AnEnum> resultCallback =
new NullableResult<AnEnum>() {
public void success(AnEnum result) {
wrapped.add(0, result == null ? null : result.index);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echoAsyncNullableEnum(anEnumArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterNoop(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowError",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
NullableResult<Object> resultCallback =
new NullableResult<Object>() {
public void success(Object result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterThrowError(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowErrorFromVoid",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterThrowErrorFromVoid(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllTypes everythingArg = (AllTypes) args.get(0);
Result<AllTypes> resultCallback =
new Result<AllTypes>() {
public void success(AllTypes result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoAllTypes(everythingArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AllNullableTypes everythingArg = (AllNullableTypes) args.get(0);
NullableResult<AllNullableTypes> resultCallback =
new NullableResult<AllNullableTypes>() {
public void success(AllNullableTypes result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoAllNullableTypes(everythingArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypes",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aNullableBoolArg = (Boolean) args.get(0);
Number aNullableIntArg = (Number) args.get(1);
String aNullableStringArg = (String) args.get(2);
Result<AllNullableTypes> resultCallback =
new Result<AllNullableTypes>() {
public void success(AllNullableTypes result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterSendMultipleNullableTypes(
aNullableBoolArg,
(aNullableIntArg == null) ? null : aNullableIntArg.longValue(),
aNullableStringArg,
resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aBoolArg = (Boolean) args.get(0);
Result<Boolean> resultCallback =
new Result<Boolean>() {
public void success(Boolean result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoBool(aBoolArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
Result<Long> resultCallback =
new Result<Long>() {
public void success(Long result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoInt(
(anIntArg == null) ? null : anIntArg.longValue(), resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
Result<Double> resultCallback =
new Result<Double>() {
public void success(Double result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoDouble(aDoubleArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
Result<String> resultCallback =
new Result<String>() {
public void success(String result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoString(aStringArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aListArg = (byte[]) args.get(0);
Result<byte[]> resultCallback =
new Result<byte[]>() {
public void success(byte[] result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoUint8List(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aListArg = (List<Object>) args.get(0);
Result<List<Object>> resultCallback =
new Result<List<Object>>() {
public void success(List<Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoList(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aMapArg = (Map<String, Object>) args.get(0);
Result<Map<String, Object>> resultCallback =
new Result<Map<String, Object>>() {
public void success(Map<String, Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoMap(aMapArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = AnEnum.values()[(int) args.get(0)];
Result<AnEnum> resultCallback =
new Result<AnEnum>() {
public void success(AnEnum result) {
wrapped.add(0, result.index);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoEnum(anEnumArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableBool",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Boolean aBoolArg = (Boolean) args.get(0);
NullableResult<Boolean> resultCallback =
new NullableResult<Boolean>() {
public void success(Boolean result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableBool(aBoolArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableInt",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Number anIntArg = (Number) args.get(0);
NullableResult<Long> resultCallback =
new NullableResult<Long>() {
public void success(Long result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableInt(
(anIntArg == null) ? null : anIntArg.longValue(), resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableDouble",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Double aDoubleArg = (Double) args.get(0);
NullableResult<Double> resultCallback =
new NullableResult<Double>() {
public void success(Double result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableDouble(aDoubleArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableString",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
NullableResult<String> resultCallback =
new NullableResult<String>() {
public void success(String result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableString(aStringArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableUint8List",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
byte[] aListArg = (byte[]) args.get(0);
NullableResult<byte[]> resultCallback =
new NullableResult<byte[]>() {
public void success(byte[] result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableUint8List(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableList",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<Object> aListArg = (List<Object>) args.get(0);
NullableResult<List<Object>> resultCallback =
new NullableResult<List<Object>>() {
public void success(List<Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableList(aListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableMap",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
Map<String, Object> aMapArg = (Map<String, Object>) args.get(0);
NullableResult<Map<String, Object>> resultCallback =
new NullableResult<Map<String, Object>>() {
public void success(Map<String, Object> result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableMap(aMapArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnum",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
AnEnum anEnumArg = args.get(0) == null ? null : AnEnum.values()[(int) args.get(0)];
NullableResult<AnEnum> resultCallback =
new NullableResult<AnEnum>() {
public void success(AnEnum result) {
wrapped.add(0, result == null ? null : result.index);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.callFlutterEchoNullableEnum(anEnumArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static class FlutterIntegrationCoreApiCodec extends StandardMessageCodec {
public static final FlutterIntegrationCoreApiCodec INSTANCE =
new FlutterIntegrationCoreApiCodec();
private FlutterIntegrationCoreApiCodec() {}
@Override
protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {
switch (type) {
case (byte) 128:
return AllClassesWrapper.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 129:
return AllNullableTypes.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 130:
return AllTypes.fromList((ArrayList<Object>) readValue(buffer));
case (byte) 131:
return TestMessage.fromList((ArrayList<Object>) readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) {
if (value instanceof AllClassesWrapper) {
stream.write(128);
writeValue(stream, ((AllClassesWrapper) value).toList());
} else if (value instanceof AllNullableTypes) {
stream.write(129);
writeValue(stream, ((AllNullableTypes) value).toList());
} else if (value instanceof AllTypes) {
stream.write(130);
writeValue(stream, ((AllTypes) value).toList());
} else if (value instanceof TestMessage) {
stream.write(131);
writeValue(stream, ((TestMessage) value).toList());
} else {
super.writeValue(stream, value);
}
}
}
/**
* The core interface that the Dart platform_test code implements for host integration tests to
* call into.
*
* <p>Generated class from Pigeon that represents Flutter messages that can be called from Java.
*/
public static class FlutterIntegrationCoreApi {
private final @NonNull BinaryMessenger binaryMessenger;
public FlutterIntegrationCoreApi(@NonNull BinaryMessenger argBinaryMessenger) {
this.binaryMessenger = argBinaryMessenger;
}
/** Public interface for sending reply. */
/** The codec used by FlutterIntegrationCoreApi. */
static @NonNull MessageCodec<Object> getCodec() {
return FlutterIntegrationCoreApiCodec.INSTANCE;
}
/**
* A no-op function taking no arguments and returning no value, to sanity test basic calling.
*/
public void noop(@NonNull VoidResult result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
null,
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
result.success();
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Responds with an error from an async function returning a value. */
public void throwError(@NonNull NullableResult<Object> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
null,
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
Object output = listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Responds with an error from an async void function. */
public void throwErrorFromVoid(@NonNull VoidResult result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
null,
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
result.success();
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed object, to test serialization and deserialization. */
public void echoAllTypes(@NonNull AllTypes everythingArg, @NonNull Result<AllTypes> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(everythingArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
AllTypes output = (AllTypes) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed object, to test serialization and deserialization. */
public void echoAllNullableTypes(
@Nullable AllNullableTypes everythingArg,
@NonNull NullableResult<AllNullableTypes> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(everythingArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
AllNullableTypes output = (AllNullableTypes) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/**
* Returns passed in arguments of multiple types.
*
* <p>Tests multiple-arity FlutterApi handling.
*/
public void sendMultipleNullableTypes(
@Nullable Boolean aNullableBoolArg,
@Nullable Long aNullableIntArg,
@Nullable String aNullableStringArg,
@NonNull Result<AllNullableTypes> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(
Arrays.asList(aNullableBoolArg, aNullableIntArg, aNullableStringArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
AllNullableTypes output = (AllNullableTypes) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed boolean, to test serialization and deserialization. */
public void echoBool(@NonNull Boolean aBoolArg, @NonNull Result<Boolean> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aBoolArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
Boolean output = (Boolean) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed int, to test serialization and deserialization. */
public void echoInt(@NonNull Long anIntArg, @NonNull Result<Long> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(anIntArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
Long output =
listReply.get(0) == null ? null : ((Number) listReply.get(0)).longValue();
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed double, to test serialization and deserialization. */
public void echoDouble(@NonNull Double aDoubleArg, @NonNull Result<Double> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aDoubleArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
Double output = (Double) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed string, to test serialization and deserialization. */
public void echoString(@NonNull String aStringArg, @NonNull Result<String> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aStringArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
String output = (String) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed byte list, to test serialization and deserialization. */
public void echoUint8List(@NonNull byte[] aListArg, @NonNull Result<byte[]> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aListArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
byte[] output = (byte[]) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed list, to test serialization and deserialization. */
public void echoList(@NonNull List<Object> aListArg, @NonNull Result<List<Object>> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aListArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
List<Object> output = (List<Object>) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed map, to test serialization and deserialization. */
public void echoMap(
@NonNull Map<String, Object> aMapArg, @NonNull Result<Map<String, Object>> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aMapArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
Map<String, Object> output = (Map<String, Object>) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed enum to test serialization and deserialization. */
public void echoEnum(@NonNull AnEnum anEnumArg, @NonNull Result<AnEnum> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(anEnumArg.index)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
AnEnum output = AnEnum.values()[(int) listReply.get(0)];
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed boolean, to test serialization and deserialization. */
public void echoNullableBool(
@Nullable Boolean aBoolArg, @NonNull NullableResult<Boolean> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aBoolArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
Boolean output = (Boolean) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed int, to test serialization and deserialization. */
public void echoNullableInt(@Nullable Long anIntArg, @NonNull NullableResult<Long> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(anIntArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
Long output =
listReply.get(0) == null ? null : ((Number) listReply.get(0)).longValue();
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed double, to test serialization and deserialization. */
public void echoNullableDouble(
@Nullable Double aDoubleArg, @NonNull NullableResult<Double> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aDoubleArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
Double output = (Double) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed string, to test serialization and deserialization. */
public void echoNullableString(
@Nullable String aStringArg, @NonNull NullableResult<String> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aStringArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
String output = (String) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed byte list, to test serialization and deserialization. */
public void echoNullableUint8List(
@Nullable byte[] aListArg, @NonNull NullableResult<byte[]> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aListArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
byte[] output = (byte[]) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed list, to test serialization and deserialization. */
public void echoNullableList(
@Nullable List<Object> aListArg, @NonNull NullableResult<List<Object>> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aListArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
List<Object> output = (List<Object>) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed map, to test serialization and deserialization. */
public void echoNullableMap(
@Nullable Map<String, Object> aMapArg,
@NonNull NullableResult<Map<String, Object>> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aMapArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
Map<String, Object> output = (Map<String, Object>) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed enum to test serialization and deserialization. */
public void echoNullableEnum(
@Nullable AnEnum anEnumArg, @NonNull NullableResult<AnEnum> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(
Collections.singletonList(anEnumArg == null ? null : anEnumArg.index)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
@SuppressWarnings("ConstantConditions")
AnEnum output =
listReply.get(0) == null ? null : AnEnum.values()[(int) listReply.get(0)];
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/**
* A no-op function taking no arguments and returning no value, to sanity test basic
* asynchronous calling.
*/
public void noopAsync(@NonNull VoidResult result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
null,
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else {
result.success();
}
} else {
result.error(createConnectionError(channelName));
}
});
}
/** Returns the passed in generic Object asynchronously. */
public void echoAsyncString(@NonNull String aStringArg, @NonNull Result<String> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aStringArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
String output = (String) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
}
/**
* An API that can be implemented for minimal, compile-only tests.
*
* <p>Generated interface from Pigeon that represents a handler of messages from Flutter.
*/
public interface HostTrivialApi {
void noop();
/** The codec used by HostTrivialApi. */
static @NonNull MessageCodec<Object> getCodec() {
return new StandardMessageCodec();
}
/** Sets up an instance of `HostTrivialApi` to handle messages through the `binaryMessenger`. */
static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable HostTrivialApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
api.noop();
wrapped.add(0, null);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
/**
* A simple API implemented in some unit tests.
*
* <p>Generated interface from Pigeon that represents a handler of messages from Flutter.
*/
public interface HostSmallApi {
void echo(@NonNull String aString, @NonNull Result<String> result);
void voidVoid(@NonNull VoidResult result);
/** The codec used by HostSmallApi. */
static @NonNull MessageCodec<Object> getCodec() {
return new StandardMessageCodec();
}
/** Sets up an instance of `HostSmallApi` to handle messages through the `binaryMessenger`. */
static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable HostSmallApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String aStringArg = (String) args.get(0);
Result<String> resultCallback =
new Result<String>() {
public void success(String result) {
wrapped.add(0, result);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.echo(aStringArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.voidVoid(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static class FlutterSmallApiCodec extends StandardMessageCodec {
public static final FlutterSmallApiCodec INSTANCE = new FlutterSmallApiCodec();
private FlutterSmallApiCodec() {}
@Override
protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {
switch (type) {
case (byte) 128:
return TestMessage.fromList((ArrayList<Object>) readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) {
if (value instanceof TestMessage) {
stream.write(128);
writeValue(stream, ((TestMessage) value).toList());
} else {
super.writeValue(stream, value);
}
}
}
/**
* A simple API called in some unit tests.
*
* <p>Generated class from Pigeon that represents Flutter messages that can be called from Java.
*/
public static class FlutterSmallApi {
private final @NonNull BinaryMessenger binaryMessenger;
public FlutterSmallApi(@NonNull BinaryMessenger argBinaryMessenger) {
this.binaryMessenger = argBinaryMessenger;
}
/** Public interface for sending reply. */
/** The codec used by FlutterSmallApi. */
static @NonNull MessageCodec<Object> getCodec() {
return FlutterSmallApiCodec.INSTANCE;
}
public void echoWrappedList(@NonNull TestMessage msgArg, @NonNull Result<TestMessage> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(msgArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
TestMessage output = (TestMessage) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
public void echoString(@NonNull String aStringArg, @NonNull Result<String> result) {
final String channelName =
"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString";
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, channelName, getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(aStringArg)),
channelReply -> {
if (channelReply instanceof List) {
List<Object> listReply = (List<Object>) channelReply;
if (listReply.size() > 1) {
result.error(
new FlutterError(
(String) listReply.get(0),
(String) listReply.get(1),
(String) listReply.get(2)));
} else if (listReply.get(0) == null) {
result.error(
new FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
""));
} else {
@SuppressWarnings("ConstantConditions")
String output = (String) listReply.get(0);
result.success(output);
}
} else {
result.error(createConnectionError(channelName));
}
});
}
}
}
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java",
"repo_id": "packages",
"token_count": 86421
} | 1,084 |
// 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 Flutter;
@import Foundation;
NS_ASSUME_NONNULL_BEGIN
@interface MockBinaryMessenger : NSObject <FlutterBinaryMessenger>
@property(nonatomic, retain) NSObject *result;
@property(nonatomic, retain) NSObject<FlutterMessageCodec> *codec;
@property(nonatomic, retain) NSMutableDictionary<NSString *, FlutterBinaryMessageHandler> *handlers;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCodec:(NSObject<FlutterMessageCodec> *)codec NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MockBinaryMessenger.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MockBinaryMessenger.h",
"repo_id": "packages",
"token_count": 221
} | 1,085 |
// 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, do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers
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';
PlatformException _createConnectionError(String channelName) {
return PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel: "$channelName".',
);
}
class FlutterSearchRequest {
FlutterSearchRequest({
this.query,
});
String? query;
Object encode() {
return <Object?>[
query,
];
}
static FlutterSearchRequest decode(Object result) {
result as List<Object?>;
return FlutterSearchRequest(
query: result[0] as String?,
);
}
}
class FlutterSearchReply {
FlutterSearchReply({
this.result,
this.error,
});
String? result;
String? error;
Object encode() {
return <Object?>[
result,
error,
];
}
static FlutterSearchReply decode(Object result) {
result as List<Object?>;
return FlutterSearchReply(
result: result[0] as String?,
error: result[1] as String?,
);
}
}
class FlutterSearchRequests {
FlutterSearchRequests({
this.requests,
});
List<Object?>? requests;
Object encode() {
return <Object?>[
requests,
];
}
static FlutterSearchRequests decode(Object result) {
result as List<Object?>;
return FlutterSearchRequests(
requests: result[0] as List<Object?>?,
);
}
}
class FlutterSearchReplies {
FlutterSearchReplies({
this.replies,
});
List<Object?>? replies;
Object encode() {
return <Object?>[
replies,
];
}
static FlutterSearchReplies decode(Object result) {
result as List<Object?>;
return FlutterSearchReplies(
replies: result[0] as List<Object?>?,
);
}
}
class _ApiCodec extends StandardMessageCodec {
const _ApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FlutterSearchReplies) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is FlutterSearchReply) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is FlutterSearchRequest) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is FlutterSearchRequests) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FlutterSearchReplies.decode(readValue(buffer)!);
case 129:
return FlutterSearchReply.decode(readValue(buffer)!);
case 130:
return FlutterSearchRequest.decode(readValue(buffer)!);
case 131:
return FlutterSearchRequests.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class Api {
/// Constructor for [Api]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
Api({BinaryMessenger? binaryMessenger})
: __pigeon_binaryMessenger = binaryMessenger;
final BinaryMessenger? __pigeon_binaryMessenger;
static const MessageCodec<Object?> pigeonChannelCodec = _ApiCodec();
Future<FlutterSearchReply> search(FlutterSearchRequest request) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.Api.search';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[request]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as FlutterSearchReply?)!;
}
}
Future<FlutterSearchReplies> doSearches(FlutterSearchRequests request) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.Api.doSearches';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[request]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as FlutterSearchReplies?)!;
}
}
Future<FlutterSearchRequests> echo(FlutterSearchRequests requests) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.Api.echo';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[requests]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as FlutterSearchRequests?)!;
}
}
Future<int> anInt(int value) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[value]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as int?)!;
}
}
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart",
"repo_id": "packages",
"token_count": 3278
} | 1,086 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_test_plugin_code/src/generated/flutter_unittests.gen.dart';
import 'package:shared_test_plugin_code/src/generated/nullable_returns.gen.dart';
import 'null_safe_test.mocks.dart';
import 'test_util.dart';
@GenerateMocks(<Type>[
BinaryMessenger,
NullableArgFlutterApi,
NullableReturnFlutterApi,
NullableCollectionArgFlutterApi,
NullableCollectionReturnFlutterApi,
])
void main() {
final TestWidgetsFlutterBinding binding =
TestWidgetsFlutterBinding.ensureInitialized();
test('with values filled', () {
final FlutterSearchReply reply = FlutterSearchReply()
..result = 'foo'
..error = 'bar';
final List<Object?> encoded = reply.encode() as List<Object?>;
final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded);
expect(reply.result, decoded.result);
expect(reply.error, decoded.error);
});
test('with null value', () {
final FlutterSearchReply reply = FlutterSearchReply()
..result = 'foo'
..error = null;
final List<Object?> encoded = reply.encode() as List<Object?>;
final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded);
expect(reply.result, decoded.result);
expect(reply.error, decoded.error);
});
test('send/receive', () async {
final FlutterSearchRequest request = FlutterSearchRequest()..query = 'hey';
final FlutterSearchReply reply = FlutterSearchReply()..result = 'ho';
final BinaryMessenger mockMessenger = MockBinaryMessenger();
final Completer<ByteData?> completer = Completer<ByteData?>();
completer.complete(Api.pigeonChannelCodec.encodeMessage(<Object>[reply]));
final Future<ByteData?> sendResult = completer.future;
when(mockMessenger.send(
'dev.flutter.pigeon.pigeon_integration_tests.Api.search', any))
.thenAnswer((Invocation realInvocation) => sendResult);
final Api api = Api(binaryMessenger: mockMessenger);
final FlutterSearchReply readReply = await api.search(request);
expect(readReply, isNotNull);
expect(reply.result, readReply.result);
});
test('send/receive list classes', () async {
final FlutterSearchRequest request = FlutterSearchRequest()..query = 'hey';
final FlutterSearchRequests requests = FlutterSearchRequests()
..requests = <FlutterSearchRequest>[request];
final BinaryMessenger mockMessenger = MockBinaryMessenger();
echoOneArgument(
mockMessenger,
'dev.flutter.pigeon.pigeon_integration_tests.Api.echo',
Api.pigeonChannelCodec,
);
final Api api = Api(binaryMessenger: mockMessenger);
final FlutterSearchRequests echo = await api.echo(requests);
expect(echo.requests!.length, 1);
expect((echo.requests![0] as FlutterSearchRequest?)!.query, 'hey');
});
test('primitive datatypes', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
echoOneArgument(
mockMessenger,
'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt',
Api.pigeonChannelCodec,
);
final Api api = Api(binaryMessenger: mockMessenger);
final int result = await api.anInt(1);
expect(result, 1);
});
test('return null to nonnull', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
const String channel =
'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt';
when(mockMessenger.send(channel, any))
.thenAnswer((Invocation realInvocation) async {
return Api.pigeonChannelCodec.encodeMessage(<Object?>[null]);
});
final Api api = Api(binaryMessenger: mockMessenger);
expect(() async => api.anInt(1),
throwsA(const TypeMatcher<PlatformException>()));
});
test('send null parameter', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
const String channel =
'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit';
when(mockMessenger.send(channel, any))
.thenAnswer((Invocation realInvocation) async {
return Api.pigeonChannelCodec.encodeMessage(<Object?>[123]);
});
final NullableArgHostApi api =
NullableArgHostApi(binaryMessenger: mockMessenger);
expect(await api.doit(null), 123);
});
test('send null collection parameter', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
const String channel =
'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit';
when(mockMessenger.send(channel, any))
.thenAnswer((Invocation realInvocation) async {
return Api.pigeonChannelCodec.encodeMessage(<Object?>[
<String?>['123']
]);
});
final NullableCollectionArgHostApi api =
NullableCollectionArgHostApi(binaryMessenger: mockMessenger);
expect(await api.doit(null), <String?>['123']);
});
test('receive null parameters', () {
final MockNullableArgFlutterApi mockFlutterApi =
MockNullableArgFlutterApi();
when(mockFlutterApi.doit(null)).thenReturn(14);
NullableArgFlutterApi.setup(mockFlutterApi);
final Completer<int> resultCompleter = Completer<int>();
binding.defaultBinaryMessenger.handlePlatformMessage(
'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit',
NullableArgFlutterApi.pigeonChannelCodec.encodeMessage(<Object?>[null]),
(ByteData? data) {
resultCompleter.complete(
(NullableArgFlutterApi.pigeonChannelCodec.decodeMessage(data)!
as List<Object?>)
.first! as int,
);
},
);
expect(resultCompleter.future, completion(14));
// Removes message handlers from global default binary messenger.
NullableArgFlutterApi.setup(null);
});
test('receive null collection parameters', () {
final MockNullableCollectionArgFlutterApi mockFlutterApi =
MockNullableCollectionArgFlutterApi();
when(mockFlutterApi.doit(null)).thenReturn(<String?>['14']);
NullableCollectionArgFlutterApi.setup(mockFlutterApi);
final Completer<List<String?>> resultCompleter = Completer<List<String?>>();
binding.defaultBinaryMessenger.handlePlatformMessage(
'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit',
NullableCollectionArgFlutterApi.pigeonChannelCodec
.encodeMessage(<Object?>[null]),
(ByteData? data) {
resultCompleter.complete(
((NullableCollectionArgFlutterApi.pigeonChannelCodec
.decodeMessage(data)! as List<Object?>)
.first! as List<Object?>)
.cast<String>(),
);
},
);
expect(resultCompleter.future, completion(<String>['14']));
// Removes message handlers from global default binary messenger.
NullableArgFlutterApi.setup(null);
});
test('receive null return', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
const String channel =
'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit';
when(mockMessenger.send(channel, any))
.thenAnswer((Invocation realInvocation) async {
return NullableReturnHostApi.pigeonChannelCodec
.encodeMessage(<Object?>[null]);
});
final NullableReturnHostApi api =
NullableReturnHostApi(binaryMessenger: mockMessenger);
expect(await api.doit(), null);
});
test('receive null collection return', () async {
final BinaryMessenger mockMessenger = MockBinaryMessenger();
const String channel =
'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit';
when(mockMessenger.send(channel, any))
.thenAnswer((Invocation realInvocation) async {
return NullableCollectionReturnHostApi.pigeonChannelCodec
.encodeMessage(<Object?>[null]);
});
final NullableCollectionReturnHostApi api =
NullableCollectionReturnHostApi(binaryMessenger: mockMessenger);
expect(await api.doit(), null);
});
test('send null return', () async {
final MockNullableReturnFlutterApi mockFlutterApi =
MockNullableReturnFlutterApi();
when(mockFlutterApi.doit()).thenReturn(null);
NullableReturnFlutterApi.setup(mockFlutterApi);
final Completer<int?> resultCompleter = Completer<int?>();
unawaited(binding.defaultBinaryMessenger.handlePlatformMessage(
'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit',
NullableReturnFlutterApi.pigeonChannelCodec.encodeMessage(<Object?>[]),
(ByteData? data) {
resultCompleter.complete(null);
},
));
expect(resultCompleter.future, completion(null));
// Removes message handlers from global default binary messenger.
NullableArgFlutterApi.setup(null);
});
test('send null collection return', () async {
final MockNullableCollectionReturnFlutterApi mockFlutterApi =
MockNullableCollectionReturnFlutterApi();
when(mockFlutterApi.doit()).thenReturn(null);
NullableCollectionReturnFlutterApi.setup(mockFlutterApi);
final Completer<List<String?>?> resultCompleter =
Completer<List<String?>?>();
unawaited(binding.defaultBinaryMessenger.handlePlatformMessage(
'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit',
NullableCollectionReturnFlutterApi.pigeonChannelCodec
.encodeMessage(<Object?>[]),
(ByteData? data) {
resultCompleter.complete(null);
},
));
expect(resultCompleter.future, completion(null));
// Removes message handlers from global default binary messenger.
NullableArgFlutterApi.setup(null);
});
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart",
"repo_id": "packages",
"token_count": 3732
} | 1,087 |
// 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 com.example.test_plugin
import io.flutter.plugin.common.BinaryMessenger
import io.mockk.every
import io.mockk.mockk
import java.nio.ByteBuffer
import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
internal class AllDatatypesTest : TestCase() {
fun compareAllTypes(firstTypes: AllTypes?, secondTypes: AllTypes?) {
assertEquals(firstTypes == null, secondTypes == null)
if (firstTypes == null || secondTypes == null) {
return
}
assertEquals(firstTypes.aBool, secondTypes.aBool)
assertEquals(firstTypes.anInt, secondTypes.anInt)
assertEquals(firstTypes.anInt64, secondTypes.anInt64)
assertEquals(firstTypes.aDouble, secondTypes.aDouble)
assertEquals(firstTypes.aString, secondTypes.aString)
assertTrue(firstTypes.aByteArray.contentEquals(secondTypes.aByteArray))
assertTrue(firstTypes.a4ByteArray.contentEquals(secondTypes.a4ByteArray))
assertTrue(firstTypes.a8ByteArray.contentEquals(secondTypes.a8ByteArray))
assertTrue(firstTypes.aFloatArray.contentEquals(secondTypes.aFloatArray))
assertEquals(firstTypes.aList, secondTypes.aList)
assertEquals(firstTypes.aMap, secondTypes.aMap)
assertEquals(firstTypes.anEnum, secondTypes.anEnum)
assertEquals(firstTypes.anObject, secondTypes.anObject)
}
fun compareAllNullableTypes(firstTypes: AllNullableTypes?, secondTypes: AllNullableTypes?) {
assertEquals(firstTypes == null, secondTypes == null)
if (firstTypes == null || secondTypes == null) {
return
}
assertEquals(firstTypes.aNullableBool, secondTypes.aNullableBool)
assertEquals(firstTypes.aNullableInt, secondTypes.aNullableInt)
assertEquals(firstTypes.aNullableDouble, secondTypes.aNullableDouble)
assertEquals(firstTypes.aNullableString, secondTypes.aNullableString)
assertTrue(firstTypes.aNullableByteArray.contentEquals(secondTypes.aNullableByteArray))
assertTrue(firstTypes.aNullable4ByteArray.contentEquals(secondTypes.aNullable4ByteArray))
assertTrue(firstTypes.aNullable8ByteArray.contentEquals(secondTypes.aNullable8ByteArray))
assertTrue(firstTypes.aNullableFloatArray.contentEquals(secondTypes.aNullableFloatArray))
assertEquals(firstTypes.aNullableList, secondTypes.aNullableList)
assertEquals(firstTypes.aNullableMap, secondTypes.aNullableMap)
assertEquals(firstTypes.nullableMapWithObject, secondTypes.nullableMapWithObject)
assertEquals(firstTypes.aNullableObject, secondTypes.aNullableObject)
}
@Test
fun testNullValues() {
val everything = AllNullableTypes()
val binaryMessenger = mockk<BinaryMessenger>()
val api = FlutterIntegrationCoreApi(binaryMessenger)
every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterIntegrationCoreApi.codec
val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2)
message.position(0)
val args = codec.decodeMessage(message) as ArrayList<*>
val replyData = codec.encodeMessage(args)
replyData?.position(0)
reply.reply(replyData)
}
var didCall = false
api.echoAllNullableTypes(everything) {
didCall = true
val output =
(it.getOrNull())?.let {
assertNull(it.aNullableBool)
assertNull(it.aNullableInt)
assertNull(it.aNullableDouble)
assertNull(it.aNullableString)
assertNull(it.aNullableByteArray)
assertNull(it.aNullable4ByteArray)
assertNull(it.aNullable8ByteArray)
assertNull(it.aNullableFloatArray)
assertNull(it.aNullableList)
assertNull(it.aNullableMap)
assertNull(it.nullableMapWithObject)
}
assertNotNull(output)
}
assertTrue(didCall)
}
@Test
fun testHasValues() {
val everything =
AllNullableTypes(
aNullableBool = false,
aNullableInt = 1234L,
aNullableDouble = 2.0,
aNullableString = "hello",
aNullableByteArray = byteArrayOf(1, 2, 3, 4),
aNullable4ByteArray = intArrayOf(1, 2, 3, 4),
aNullable8ByteArray = longArrayOf(1, 2, 3, 4),
aNullableFloatArray = doubleArrayOf(0.5, 0.25, 1.5, 1.25),
aNullableList = listOf(1, 2, 3),
aNullableMap = mapOf("hello" to 1234),
nullableMapWithObject = mapOf("hello" to 1234),
aNullableObject = 0,
)
val binaryMessenger = mockk<BinaryMessenger>()
val api = FlutterIntegrationCoreApi(binaryMessenger)
every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterIntegrationCoreApi.codec
val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2)
message.position(0)
val args = codec.decodeMessage(message) as ArrayList<*>
val replyData = codec.encodeMessage(args)
replyData?.position(0)
reply.reply(replyData)
}
var didCall = false
api.echoAllNullableTypes(everything) {
didCall = true
compareAllNullableTypes(everything, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testIntegerToLong() {
val everything = AllNullableTypes(aNullableInt = 123L)
val list = everything.toList()
assertNotNull(list)
assertNull(list.first())
assertNotNull(list[1])
assertTrue(list[1] == 123L)
val list2 =
listOf(
null,
123,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null)
val everything2 = AllNullableTypes.fromList(list2)
assertEquals(everything.aNullableInt, everything2.aNullableInt)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt",
"repo_id": "packages",
"token_count": 2560
} | 1,088 |
// 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 Flutter
import XCTest
@testable import test_plugin
class MockPrimitiveHostApi: PrimitiveHostApi {
func anInt(value: Int64) -> Int64 { value }
func aBool(value: Bool) -> Bool { value }
func aString(value: String) -> String { value }
func aDouble(value: Double) -> Double { value }
func aMap(value: [AnyHashable: Any?]) -> [AnyHashable: Any?] { value }
func aList(value: [Any?]) -> [Any?] { value }
func anInt32List(value: FlutterStandardTypedData) -> FlutterStandardTypedData { value }
func aBoolList(value: [Bool?]) -> [Bool?] { value }
func aStringIntMap(value: [String?: Int64?]) -> [String?: Int64?] { value }
}
class PrimitiveTests: XCTestCase {
var codec = FlutterStandardMessageCodec.sharedInstance()
func testIntPrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<Int32>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input = 1
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "anInt")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputList = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputList)
let output = outputList!.first as? Int64
XCTAssertEqual(1, output)
XCTAssertTrue(outputList!.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testIntPrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
api.anInt(value: 1) { result in
switch result {
case .success(let res):
XCTAssertEqual(1, res)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testBoolPrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<Bool>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input = true
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "aBool")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputList = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputList)
let output = outputList!.first as? Bool
XCTAssertEqual(true, output)
XCTAssertTrue(outputList!.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testBoolPrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
api.aBool(value: true) { result in
switch result {
case .success(let res):
XCTAssertEqual(true, res)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testDoublePrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<Double>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input: Double = 1.0
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "aDouble")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputList = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputList)
let output = outputList!.first as? Double
XCTAssertEqual(1.0, output)
XCTAssertTrue(outputList!.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testDoublePrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
let arg: Double = 1.5
api.aDouble(value: arg) { result in
switch result {
case .success(let res):
XCTAssertEqual(arg, res)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testStringPrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<String>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input: String = "hello"
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "aString")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputList = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputList)
let output = outputList!.first as? String
XCTAssertEqual("hello", output)
XCTAssertTrue(outputList!.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testStringPrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
let arg: String = "hello"
api.aString(value: arg) { result in
switch result {
case .success(let res):
XCTAssertEqual(arg, res)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testListPrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<[Int]>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input: [Int] = [1, 2, 3]
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "aList")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputList = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputList)
let output = outputList!.first as? [Int]
XCTAssertEqual([1, 2, 3], output)
XCTAssertTrue(outputList!.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testListPrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
let arg = ["hello"]
api.aList(value: arg) { result in
switch result {
case .success(let res):
XCTAssert(equalsList(arg, res))
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testMapPrimitiveHost() throws {
let binaryMessenger = MockBinaryMessenger<[String: Int]>(codec: codec)
PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input: [String: Int] = ["hello": 1, "world": 2]
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "aMap")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let output = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertTrue(output?.count == 1)
let outputMap = output?.first as? [String: Int]
XCTAssertNotNil(outputMap)
XCTAssertEqual(["hello": 1, "world": 2], outputMap)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testMapPrimitiveFlutter() throws {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
let arg = ["hello": 1]
api.aMap(value: arg) { result in
switch result {
case .success(let res):
XCTAssert(equalsDictionary(arg, res))
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift",
"repo_id": "packages",
"token_count": 3573
} | 1,089 |
// 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 XCTest
@testable import test_plugin
class MyApi: HostTrivialApi {
func noop() {}
}
// Since the generator is almost entirely shared with iOS, this is currently
// just testing that the generated code compiles for macOS (e.g., that the
// Flutter framework import is correct).
class BasicCompileTest: XCTestCase {
func testMakeApi() {
let api = MyApi()
XCTAssertNotNil(api)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift",
"repo_id": "packages",
"token_count": 174
} | 1,090 |
// 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/test_plugin/test_plugin_c_api.h"
#include <flutter/plugin_registrar_windows.h>
#include "test_plugin.h"
void TestPluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
test_plugin::TestPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));
}
| packages/packages/pigeon/platform_tests/test_plugin/windows/test_plugin_c_api.cpp/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test_plugin_c_api.cpp",
"repo_id": "packages",
"token_count": 184
} | 1,091 |
// 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_print
////////////////////////////////////////////////////////////////////////////////
/// CI entrypoint for running Pigeon tests.
///
/// For any use other than CI, use test.dart instead.
////////////////////////////////////////////////////////////////////////////////
library;
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:path/path.dart' as p;
import 'shared/generation.dart';
import 'shared/test_runner.dart';
import 'shared/test_suites.dart';
/// Exits with failure if any tests in [testSuites] are not included in any of
/// the given test [shards].
void _validateTestCoverage(List<List<String>> shards) {
final Set<String> missing = testSuites.keys.toSet();
shards.forEach(missing.removeAll);
if (missing.isNotEmpty) {
print('The following test suites are not being run on any host:');
for (final String suite in missing) {
print(' $suite');
}
exit(1);
}
}
Future<void> _validateGeneratedTestFiles() async {
await _validateGeneratedFiles(
(String baseDir) => generateTestPigeons(baseDir: baseDir),
generationMessage: 'Generating test output',
incorrectFilesMessage:
'The following files are not updated, or not formatted correctly:',
);
}
Future<void> _validateGeneratedExampleFiles() async {
await _validateGeneratedFiles(
(String _) => generateExamplePigeons(),
generationMessage: 'Generating example output',
incorrectFilesMessage:
'Either messages.dart and messages_test.dart have non-matching definitions or\n'
'the following files are not updated, or not formatted correctly:',
);
}
Future<void> _validateGeneratedFiles(
Future<int> Function(String baseDirectory) generator, {
required String generationMessage,
required String incorrectFilesMessage,
}) async {
// Generated file validation is split by platform, both to avoid duplication
// of work, and to avoid issues if different CI configurations have different
// setups (e.g., different clang-format versions or no clang-format at all).
final Set<GeneratorLanguage> languagesToValidate;
if (Platform.isLinux) {
languagesToValidate = <GeneratorLanguage>{
GeneratorLanguage.cpp,
GeneratorLanguage.dart,
GeneratorLanguage.java,
GeneratorLanguage.kotlin,
GeneratorLanguage.objc,
};
} else if (Platform.isMacOS) {
languagesToValidate = <GeneratorLanguage>{
GeneratorLanguage.swift,
};
} else {
return;
}
final String baseDir = p.dirname(p.dirname(Platform.script.toFilePath()));
final String repositoryRoot = p.dirname(p.dirname(baseDir));
final String relativePigeonPath = p.relative(baseDir, from: repositoryRoot);
print('Validating generated files:');
print(' $generationMessage...');
final int generateExitCode = await generateExamplePigeons();
if (generateExitCode != 0) {
print('Generation failed; see above for errors.');
exit(generateExitCode);
}
print(' Formatting output...');
final int formatExitCode = await formatAllFiles(
repositoryRoot: repositoryRoot, languages: languagesToValidate);
if (formatExitCode != 0) {
print('Formatting failed; see above for errors.');
exit(formatExitCode);
}
print(' Checking for changes...');
final List<String> modifiedFiles = await _modifiedFiles(
repositoryRoot: repositoryRoot, relativePigeonPath: relativePigeonPath);
final Set<String> extensions = languagesToValidate
.map((GeneratorLanguage lang) => _extensionsForLanguage(lang))
.flattened
.toSet();
final Iterable<String> filteredFiles = modifiedFiles.where((String path) =>
extensions.contains(p.extension(path).replaceFirst('.', '')));
if (filteredFiles.isEmpty) {
return;
}
print(incorrectFilesMessage);
filteredFiles.map((String line) => ' $line').forEach(print);
print('\nTo fix run "dart run tool/generate.dart --format" from the pigeon/ '
'directory, or apply the diff with the command below.\n');
final ProcessResult diffResult = await Process.run(
'git',
<String>['diff', ...filteredFiles],
workingDirectory: repositoryRoot,
);
if (diffResult.exitCode != 0) {
print('Unable to determine diff.');
exit(1);
}
print('patch -p1 <<DONE');
print(diffResult.stdout);
print('DONE');
exit(1);
}
Set<String> _extensionsForLanguage(GeneratorLanguage language) {
return switch (language) {
GeneratorLanguage.cpp => <String>{'cc', 'cpp', 'h'},
GeneratorLanguage.dart => <String>{'dart'},
GeneratorLanguage.java => <String>{'java'},
GeneratorLanguage.kotlin => <String>{'kt'},
GeneratorLanguage.swift => <String>{'swift'},
GeneratorLanguage.objc => <String>{'h', 'm', 'mm'},
};
}
Future<List<String>> _modifiedFiles(
{required String repositoryRoot,
required String relativePigeonPath}) async {
final ProcessResult result = await Process.run(
'git',
<String>['ls-files', '--modified', relativePigeonPath],
workingDirectory: repositoryRoot,
);
if (result.exitCode != 0) {
print('Unable to determine changed files.');
print(result.stdout);
print(result.stderr);
exit(1);
}
return (result.stdout as String)
.split('\n')
.map((String line) => line.trim())
.where((String line) => line.isNotEmpty)
.toList();
}
Future<void> main(List<String> args) async {
// Run most tests on Linux, since Linux tends to be the easiest and cheapest.
const List<String> linuxHostTests = <String>[
commandLineTests,
androidJavaUnitTests,
androidJavaLint,
androidKotlinUnitTests,
androidJavaIntegrationTests,
androidKotlinIntegrationTests,
];
const List<String> macOSHostTests = <String>[
iOSObjCUnitTests,
// Currently these are testing exactly the same thing as
// macOS*IntegrationTests, so we don't need to run both by default. This
// should be enabled if any iOS-only tests are added (e.g., for a feature
// not supported by macOS).
// iOSObjCIntegrationTests,
// iOSSwiftIntegrationTests,
iOSSwiftUnitTests,
macOSObjCIntegrationTests,
macOSSwiftUnitTests,
macOSSwiftIntegrationTests,
];
// Run Windows tests on Windows, since that's the only place they can run.
const List<String> windowsHostTests = <String>[
windowsUnitTests,
windowsIntegrationTests,
];
_validateTestCoverage(<List<String>>[
linuxHostTests,
macOSHostTests,
windowsHostTests,
// Tests that are deliberately not included in CI:
<String>[
// See comments in macOSHostTests:
iOSObjCIntegrationTests,
iOSSwiftIntegrationTests,
// These are Dart unit tests, which are already run by the normal
// test-dart repo tools command.
dartUnitTests,
flutterUnitTests,
],
]);
// Ensure that all generated files are up to date.
// Only run on master, since Dart format can change between versions.
if (Platform.environment['CHANNEL'] == 'stable') {
print('Skipping generated file validation on stable.');
} else {
await _validateGeneratedTestFiles();
await _validateGeneratedExampleFiles();
}
final List<String> testsToRun;
if (Platform.isMacOS) {
testsToRun = macOSHostTests;
} else if (Platform.isWindows) {
testsToRun = windowsHostTests;
} else if (Platform.isLinux) {
testsToRun = linuxHostTests;
} else {
print('Unsupported host platform.');
exit(2);
}
await runTests(testsToRun);
}
| packages/packages/pigeon/tool/run_tests.dart/0 | {
"file_path": "packages/packages/pigeon/tool/run_tests.dart",
"repo_id": "packages",
"token_count": 2517
} | 1,092 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/platform/example/android/gradle.properties/0 | {
"file_path": "packages/packages/platform/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 31
} | 1,093 |
// 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:convert';
import '../interface/platform.dart';
/// Provides a mutable implementation of the [Platform] interface.
class FakePlatform extends Platform {
/// Creates a new [FakePlatform] with the specified properties.
///
/// Unspecified properties will *not* be assigned default values (they will
/// remain `null`). If an unset non-null value is read, a [StateError] will
/// be thrown instead of returning `null`.
FakePlatform({
int? numberOfProcessors,
String? pathSeparator,
String? operatingSystem,
String? operatingSystemVersion,
String? localHostname,
Map<String, String>? environment,
String? executable,
String? resolvedExecutable,
Uri? script,
List<String>? executableArguments,
this.packageConfig,
String? version,
bool? stdinSupportsAnsi,
bool? stdoutSupportsAnsi,
String? localeName,
}) : _numberOfProcessors = numberOfProcessors,
_pathSeparator = pathSeparator,
_operatingSystem = operatingSystem,
_operatingSystemVersion = operatingSystemVersion,
_localHostname = localHostname,
_environment = environment,
_executable = executable,
_resolvedExecutable = resolvedExecutable,
_script = script,
_executableArguments = executableArguments,
_version = version,
_stdinSupportsAnsi = stdinSupportsAnsi,
_stdoutSupportsAnsi = stdoutSupportsAnsi,
_localeName = localeName;
/// Creates a new [FakePlatform] with properties whose initial values mirror
/// the specified [platform].
FakePlatform.fromPlatform(Platform platform)
: _numberOfProcessors = platform.numberOfProcessors,
_pathSeparator = platform.pathSeparator,
_operatingSystem = platform.operatingSystem,
_operatingSystemVersion = platform.operatingSystemVersion,
_localHostname = platform.localHostname,
_environment = Map<String, String>.from(platform.environment),
_executable = platform.executable,
_resolvedExecutable = platform.resolvedExecutable,
_script = platform.script,
_executableArguments = List<String>.from(platform.executableArguments),
packageConfig = platform.packageConfig,
_version = platform.version,
_stdinSupportsAnsi = platform.stdinSupportsAnsi,
_stdoutSupportsAnsi = platform.stdoutSupportsAnsi,
_localeName = platform.localeName;
/// Creates a new [FakePlatform] with properties extracted from the encoded
/// JSON string.
///
/// [json] must be a JSON string that matches the encoding produced by
/// [toJson].
factory FakePlatform.fromJson(String json) {
final Map<String, dynamic> map =
const JsonDecoder().convert(json) as Map<String, dynamic>;
return FakePlatform(
numberOfProcessors: map['numberOfProcessors'] as int?,
pathSeparator: map['pathSeparator'] as String?,
operatingSystem: map['operatingSystem'] as String?,
operatingSystemVersion: map['operatingSystemVersion'] as String?,
localHostname: map['localHostname'] as String?,
environment:
(map['environment'] as Map<Object?, Object?>).cast<String, String>(),
executable: map['executable'] as String?,
resolvedExecutable: map['resolvedExecutable'] as String?,
script: Uri.parse(map['script'] as String),
executableArguments:
(map['executableArguments'] as List<Object?>).cast<String>(),
packageConfig: map['packageConfig'] as String?,
version: map['version'] as String?,
stdinSupportsAnsi: map['stdinSupportsAnsi'] as bool?,
stdoutSupportsAnsi: map['stdoutSupportsAnsi'] as bool?,
localeName: map['localeName'] as String?,
);
}
/// Creates a new [FakePlatform] from this one, with some properties replaced by the given properties.
FakePlatform copyWith({
int? numberOfProcessors,
String? pathSeparator,
String? operatingSystem,
String? operatingSystemVersion,
String? localHostname,
Map<String, String>? environment,
String? executable,
String? resolvedExecutable,
Uri? script,
List<String>? executableArguments,
String? packageConfig,
String? version,
bool? stdinSupportsAnsi,
bool? stdoutSupportsAnsi,
String? localeName,
}) {
return FakePlatform(
numberOfProcessors: numberOfProcessors ?? this.numberOfProcessors,
pathSeparator: pathSeparator ?? this.pathSeparator,
operatingSystem: operatingSystem ?? this.operatingSystem,
operatingSystemVersion:
operatingSystemVersion ?? this.operatingSystemVersion,
localHostname: localHostname ?? this.localHostname,
environment: environment ?? this.environment,
executable: executable ?? this.executable,
resolvedExecutable: resolvedExecutable ?? this.resolvedExecutable,
script: script ?? this.script,
executableArguments: executableArguments ?? this.executableArguments,
packageConfig: packageConfig ?? this.packageConfig,
version: version ?? this.version,
stdinSupportsAnsi: stdinSupportsAnsi ?? this.stdinSupportsAnsi,
stdoutSupportsAnsi: stdoutSupportsAnsi ?? this.stdoutSupportsAnsi,
localeName: localeName ?? this.localeName,
);
}
@override
int get numberOfProcessors => _throwIfNull(_numberOfProcessors);
int? _numberOfProcessors;
@override
String get pathSeparator => _throwIfNull(_pathSeparator);
String? _pathSeparator;
@override
String get operatingSystem => _throwIfNull(_operatingSystem);
String? _operatingSystem;
@override
String get operatingSystemVersion => _throwIfNull(_operatingSystemVersion);
String? _operatingSystemVersion;
@override
String get localHostname => _throwIfNull(_localHostname);
String? _localHostname;
@override
Map<String, String> get environment => _throwIfNull(_environment);
Map<String, String>? _environment;
@override
String get executable => _throwIfNull(_executable);
String? _executable;
@override
String get resolvedExecutable => _throwIfNull(_resolvedExecutable);
String? _resolvedExecutable;
@override
Uri get script => _throwIfNull(_script);
Uri? _script;
@override
List<String> get executableArguments => _throwIfNull(_executableArguments);
List<String>? _executableArguments;
@override
String? packageConfig;
@override
String get version => _throwIfNull(_version);
String? _version;
@override
bool get stdinSupportsAnsi => _throwIfNull(_stdinSupportsAnsi);
bool? _stdinSupportsAnsi;
@override
bool get stdoutSupportsAnsi => _throwIfNull(_stdoutSupportsAnsi);
bool? _stdoutSupportsAnsi;
@override
String get localeName => _throwIfNull(_localeName);
String? _localeName;
T _throwIfNull<T>(T? value) {
if (value == null) {
throw StateError(
'Tried to read property of FakePlatform but it was unset.');
}
return value;
}
}
| packages/packages/platform/lib/src/testing/fake_platform.dart/0 | {
"file_path": "packages/packages/platform/lib/src/testing/fake_platform.dart",
"repo_id": "packages",
"token_count": 2407
} | 1,094 |
## NEXT
* Updates support matrix in README to indicate that iOS 11 is no longer supported.
* Clients on versions of Flutter that still support iOS 11 can continue to use this
package with iOS 11, but will not receive any further updates to the iOS implementation.
## 0.10.1
* Fixes new lint warnings.
## 0.10.0
* Transitions to federated architecture.
* Adds iOS implementation to federated package.
## 0.9.3+7
* Updates metadata to point to new source folder.
## 0.9.3+6
* Migrates to `dart:ui_web` APIs.
* Updates minimum supported SDK version to Flutter 3.13.0/Dart 3.1.0.
## 0.9.3+5
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Aligns Dart and Flutter SDK constraints.
## 0.9.3+4
* Removes const keyword from PointerInterceptor's constructor.
* Updates minimum Flutter version to 3.0.
## 0.9.3+3
* Fixes lint warnings.
## 0.9.3+2
* (Temporarily) helps tests introduced in prior version to pass in `stable`.
(This will be removed when `master` rolls to `stable`)
* Updates README to reference the correct github URL.
## 0.9.3+1
* Updates example code and integration tests to accomodate hit-testing changes in the Flutter web engine.
## 0.9.3
* Require minimal version of flutter SDK to be `2.10`
## 0.9.2
* Marked `PointerInterceptor` as invisible, so it can be optimized by the engine.
* (Version Retracted. This attempted to use an API from Flutter `2.10` in earlier versions of Flutter. Fixed in v0.9.3)
## 0.9.1
* Removed `android` and `ios` directories from `example`, as the example doesn't
build for those platforms.
* Added `intercepting` field to allow for conditional pointer interception
## 0.9.0+1
* Change sizing of HtmlElementView so it works well when slotted.
## 0.9.0
* Migrates to null safety.
## 0.8.0+2
* Use `ElevatedButton` instead of the deprecated `RaisedButton` in example and docs.
## 0.8.0+1
* Update README.md so images render in pub.dev
## 0.8.0
* Initial release of the `PointerInterceptor` widget.
| packages/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md",
"repo_id": "packages",
"token_count": 653
} | 1,095 |
// 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: avoid_web_libraries_in_flutter
import 'package:flutter/material.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
import 'native_widget.dart';
const double _videoWidth = 640;
const double _videoHeight = 480;
void main() {
runApp(const MyApp());
}
/// Main app
class MyApp extends StatelessWidget {
/// Creates main app.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Stopping Clicks with some DOM',
home: MyHomePage(),
);
}
}
/// First page
class MyHomePage extends StatefulWidget {
/// Creates first page.
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _lastClick = 'none';
void _clickedOn(String key) {
setState(() {
_lastClick = key;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('PointerInterceptor demo'),
actions: <Widget>[
PointerInterceptor(
// debug: true,
child: IconButton(
icon: const Icon(Icons.add_alert),
tooltip: 'AppBar Icon',
onPressed: () {
_clickedOn('appbar-icon');
},
),
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Last click on: $_lastClick',
key: const Key('last-clicked'),
),
Container(
color: Colors.black,
width: _videoWidth,
height: _videoHeight,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
NativeWidget(
key: const ValueKey<String>('background-widget'),
onClick: () {
_clickedOn('native-element');
},
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
key: const Key('transparent-button'),
child: const Text('Never calls onPressed'),
onPressed: () {
_clickedOn('transparent-button');
},
),
PointerInterceptor(
intercepting: false,
child: ElevatedButton(
key: const Key('wrapped-transparent-button'),
child:
const Text('Never calls onPressed transparent'),
onPressed: () {
_clickedOn('wrapped-transparent-button');
},
),
),
PointerInterceptor(
child: ElevatedButton(
key: const Key('clickable-button'),
child: const Text('Works As Expected'),
onPressed: () {
_clickedOn('clickable-button');
},
),
),
],
),
],
),
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
PointerInterceptor(
// debug: true,
child: FloatingActionButton(
child: const Icon(Icons.navigation),
onPressed: () {
_clickedOn('fab-1');
},
),
),
],
),
drawer: Drawer(
child: PointerInterceptor(
// debug: true, // Enable this to "see" the interceptor covering the column.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
title: const Text('Item 1'),
onTap: () {
_clickedOn('drawer-item-1');
},
),
ListTile(
title: const Text('Item 2'),
onTap: () {
_clickedOn('drawer-item-2');
},
),
],
),
),
),
);
}
}
| packages/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart",
"repo_id": "packages",
"token_count": 2693
} | 1,096 |
// 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 Flutter
import UIKit
import XCTest
@testable import pointer_interceptor_ios
class RunnerTests: XCTestCase {
func testNonDebugMode() {
let view = PointerInterceptorView(
frame: CGRect(x: 0, y: 0, width: 180, height: 48.0), debug: false)
let debugView = view.view()
XCTAssertTrue(debugView.backgroundColor == UIColor.clear)
}
func testDebugMode() {
let view = PointerInterceptorView(
frame: CGRect(x: 0, y: 0, width: 180, height: 48.0), debug: true)
let debugView = view.view()
XCTAssertTrue(debugView.backgroundColor == UIColor(red: 1, green: 0, blue: 0, alpha: 0.5))
}
}
| packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift",
"repo_id": "packages",
"token_count": 282
} | 1,097 |
## 0.10.0+1
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 0.10.0
* Initial release from migration to federated architecture.
| packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 48
} | 1,098 |
name: pointer_interceptor_web_example
description: "Demonstrates how to use the pointer_interceptor_web plugin."
publish_to: 'none'
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
pointer_interceptor_platform_interface: ^0.10.0
pointer_interceptor_web:
path: ../../pointer_interceptor_web
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 204
} | 1,099 |
test_on: vm
| packages/packages/process/dart_test.yaml/0 | {
"file_path": "packages/packages/process/dart_test.yaml",
"repo_id": "packages",
"token_count": 6
} | 1,100 |
# quick_actions_example
Demonstrates how to use the quick_actions plugin.
| packages/packages/quick_actions/quick_actions/example/README.md/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/example/README.md",
"repo_id": "packages",
"token_count": 21
} | 1,101 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/quick_actions/quick_actions/example/android/gradle.properties/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,102 |
group 'io.flutter.plugins.quickactions'
version '1.0-SNAPSHOT'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.1'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.quickactions'
}
compileSdk 34
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.0.0'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
| packages/packages/quick_actions/quick_actions_android/android/build.gradle/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/android/build.gradle",
"repo_id": "packages",
"token_count": 643
} | 1,103 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
import 'src/messages.g.dart';
export 'package:quick_actions_platform_interface/types/types.dart';
late QuickActionHandler _handler;
/// An implementation of [QuickActionsPlatform] for Android.
class QuickActionsAndroid extends QuickActionsPlatform {
/// Creates a new plugin implementation instance.
QuickActionsAndroid({
@visibleForTesting AndroidQuickActionsApi? api,
}) : _hostApi = api ?? AndroidQuickActionsApi();
final AndroidQuickActionsApi _hostApi;
/// Registers this class as the default instance of [QuickActionsPlatform].
static void registerWith() {
QuickActionsPlatform.instance = QuickActionsAndroid();
}
@override
Future<void> initialize(QuickActionHandler handler) async {
final _QuickActionHandlerApi quickActionsHandlerApi =
_QuickActionHandlerApi();
AndroidQuickActionsFlutterApi.setup(quickActionsHandlerApi);
_handler = handler;
final String? action = await _hostApi.getLaunchAction();
if (action != null) {
_handler(action);
}
}
@override
Future<void> setShortcutItems(List<ShortcutItem> items) async {
await _hostApi.setShortcutItems(
items.map(_shortcutItemToShortcutItemMessage).toList(),
);
}
@override
Future<void> clearShortcutItems() => _hostApi.clearShortcutItems();
ShortcutItemMessage _shortcutItemToShortcutItemMessage(ShortcutItem item) {
return ShortcutItemMessage(
type: item.type,
localizedTitle: item.localizedTitle,
icon: item.icon,
);
}
}
class _QuickActionHandlerApi extends AndroidQuickActionsFlutterApi {
@override
void launchAction(String action) {
_handler(action);
}
}
| packages/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart",
"repo_id": "packages",
"token_count": 622
} | 1,104 |
// 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/widgets.dart';
/// For clarity, this example uses the text representation of the sample remote
/// widget library, and parses it locally. To do this, [parseLibraryFile] is
/// used. In production, this is strongly discouraged since it is 10x slower
/// than using [decodeLibraryBlob] to parse the binary version of the format.
import 'package:rfw/formats.dart' show parseLibraryFile;
import 'package:rfw/rfw.dart';
void main() {
runApp(const Example());
}
// The "#docregion" comment helps us keep this code in sync with the
// excerpt in the rfw package's README.md file.
//
// #docregion Example
class Example extends StatefulWidget {
const Example({super.key});
@override
State<Example> createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
final Runtime _runtime = Runtime();
final DynamicContent _data = DynamicContent();
// Normally this would be obtained dynamically, but for this example
// we hard-code the "remote" widgets into the app.
//
// Also, normally we would decode this with [decodeLibraryBlob] rather than
// parsing the text version using [parseLibraryFile]. However, to make it
// easier to demo, this uses the slower text format.
static final RemoteWidgetLibrary _remoteWidgets = parseLibraryFile('''
// The "import" keyword is used to specify dependencies, in this case,
// the built-in widgets that are added by initState below.
import core.widgets;
// The "widget" keyword is used to define a new widget constructor.
// The "root" widget is specified as the one to render in the build
// method below.
widget root = Container(
color: 0xFF002211,
child: Center(
child: Text(text: ["Hello, ", data.greet.name, "!"], textDirection: "ltr"),
),
);
''');
static const LibraryName coreName = LibraryName(<String>['core', 'widgets']);
static const LibraryName mainName = LibraryName(<String>['main']);
@override
void initState() {
super.initState();
// Local widget library:
_runtime.update(coreName, createCoreWidgets());
// Remote widget library:
_runtime.update(mainName, _remoteWidgets);
// Configuration data:
_data.update('greet', <String, Object>{'name': 'World'});
}
@override
Widget build(BuildContext context) {
return RemoteWidget(
runtime: _runtime,
data: _data,
widget: const FullyQualifiedWidgetName(mainName, 'root'),
onEvent: (String name, DynamicMap arguments) {
// The example above does not have any way to trigger events, but if it
// did, they would result in this callback being invoked.
debugPrint('user triggered event "$name" with data: $arguments');
},
);
}
}
// #enddocregion Example
| packages/packages/rfw/example/hello/lib/main.dart/0 | {
"file_path": "packages/packages/rfw/example/hello/lib/main.dart",
"repo_id": "packages",
"token_count": 907
} | 1,105 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/rfw/example/local/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/local/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,106 |
// 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.
/// # Remote Flutter Widgets
///
/// Renders a widget tree described in a file, which you can change at runtime.
///
/// There are many ways to use a package such as this one. In general, the
/// approach looks something like this:
///
/// 
///
/// The network aspects of this design are out of scope for this package. Remote
/// widget libraries and data should be cached locally, to avoid network issues
/// causing interface failures.
///
/// In the extreme, this package can be combined with a local scripting runtime
/// (e.g. [https://pub.dev/packages/hetu_script](hetu_script)) to run
/// remotely-fetched logic locally:
///
/// 
///
///
/// ## Using the [RemoteWidget] widget
///
/// To render a remote widget, the [RemoteWidget] widget can be used. It takes a
/// [DynamicContent] instance and a [Runtime] instance, which must be configured
/// ahead of time.
///
/// ## Best practices for handling remote data
///
/// The most efficient way to parse remote data is [decodeDataBlob] and the most
/// efficient way to parse remote widget libraries is [decodeLibraryBlob].
///
/// The methods for parsing the text format are not exported by
/// `package:rfw/rfw.dart` to discourage their use in client-side code.
///
/// ## Server-side Dart
///
/// This package can be used in non-Flutter environments by importing
/// `package:rfw/formats.dart` rather than `package:rfw/rfw.dart`. In the
/// [formats] mode, the [Runtime] and [DynamicContent] objects, as well as the
/// [RemoteWidget] widget, are not available, but the [parseDataFile] and
/// [parseLibraryFile] methods are. They can be used in conjunction with
/// [encodeDataBlob] and [encodeLibraryBlob] (respectively) to generate the
/// binary files used by client-side code.
library rfw;
export 'src/dart/binary.dart';
export 'src/dart/model.dart';
export 'src/dart/text.dart' hide parseDataFile, parseLibraryFile;
export 'src/flutter/argument_decoders.dart';
export 'src/flutter/content.dart';
export 'src/flutter/core_widgets.dart';
export 'src/flutter/material_widgets.dart';
export 'src/flutter/remote_widget.dart';
export 'src/flutter/runtime.dart';
| packages/packages/rfw/lib/rfw.dart/0 | {
"file_path": "packages/packages/rfw/lib/rfw.dart",
"repo_id": "packages",
"token_count": 920
} | 1,107 |
// 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 hand-formatted.
import 'package:flutter_test/flutter_test.dart';
import 'package:rfw/formats.dart';
void main() {
testWidgets('$LibraryName', (WidgetTester tester) async {
T deconst<T>(T value) => value;
final LibraryName a = LibraryName(<String>['core', deconst<String>('widgets')]);
final LibraryName b = LibraryName(<String>['core', deconst<String>('widgets')]);
final LibraryName c = LibraryName(<String>['core', deconst<String>('material')]);
const LibraryName d = LibraryName(<String>['core']);
expect('$a', 'core.widgets');
expect('$c', 'core.material');
expect(a, equals(b));
expect(a.hashCode, equals(b.hashCode));
expect(a, isNot(equals(c)));
expect(a.hashCode, isNot(equals(c.hashCode)));
expect(a.compareTo(b), 0);
expect(b.compareTo(a), 0);
expect(a.compareTo(c), 1);
expect(c.compareTo(a), -1);
expect(b.compareTo(c), 1);
expect(c.compareTo(b), -1);
expect(a.compareTo(d), 1);
expect(b.compareTo(d), 1);
expect(c.compareTo(d), 1);
expect(d.compareTo(a), -1);
expect(d.compareTo(b), -1);
expect(d.compareTo(c), -1);
});
testWidgets('$FullyQualifiedWidgetName', (WidgetTester tester) async {
const FullyQualifiedWidgetName aa = FullyQualifiedWidgetName(LibraryName(<String>['a']), 'a');
const FullyQualifiedWidgetName ab = FullyQualifiedWidgetName(LibraryName(<String>['a']), 'b');
const FullyQualifiedWidgetName bb = FullyQualifiedWidgetName(LibraryName(<String>['b']), 'b');
expect('$aa', 'a:a');
expect(aa, isNot(equals(bb)));
expect(aa.hashCode, isNot(equals(bb.hashCode)));
expect(aa.compareTo(aa), 0);
expect(aa.compareTo(ab), -1);
expect(aa.compareTo(bb), -1);
expect(ab.compareTo(aa), 1);
expect(ab.compareTo(ab), 0);
expect(ab.compareTo(bb), -1);
expect(bb.compareTo(aa), 1);
expect(bb.compareTo(ab), 1);
expect(bb.compareTo(bb), 0);
});
testWidgets('toStrings', (WidgetTester tester) async {
expect('$missing', '<missing>');
expect('${const Loop(0, 1)}', '...for loop in 0: 1');
expect('${const Switch(0, <Object?, Object>{1: 2})}', 'switch 0 {1: 2}');
expect('${const ConstructorCall("a", <String, Object>{})}', 'a({})');
expect('${const ArgsReference(<Object>["a"])}', 'args.a');
expect('${const BoundArgsReference(false, <Object>["a"])}', 'args(false).a');
expect('${const DataReference(<Object>["a"])}', 'data.a');
expect('${const LoopReference(0, <Object>["a"])}', 'loop0.a');
expect('${const BoundLoopReference(0, <Object>["a"])}', 'loop(0).a');
expect('${const StateReference(<Object>["a"])}', 'state.a');
expect('${const BoundStateReference(0, <Object>["a"])}', 'state^0.a');
expect('${const EventHandler("a", <String, Object?>{})}', 'event a {}');
expect('${const SetStateHandler(StateReference(<Object>["a"]), false)}', 'set state.a = false');
expect('${const Import(LibraryName(<String>["a"]))}', 'import a;');
expect('${const WidgetDeclaration("a", null, ConstructorCall("b", <String, Object>{}))}', 'widget a = b({});');
expect('${const WidgetDeclaration("a", <String, Object?>{ "x": false }, ConstructorCall("b", <String, Object>{}))}', 'widget a = b({});');
expect('${const RemoteWidgetLibrary(<Import>[Import(LibraryName(<String>["a"]))], <WidgetDeclaration>[WidgetDeclaration("a", null, ConstructorCall("b", <String, Object>{}))])}', 'import a;\nwidget a = b({});');
});
testWidgets('$BoundArgsReference', (WidgetTester tester) async {
final Object target = Object();
final BoundArgsReference result = const ArgsReference(<Object>[0]).bind(target);
expect(result.arguments, target);
expect(result.parts, const <Object>[0]);
});
testWidgets('$DataReference', (WidgetTester tester) async {
final DataReference result = const DataReference(<Object>[0]).constructReference(<Object>[1]);
expect(result.parts, const <Object>[0, 1]);
});
testWidgets('$LoopReference', (WidgetTester tester) async {
final LoopReference result = const LoopReference(9, <Object>[0]).constructReference(<Object>[1]);
expect(result.parts, const <Object>[0, 1]);
});
testWidgets('$BoundLoopReference', (WidgetTester tester) async {
final Object target = Object();
final BoundLoopReference result = const LoopReference(9, <Object>[0]).bind(target).constructReference(<Object>[1]);
expect(result.value, target);
expect(result.parts, const <Object>[0, 1]);
});
testWidgets('$BoundStateReference', (WidgetTester tester) async {
final BoundStateReference result = const StateReference(<Object>[0]).bind(9).constructReference(<Object>[1]);
expect(result.depth, 9);
expect(result.parts, const <Object>[0, 1]);
});
testWidgets('$SourceLocation comparison', (WidgetTester tester) async {
const SourceLocation test1 = SourceLocation('test', 123);
const SourceLocation test2 = SourceLocation('test', 234);
expect(test1.compareTo(test2), lessThan(0));
// test1 vs test1
expect(test1 == test1, isTrue);
expect(test1 < test1, isFalse);
expect(test1 <= test1, isTrue);
expect(test1 > test1, isFalse);
expect(test1 >= test1, isTrue);
// test1 vs test2
expect(test1 == test2, isFalse);
expect(test1 < test2, isTrue);
expect(test1 <= test2, isTrue);
expect(test1 > test2, isFalse);
expect(test1 >= test2, isFalse);
// test2 vs test1
expect(test2 == test1, isFalse);
expect(test2 < test1, isFalse);
expect(test2 <= test1, isFalse);
expect(test2 > test1, isTrue);
expect(test2 >= test1, isTrue);
// map
final Map<SourceLocation, SourceLocation> map = <SourceLocation, SourceLocation>{
test1: test1,
test2: test2,
};
expect(map[test1], test1);
expect(map[test2], test2);
});
testWidgets('$SourceLocation with non-matching sources', (WidgetTester tester) async {
const SourceLocation test1 = SourceLocation('test1', 123);
const SourceLocation test2 = SourceLocation('test2', 234);
expect(() => test1.compareTo(test2), throwsA(anything));
expect(() => test1 < test2, throwsA(anything));
expect(() => test1 <= test2, throwsA(anything));
expect(() => test1 > test2, throwsA(anything));
expect(() => test1 >= test2, throwsA(anything));
});
testWidgets('$SourceLocation toString', (WidgetTester tester) async {
const SourceLocation test = SourceLocation('test1', 123);
expect('$test', 'test1@123');
});
testWidgets('$SourceRange', (WidgetTester tester) async {
const SourceLocation a = SourceLocation('test', 123);
const SourceLocation b = SourceLocation('test', 124);
const SourceLocation c = SourceLocation('test', 125);
final SourceRange range1 = SourceRange(a, b);
final SourceRange range2 = SourceRange(b, c);
// toString
expect('$range1', '[email protected]');
// equality
expect(range1 == range1, isTrue);
expect(range1 == range2, isFalse);
expect(range2 == range1, isFalse);
// map
final Map<SourceRange, SourceRange> map = <SourceRange, SourceRange>{
range1: range1,
range2: range2,
};
expect(map[range1], range1);
expect(map[range2], range2);
});
}
| packages/packages/rfw/test/model_test.dart/0 | {
"file_path": "packages/packages/rfw/test/model_test.dart",
"repo_id": "packages",
"token_count": 2726
} | 1,108 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/shared_preferences/shared_preferences/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,109 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,110 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
/// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing
/// a persistent store for simple data.
///
/// Data is persisted to disk asynchronously.
class SharedPreferences {
SharedPreferences._(this._preferenceCache);
static String _prefix = 'flutter.';
static bool _prefixHasBeenChanged = false;
static Set<String>? _allowList;
static Completer<SharedPreferences>? _completer;
static SharedPreferencesStorePlatform get _store =>
SharedPreferencesStorePlatform.instance;
/// Sets the prefix that is attached to all keys for all shared preferences.
///
/// This changes the inputs when adding data to preferences as well as
/// setting the filter that determines what data will be returned
/// from the `getInstance` method.
///
/// By default, the prefix is 'flutter.', which is compatible with the
/// previous behavior of this plugin. To use preferences with no prefix,
/// set [prefix] to ''.
///
/// If [prefix] is set to '', you may encounter preferences that are
/// incompatible with shared_preferences. The optional parameter
/// [allowList] will cause the plugin to only return preferences that
/// are both contained in the list AND match the provided prefix.
///
/// No migration of existing preferences is performed by this method.
/// If you set a different prefix, and have previously stored preferences,
/// you will need to handle any migration yourself.
///
/// This cannot be called after `getInstance`.
static void setPrefix(String prefix, {Set<String>? allowList}) {
if (_completer != null) {
throw StateError('setPrefix cannot be called after getInstance');
}
_prefix = prefix;
_prefixHasBeenChanged = true;
_allowList = allowList;
}
/// Resets class's static values to allow for testing of setPrefix flow.
@visibleForTesting
static void resetStatic() {
_completer = null;
_prefix = 'flutter.';
_prefixHasBeenChanged = false;
_allowList = null;
}
/// Loads and parses the [SharedPreferences] for this app from disk.
///
/// Because this is reading from disk, it shouldn't be awaited in
/// performance-sensitive blocks.
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
final Completer<SharedPreferences> completer =
Completer<SharedPreferences>();
_completer = completer;
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
completer.complete(SharedPreferences._(preferencesMap));
} catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = completer.future;
_completer = null;
return sharedPrefsFuture;
}
}
return _completer!.future;
}
/// The cache that holds all preferences.
///
/// It is instantiated to the current state of the SharedPreferences or
/// NSUserDefaults object and then kept in sync via setter methods in this
/// class.
///
/// It is NOT guaranteed that this cache and the device prefs will remain
/// in sync since the setter method might fail for any reason.
final Map<String, Object> _preferenceCache;
/// Returns all keys in the persistent storage.
Set<String> getKeys() => Set<String>.from(_preferenceCache.keys);
/// Reads a value of any type from persistent storage.
Object? get(String key) => _preferenceCache[key];
/// Reads a value from persistent storage, throwing an exception if it's not a
/// bool.
bool? getBool(String key) => _preferenceCache[key] as bool?;
/// Reads a value from persistent storage, throwing an exception if it's not
/// an int.
int? getInt(String key) => _preferenceCache[key] as int?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// double.
double? getDouble(String key) => _preferenceCache[key] as double?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// String.
String? getString(String key) => _preferenceCache[key] as String?;
/// Returns true if the persistent storage contains the given [key].
bool containsKey(String key) => _preferenceCache.containsKey(key);
/// Reads a set of string values from persistent storage, throwing an
/// exception if it's not a string set.
List<String>? getStringList(String key) {
List<dynamic>? list = _preferenceCache[key] as List<dynamic>?;
if (list != null && list is! List<String>) {
list = list.cast<String>().toList();
_preferenceCache[key] = list;
}
// Make a copy of the list so that later mutations won't propagate
return list?.toList() as List<String>?;
}
/// Saves a boolean [value] to persistent storage in the background.
Future<bool> setBool(String key, bool value) => _setValue('Bool', key, value);
/// Saves an integer [value] to persistent storage in the background.
Future<bool> setInt(String key, int value) => _setValue('Int', key, value);
/// Saves a double [value] to persistent storage in the background.
///
/// Android doesn't support storing doubles, so it will be stored as a float.
Future<bool> setDouble(String key, double value) =>
_setValue('Double', key, value);
/// Saves a string [value] to persistent storage in the background.
///
/// Note: Due to limitations in Android's SharedPreferences,
/// values cannot start with any one of the following:
///
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu'
Future<bool> setString(String key, String value) =>
_setValue('String', key, value);
/// Saves a list of strings [value] to persistent storage in the background.
Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);
/// Removes an entry from persistent storage.
Future<bool> remove(String key) {
final String prefixedKey = '$_prefix$key';
_preferenceCache.remove(key);
return _store.remove(prefixedKey);
}
Future<bool> _setValue(String valueType, String key, Object value) {
ArgumentError.checkNotNull(value, 'value');
final String prefixedKey = '$_prefix$key';
if (value is List<String>) {
// Make a copy of the list so that later mutations won't propagate
_preferenceCache[key] = value.toList();
} else {
_preferenceCache[key] = value;
}
return _store.setValue(valueType, prefixedKey, value);
}
/// Always returns true.
/// On iOS, synchronize is marked deprecated. On Android, we commit every set.
@Deprecated('This method is now a no-op, and should no longer be called.')
Future<bool> commit() async => true;
/// Completes with true once the user preferences for the app has been cleared.
Future<bool> clear() {
_preferenceCache.clear();
if (_prefixHasBeenChanged) {
try {
return _store.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(
prefix: _prefix,
allowList: _allowList,
),
),
);
} catch (e) {
// Catching and clarifying UnimplementedError to provide a more robust message.
if (e is UnimplementedError) {
throw UnimplementedError('''
This implementation of Shared Preferences doesn't yet support the setPrefix method.
Either update the implementation to support setPrefix, or do not call setPrefix.
''');
} else {
rethrow;
}
}
}
return _store.clear();
}
/// Fetches the latest values from the host platform.
///
/// Use this method to observe modifications that were made in native code
/// (without using the plugin) while the app is running.
Future<void> reload() async {
final Map<String, Object> preferences =
await SharedPreferences._getSharedPreferencesMap();
_preferenceCache.clear();
_preferenceCache.addAll(preferences);
}
static Future<Map<String, Object>> _getSharedPreferencesMap() async {
final Map<String, Object> fromSystem = <String, Object>{};
if (_prefixHasBeenChanged) {
try {
fromSystem.addAll(
await _store.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(
prefix: _prefix,
allowList: _allowList,
),
),
),
);
} catch (e) {
// Catching and clarifying UnimplementedError to provide a more robust message.
if (e is UnimplementedError) {
throw UnimplementedError('''
This implementation of Shared Preferences doesn't yet support the setPrefix method.
Either update the implementation to support setPrefix, or do not call setPrefix.
''');
} else {
rethrow;
}
}
} else {
fromSystem.addAll(await _store.getAll());
}
if (_prefix.isEmpty) {
return fromSystem;
}
// Strip the prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (final String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key]!;
}
return preferencesMap;
}
/// Initializes the shared preferences with mock values for testing.
///
/// If the singleton instance has been initialized already, it is nullified.
@visibleForTesting
static void setMockInitialValues(Map<String, Object> values) {
final Map<String, Object> newValues =
values.map<String, Object>((String key, Object value) {
String newKey = key;
if (!key.startsWith(_prefix)) {
newKey = '$_prefix$key';
}
return MapEntry<String, Object>(newKey, value);
});
SharedPreferencesStorePlatform.instance =
InMemorySharedPreferencesStore.withData(newValues);
_completer = null;
}
}
| packages/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart",
"repo_id": "packages",
"token_count": 3532
} | 1,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.