text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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() { testWidgets('replace inside shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/134524. final UniqueKey a = UniqueKey(); final UniqueKey b = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/a', builder: (_, __) => DummyScreen(key: a), ), GoRoute( path: '/b', builder: (_, __) => DummyScreen(key: b), ) ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); router.replace<void>('/b'); await tester.pumpAndSettle(); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsNothing); expect(find.byKey(b), findsOneWidget); }); testWidgets('push from outside of shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/130406. final UniqueKey a = UniqueKey(); final UniqueKey b = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/a', builder: (_, __) => DummyScreen(key: a), ), ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/b', builder: (_, __) => DummyScreen(key: b), ), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsNothing); expect(find.byKey(a), findsOneWidget); router.push('/b'); await tester.pumpAndSettle(); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsNothing); expect(find.byKey(b), findsOneWidget); }); testWidgets('shell route reflect imperative push', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/125752. final UniqueKey home = UniqueKey(); final UniqueKey a = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (_, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar(title: Text('location: ${state.uri.path}')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/', builder: (_, __) => DummyScreen(key: home), routes: <RouteBase>[ GoRoute( path: 'a', builder: (_, __) => DummyScreen(key: a), ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('location: /a'), findsOneWidget); expect(find.byKey(a), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.text('location: /'), findsOneWidget); expect(find.byKey(a), findsNothing); expect(find.byKey(home), findsOneWidget); router.push('/a'); await tester.pumpAndSettle(); expect(find.text('location: /a'), findsOneWidget); expect(find.byKey(a), findsOneWidget); expect(find.byKey(home), findsNothing); }); testWidgets('push shell route in another shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120791. final UniqueKey b = UniqueKey(); final UniqueKey a = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell1')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/a', builder: (_, __) => DummyScreen(key: a), ), ], ), ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell2')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/b', builder: (_, __) => DummyScreen(key: b), ), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell1'), findsOneWidget); expect(find.byKey(a), findsOneWidget); router.push('/b'); await tester.pumpAndSettle(); expect(find.text('shell1'), findsNothing); expect(find.byKey(a), findsNothing); expect(find.text('shell2'), findsOneWidget); expect(find.byKey(b), findsOneWidget); }); testWidgets('push inside or outside shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120665. final UniqueKey inside = UniqueKey(); final UniqueKey outside = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/in', builder: (_, __) => DummyScreen(key: inside), ), ], ), GoRoute( path: '/out', builder: (_, __) => DummyScreen(key: outside), ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/out'); expect(find.text('shell'), findsNothing); expect(find.byKey(outside), findsOneWidget); router.push('/in'); await tester.pumpAndSettle(); expect(find.text('shell'), findsOneWidget); expect(find.byKey(outside), findsNothing); expect(find.byKey(inside), findsOneWidget); router.push('/out'); await tester.pumpAndSettle(); expect(find.text('shell'), findsNothing); expect(find.byKey(outside), findsOneWidget); expect(find.byKey(inside), findsNothing); }); testWidgets('complex case 1', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/113001. final UniqueKey a = UniqueKey(); final UniqueKey b = UniqueKey(); final UniqueKey c = UniqueKey(); final UniqueKey d = UniqueKey(); final UniqueKey e = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (_, __, Widget child) { return Scaffold( appBar: AppBar(title: const Text('shell')), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/a', builder: (_, __) => DummyScreen(key: a), ), GoRoute( path: '/c', builder: (_, __) => DummyScreen(key: c), ), ], ), GoRoute( path: '/d', builder: (_, __) => DummyScreen(key: d), routes: <RouteBase>[ GoRoute( path: 'e', builder: (_, __) => DummyScreen(key: e), ), ], ), GoRoute( path: '/b', builder: (_, __) => DummyScreen(key: b), ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); router.push('/b'); await tester.pumpAndSettle(); expect(find.text('shell'), findsNothing); expect(find.byKey(a), findsNothing); expect(find.byKey(b), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); router.go('/c'); await tester.pumpAndSettle(); expect(find.text('shell'), findsOneWidget); expect(find.byKey(c), findsOneWidget); router.push('/d'); await tester.pumpAndSettle(); expect(find.text('shell'), findsNothing); expect(find.byKey(d), findsOneWidget); router.push('/d/e'); await tester.pumpAndSettle(); expect(find.text('shell'), findsNothing); expect(find.byKey(e), findsOneWidget); }); }
packages/packages/go_router/test/imperative_api_test.dart/0
{ "file_path": "packages/packages/go_router/test/imperative_api_test.dart", "repo_id": "packages", "token_count": 3991 }
969
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: cascade_invocations, diagnostic_describe_all_properties import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; Future<GoRouter> createGoRouter(WidgetTester tester) async { final GoRouter goRouter = GoRouter( initialLocation: '/', routes: <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), GoRoute( path: '/error', builder: (_, __) => TestErrorScreen(TestFailure('Exception')), ), ], ); await tester.pumpWidget(MaterialApp.router( routerConfig: goRouter, )); return goRouter; } Widget fakeNavigationBuilder( BuildContext context, GoRouterState state, Widget child, ) => child; class GoRouterNamedLocationSpy extends GoRouter { GoRouterNamedLocationSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map<String, String>? pathParameters; Map<String, dynamic>? queryParameters; @override String namedLocation( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, }) { this.name = name; this.pathParameters = pathParameters; this.queryParameters = queryParameters; return ''; } } class GoRouterGoSpy extends GoRouter { GoRouterGoSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? myLocation; Object? extra; @override void go(String location, {Object? extra}) { myLocation = location; this.extra = extra; } } class GoRouterGoNamedSpy extends GoRouter { GoRouterGoNamedSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map<String, String>? pathParameters; Map<String, dynamic>? queryParameters; Object? extra; @override void goNamed( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) { this.name = name; this.pathParameters = pathParameters; this.queryParameters = queryParameters; this.extra = extra; } } class GoRouterPushSpy extends GoRouter { GoRouterPushSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? myLocation; Object? extra; @override Future<T?> push<T extends Object?>(String location, {Object? extra}) { myLocation = location; this.extra = extra; return Future<T?>.value(extra as T?); } } class GoRouterPushNamedSpy extends GoRouter { GoRouterPushNamedSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map<String, String>? pathParameters; Map<String, dynamic>? queryParameters; Object? extra; @override Future<T?> pushNamed<T extends Object?>( String name, { Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra, }) { this.name = name; this.pathParameters = pathParameters; this.queryParameters = queryParameters; this.extra = extra; return Future<T?>.value(extra as T?); } } class GoRouterPopSpy extends GoRouter { GoRouterPopSpy({required List<RouteBase> routes}) : super.routingConfig( routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); bool popped = false; Object? poppedResult; @override void pop<T extends Object?>([T? result]) { popped = true; poppedResult = result; } } Future<GoRouter> createRouter( List<RouteBase> routes, WidgetTester tester, { GoRouterRedirect? redirect, String initialLocation = '/', Object? initialExtra, int redirectLimit = 5, GlobalKey<NavigatorState>? navigatorKey, GoRouterWidgetBuilder? errorBuilder, String? restorationScopeId, Codec<Object?, Object?>? extraCodec, GoExceptionHandler? onException, bool requestFocus = true, bool overridePlatformDefaultLocation = false, }) async { final GoRouter goRouter = GoRouter( routes: routes, redirect: redirect, extraCodec: extraCodec, initialLocation: initialLocation, onException: onException, initialExtra: initialExtra, redirectLimit: redirectLimit, errorBuilder: errorBuilder, navigatorKey: navigatorKey, restorationScopeId: restorationScopeId, requestFocus: requestFocus, overridePlatformDefaultLocation: overridePlatformDefaultLocation, ); addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null, routerConfig: goRouter, ), ); return goRouter; } Future<GoRouter> createRouterWithRoutingConfig( ValueListenable<RoutingConfig> config, WidgetTester tester, { String initialLocation = '/', Object? initialExtra, GlobalKey<NavigatorState>? navigatorKey, GoRouterWidgetBuilder? errorBuilder, String? restorationScopeId, GoExceptionHandler? onException, bool requestFocus = true, bool overridePlatformDefaultLocation = false, }) async { final GoRouter goRouter = GoRouter.routingConfig( routingConfig: config, initialLocation: initialLocation, onException: onException, initialExtra: initialExtra, errorBuilder: errorBuilder, navigatorKey: navigatorKey, restorationScopeId: restorationScopeId, requestFocus: requestFocus, overridePlatformDefaultLocation: overridePlatformDefaultLocation, ); addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null, routerConfig: goRouter, ), ); return goRouter; } class TestErrorScreen extends DummyScreen { const TestErrorScreen(this.ex, {super.key}); final Exception ex; } class HomeScreen extends DummyScreen { const HomeScreen({super.key}); } class Page1Screen extends DummyScreen { const Page1Screen({super.key}); } class Page2Screen extends DummyScreen { const Page2Screen({super.key}); } class LoginScreen extends DummyScreen { const LoginScreen({super.key}); } class FamilyScreen extends DummyScreen { const FamilyScreen(this.fid, {super.key}); final String fid; } class FamiliesScreen extends DummyScreen { const FamiliesScreen({required this.selectedFid, super.key}); final String selectedFid; } class PersonScreen extends DummyScreen { const PersonScreen(this.fid, this.pid, {super.key}); final String fid; final String pid; } class DummyScreen extends StatelessWidget { const DummyScreen({ this.queryParametersAll = const <String, dynamic>{}, super.key, }); final Map<String, dynamic> queryParametersAll; @override Widget build(BuildContext context) => const Placeholder(); } Widget dummy(BuildContext context, GoRouterState state) => const DummyScreen(); final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); class DummyStatefulWidget extends StatefulWidget { const DummyStatefulWidget({super.key}); @override State<StatefulWidget> createState() => DummyStatefulWidgetState(); } class DummyStatefulWidgetState extends State<DummyStatefulWidget> { int counter = 0; void increment() => setState(() { counter++; }); @override Widget build(BuildContext context) => Container(); } class DummyRestorableStatefulWidget extends StatefulWidget { const DummyRestorableStatefulWidget({super.key, this.restorationId}); final String? restorationId; @override State<StatefulWidget> createState() => DummyRestorableStatefulWidgetState(); } class DummyRestorableStatefulWidgetState extends State<DummyRestorableStatefulWidget> with RestorationMixin { final RestorableInt _counter = RestorableInt(0); @override String? get restorationId => widget.restorationId; int get counter => _counter.value; void increment([int count = 1]) => setState(() { _counter.value += count; }); @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { if (restorationId != null) { registerForRestoration(_counter, restorationId!); } } @override void dispose() { _counter.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Container(); } Future<void> simulateAndroidBackButton(WidgetTester tester) async { final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); } GoRouterPageBuilder createPageBuilder( {String? restorationId, required Widget child}) => (BuildContext context, GoRouterState state) => MaterialPage<dynamic>(restorationId: restorationId, child: child); StatefulShellRouteBuilder mockStackedShellBuilder = (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { return navigationShell; }; /// A routing config that is never going to change. class ConstantRoutingConfig extends ValueListenable<RoutingConfig> { const ConstantRoutingConfig(this.value); @override void addListener(VoidCallback listener) { // Intentionally empty because listener will never be called. } @override void removeListener(VoidCallback listener) { // Intentionally empty because listener will never be called. } @override final RoutingConfig value; } RouteConfiguration createRouteConfiguration({ required List<RouteBase> routes, required GlobalKey<NavigatorState> navigatorKey, required GoRouterRedirect topRedirect, required int redirectLimit, }) { return RouteConfiguration( ConstantRoutingConfig(RoutingConfig( routes: routes, redirect: topRedirect, redirectLimit: redirectLimit, )), navigatorKey: navigatorKey); } class SimpleDependencyProvider extends InheritedNotifier<SimpleDependency> { const SimpleDependencyProvider( {super.key, required SimpleDependency dependency, required super.child}) : super(notifier: dependency); static SimpleDependency of(BuildContext context) { final SimpleDependencyProvider result = context.dependOnInheritedWidgetOfExactType<SimpleDependencyProvider>()!; return result.notifier!; } } class SimpleDependency extends ChangeNotifier { bool get boolProperty => _boolProperty; bool _boolProperty = true; set boolProperty(bool value) { if (value == _boolProperty) { return; } _boolProperty = value; notifyListeners(); } }
packages/packages/go_router/test/test_helpers.dart/0
{ "file_path": "packages/packages/go_router/test/test_helpers.dart", "repo_id": "packages", "token_count": 3829 }
970
// 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, unreachable_from_main import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'shared/data.dart'; part 'all_types.g.dart'; @TypedGoRoute<AllTypesBaseRoute>(path: '/', routes: <TypedGoRoute<GoRouteData>>[ TypedGoRoute<BigIntRoute>(path: 'big-int-route/:requiredBigIntField'), TypedGoRoute<BoolRoute>(path: 'bool-route/:requiredBoolField'), TypedGoRoute<DateTimeRoute>(path: 'date-time-route/:requiredDateTimeField'), TypedGoRoute<DoubleRoute>(path: 'double-route/:requiredDoubleField'), TypedGoRoute<IntRoute>(path: 'int-route/:requiredIntField'), TypedGoRoute<NumRoute>(path: 'num-route/:requiredNumField'), TypedGoRoute<DoubleRoute>(path: 'double-route/:requiredDoubleField'), TypedGoRoute<EnumRoute>(path: 'enum-route/:requiredEnumField'), TypedGoRoute<EnhancedEnumRoute>( path: 'enhanced-enum-route/:requiredEnumField'), TypedGoRoute<StringRoute>(path: 'string-route/:requiredStringField'), TypedGoRoute<UriRoute>(path: 'uri-route/:requiredUriField'), TypedGoRoute<IterableRoute>(path: 'iterable-route'), TypedGoRoute<IterableRouteWithDefaultValues>( path: 'iterable-route-with-default-values'), ]) @immutable class AllTypesBaseRoute extends GoRouteData { const AllTypesBaseRoute(); @override Widget build(BuildContext context, GoRouterState state) => const BasePage<void>( dataTitle: 'Root', ); } class BigIntRoute extends GoRouteData { BigIntRoute({ required this.requiredBigIntField, this.bigIntField, }); final BigInt requiredBigIntField; final BigInt? bigIntField; @override Widget build(BuildContext context, GoRouterState state) => BasePage<BigInt>( dataTitle: 'BigIntRoute', param: requiredBigIntField, queryParam: bigIntField, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('BigIntRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class BoolRoute extends GoRouteData { BoolRoute({ required this.requiredBoolField, this.boolField, this.boolFieldWithDefaultValue = true, }); final bool requiredBoolField; final bool? boolField; final bool boolFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<bool>( dataTitle: 'BoolRoute', param: requiredBoolField, queryParam: boolField, queryParamWithDefaultValue: boolFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('BoolRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class DateTimeRoute extends GoRouteData { DateTimeRoute({ required this.requiredDateTimeField, this.dateTimeField, }); final DateTime requiredDateTimeField; final DateTime? dateTimeField; @override Widget build(BuildContext context, GoRouterState state) => BasePage<DateTime>( dataTitle: 'DateTimeRoute', param: requiredDateTimeField, queryParam: dateTimeField, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('DateTimeRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class DoubleRoute extends GoRouteData { DoubleRoute({ required this.requiredDoubleField, this.doubleField, this.doubleFieldWithDefaultValue = 1.0, }); final double requiredDoubleField; final double? doubleField; final double doubleFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<double>( dataTitle: 'DoubleRoute', param: requiredDoubleField, queryParam: doubleField, queryParamWithDefaultValue: doubleFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('DoubleRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class IntRoute extends GoRouteData { IntRoute({ required this.requiredIntField, this.intField, this.intFieldWithDefaultValue = 1, }); final int requiredIntField; final int? intField; final int intFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<int>( dataTitle: 'IntRoute', param: requiredIntField, queryParam: intField, queryParamWithDefaultValue: intFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('IntRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class NumRoute extends GoRouteData { NumRoute({ required this.requiredNumField, this.numField, this.numFieldWithDefaultValue = 1, }); final num requiredNumField; final num? numField; final num numFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<num>( dataTitle: 'NumRoute', param: requiredNumField, queryParam: numField, queryParamWithDefaultValue: numFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('NumRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class EnumRoute extends GoRouteData { EnumRoute({ required this.requiredEnumField, this.enumField, this.enumFieldWithDefaultValue = PersonDetails.favoriteFood, }); final PersonDetails requiredEnumField; final PersonDetails? enumField; final PersonDetails enumFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<PersonDetails>( dataTitle: 'EnumRoute', param: requiredEnumField, queryParam: enumField, queryParamWithDefaultValue: enumFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnumRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class EnhancedEnumRoute extends GoRouteData { EnhancedEnumRoute({ required this.requiredEnumField, this.enumField, this.enumFieldWithDefaultValue = SportDetails.football, }); final SportDetails requiredEnumField; final SportDetails? enumField; final SportDetails enumFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<SportDetails>( dataTitle: 'EnhancedEnumRoute', param: requiredEnumField, queryParam: enumField, queryParamWithDefaultValue: enumFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnhancedEnumRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class StringRoute extends GoRouteData { StringRoute({ required this.requiredStringField, this.stringField, this.stringFieldWithDefaultValue = 'defaultValue', }); final String requiredStringField; final String? stringField; final String stringFieldWithDefaultValue; @override Widget build(BuildContext context, GoRouterState state) => BasePage<String>( dataTitle: 'StringRoute', param: requiredStringField, queryParam: stringField, queryParamWithDefaultValue: stringFieldWithDefaultValue, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('StringRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class UriRoute extends GoRouteData { UriRoute({ required this.requiredUriField, this.uriField, }); final Uri requiredUriField; final Uri? uriField; @override Widget build(BuildContext context, GoRouterState state) => BasePage<Uri>( dataTitle: 'UriRoute', param: requiredUriField, queryParam: uriField, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('UriRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class IterableRoute extends GoRouteData { IterableRoute({ this.intIterableField, this.doubleIterableField, this.stringIterableField, this.boolIterableField, this.enumIterableField, this.enumOnlyInIterableField, this.intListField, this.doubleListField, this.stringListField, this.boolListField, this.enumListField, this.enumOnlyInListField, this.intSetField, this.doubleSetField, this.stringSetField, this.boolSetField, this.enumSetField, this.enumOnlyInSetField, }); final Iterable<int>? intIterableField; final List<int>? intListField; final Set<int>? intSetField; final Iterable<double>? doubleIterableField; final List<double>? doubleListField; final Set<double>? doubleSetField; final Iterable<String>? stringIterableField; final List<String>? stringListField; final Set<String>? stringSetField; final Iterable<bool>? boolIterableField; final List<bool>? boolListField; final Set<bool>? boolSetField; final Iterable<SportDetails>? enumIterableField; final List<SportDetails>? enumListField; final Set<SportDetails>? enumSetField; final Iterable<CookingRecipe>? enumOnlyInIterableField; final List<CookingRecipe>? enumOnlyInListField; final Set<CookingRecipe>? enumOnlyInSetField; @override Widget build(BuildContext context, GoRouterState state) => IterablePage( dataTitle: 'IterableRoute', intIterableField: intIterableField, doubleIterableField: doubleIterableField, stringIterableField: stringIterableField, boolIterableField: boolIterableField, enumIterableField: enumIterableField, intListField: intListField, doubleListField: doubleListField, stringListField: stringListField, boolListField: boolListField, enumListField: enumListField, intSetField: intSetField, doubleSetField: doubleSetField, stringSetField: stringSetField, boolSetField: boolSetField, enumSetField: enumSetField, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('IterableRoute'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class IterableRouteWithDefaultValues extends GoRouteData { const IterableRouteWithDefaultValues({ this.intIterableField = const <int>[0], this.doubleIterableField = const <double>[0, 1, 2], this.stringIterableField = const <String>['defaultValue'], this.boolIterableField = const <bool>[false], this.enumIterableField = const <SportDetails>[ SportDetails.tennis, SportDetails.hockey, ], this.intListField = const <int>[0], this.doubleListField = const <double>[1, 2, 3], this.stringListField = const <String>['defaultValue0', 'defaultValue1'], this.boolListField = const <bool>[true], this.enumListField = const <SportDetails>[SportDetails.football], this.intSetField = const <int>{0, 1}, this.doubleSetField = const <double>{}, this.stringSetField = const <String>{'defaultValue'}, this.boolSetField = const <bool>{true, false}, this.enumSetField = const <SportDetails>{SportDetails.hockey}, }); final Iterable<int> intIterableField; final List<int> intListField; final Set<int> intSetField; final Iterable<double> doubleIterableField; final List<double> doubleListField; final Set<double> doubleSetField; final Iterable<String> stringIterableField; final List<String> stringListField; final Set<String> stringSetField; final Iterable<bool> boolIterableField; final List<bool> boolListField; final Set<bool> boolSetField; final Iterable<SportDetails> enumIterableField; final List<SportDetails> enumListField; final Set<SportDetails> enumSetField; @override Widget build(BuildContext context, GoRouterState state) => IterablePage( dataTitle: 'IterableRouteWithDefaultValues', intIterableField: intIterableField, doubleIterableField: doubleIterableField, stringIterableField: stringIterableField, boolIterableField: boolIterableField, enumIterableField: enumIterableField, intListField: intListField, doubleListField: doubleListField, stringListField: stringListField, boolListField: boolListField, enumListField: enumListField, intSetField: intSetField, doubleSetField: doubleSetField, stringSetField: stringSetField, boolSetField: boolSetField, enumSetField: enumSetField, ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('IterableRouteWithDefaultValues'), onTap: () => go(context), selected: GoRouterState.of(context).uri.toString() == location, ); } class BasePage<T> extends StatelessWidget { const BasePage({ required this.dataTitle, this.param, this.queryParam, this.queryParamWithDefaultValue, super.key, }); final String dataTitle; final T? param; final T? queryParam; final T? queryParamWithDefaultValue; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: const Text('Go router typed routes'), ), drawer: Drawer( child: ListView( children: <Widget>[ BigIntRoute( requiredBigIntField: BigInt.two, bigIntField: BigInt.zero, ).drawerTile(context), BoolRoute( requiredBoolField: true, boolField: false, ).drawerTile(context), DateTimeRoute( requiredDateTimeField: DateTime(1970), dateTimeField: DateTime(0), ).drawerTile(context), DoubleRoute( requiredDoubleField: 3.14, doubleField: -3.14, ).drawerTile(context), IntRoute( requiredIntField: 42, intField: -42, ).drawerTile(context), NumRoute( requiredNumField: 2.71828, numField: -2.71828, ).drawerTile(context), StringRoute( requiredStringField: r'$!/#bob%%20', stringField: r'$!/#bob%%20', ).drawerTile(context), EnumRoute( requiredEnumField: PersonDetails.favoriteSport, enumField: PersonDetails.favoriteFood, ).drawerTile(context), EnhancedEnumRoute( requiredEnumField: SportDetails.football, enumField: SportDetails.volleyball, ).drawerTile(context), UriRoute( requiredUriField: Uri.parse('https://dart.dev'), uriField: Uri.parse('https://dart.dev'), ).drawerTile(context), IterableRoute( intIterableField: <int>[1, 2, 3], doubleIterableField: <double>[.3, .4, .5], stringIterableField: <String>['quo usque tandem'], boolIterableField: <bool>[true, false, false], enumIterableField: <SportDetails>[ SportDetails.football, SportDetails.hockey, ], intListField: <int>[1, 2, 3], doubleListField: <double>[.3, .4, .5], stringListField: <String>['quo usque tandem'], boolListField: <bool>[true, false, false], enumListField: <SportDetails>[ SportDetails.football, SportDetails.hockey, ], intSetField: <int>{1, 2, 3}, doubleSetField: <double>{.3, .4, .5}, stringSetField: <String>{'quo usque tandem'}, boolSetField: <bool>{true, false}, enumSetField: <SportDetails>{ SportDetails.football, SportDetails.hockey, }, ).drawerTile(context), const IterableRouteWithDefaultValues().drawerTile(context), ], )), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('Built!'), Text(dataTitle), Text('Param: $param'), Text('Query param: $queryParam'), Text( 'Query param with default value: $queryParamWithDefaultValue', ), SelectableText(GoRouterState.of(context).uri.toString()), ], ), ), ); } void main() => runApp(AllTypesApp()); class AllTypesApp extends StatelessWidget { AllTypesApp({super.key}); @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, ); late final GoRouter _router = GoRouter( debugLogDiagnostics: true, routes: $appRoutes, initialLocation: const AllTypesBaseRoute().location, ); } class IterablePage extends StatelessWidget { const IterablePage({ required this.dataTitle, this.intIterableField, this.doubleIterableField, this.stringIterableField, this.boolIterableField, this.enumIterableField, this.intListField, this.doubleListField, this.stringListField, this.boolListField, this.enumListField, this.intSetField, this.doubleSetField, this.stringSetField, this.boolSetField, this.enumSetField, super.key, }); final String dataTitle; final Iterable<int>? intIterableField; final List<int>? intListField; final Set<int>? intSetField; final Iterable<double>? doubleIterableField; final List<double>? doubleListField; final Set<double>? doubleSetField; final Iterable<String>? stringIterableField; final List<String>? stringListField; final Set<String>? stringSetField; final Iterable<bool>? boolIterableField; final List<bool>? boolListField; final Set<bool>? boolSetField; final Iterable<SportDetails>? enumIterableField; final List<SportDetails>? enumListField; final Set<SportDetails>? enumSetField; @override Widget build(BuildContext context) { return BasePage<String>( dataTitle: dataTitle, queryParamWithDefaultValue: <String, Iterable<dynamic>?>{ 'intIterableField': intIterableField, 'intListField': intListField, 'intSetField': intSetField, 'doubleIterableField': doubleIterableField, 'doubleListField': doubleListField, 'doubleSetField': doubleSetField, 'stringIterableField': stringIterableField, 'stringListField': stringListField, 'stringSetField': stringSetField, 'boolIterableField': boolIterableField, 'boolListField': boolListField, 'boolSetField': boolSetField, 'enumIterableField': enumIterableField, 'enumListField': enumListField, 'enumSetField': enumSetField, }.toString(), ); } }
packages/packages/go_router_builder/example/lib/all_types.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/all_types.dart", "repo_id": "packages", "token_count": 7712 }
971
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'stateful_shell_route_example.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $myShellRouteData, ]; RouteBase get $myShellRouteData => StatefulShellRouteData.$route( restorationScopeId: MyShellRouteData.$restorationScopeId, navigatorContainerBuilder: MyShellRouteData.$navigatorContainerBuilder, factory: $MyShellRouteDataExtension._fromState, branches: [ StatefulShellBranchData.$branch( routes: [ GoRouteData.$route( path: '/detailsA', factory: $DetailsARouteDataExtension._fromState, ), ], ), StatefulShellBranchData.$branch( navigatorKey: BranchBData.$navigatorKey, restorationScopeId: BranchBData.$restorationScopeId, routes: [ GoRouteData.$route( path: '/detailsB', factory: $DetailsBRouteDataExtension._fromState, ), ], ), ], ); extension $MyShellRouteDataExtension on MyShellRouteData { static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } extension $DetailsARouteDataExtension on DetailsARouteData { static DetailsARouteData _fromState(GoRouterState state) => const DetailsARouteData(); String get location => GoRouteData.$location( '/detailsA', ); 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); } extension $DetailsBRouteDataExtension on DetailsBRouteData { static DetailsBRouteData _fromState(GoRouterState state) => const DetailsBRouteData(); String get location => GoRouteData.$location( '/detailsB', ); 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/example/lib/stateful_shell_route_example.g.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/stateful_shell_route_example.g.dart", "repo_id": "packages", "token_count": 883 }
972
// 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:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; /// The name of the generated, private helper for converting [String] to [bool]. const String boolConverterHelperName = r'_$boolConverter'; /// The name of the generated, private helper for handling nullable value /// conversion. const String convertMapValueHelperName = r'_$convertMapValue'; /// The name of the generated, private helper for converting [Duration] to /// [bool]. const String durationDecoderHelperName = r'_$duractionConverter'; /// The name of the generated, private helper for converting [String] to [Enum]. const String enumExtensionHelperName = r'_$fromName'; /// The property/parameter name used to represent the `extra` data that may /// be passed to a route. const String extraFieldName = r'$extra'; /// Shared start of error message related to a likely code issue. const String likelyIssueMessage = 'Should never get here! File an issue!'; const List<_TypeHelper> _helpers = <_TypeHelper>[ _TypeHelperBigInt(), _TypeHelperBool(), _TypeHelperDateTime(), _TypeHelperDouble(), _TypeHelperEnum(), _TypeHelperInt(), _TypeHelperNum(), _TypeHelperString(), _TypeHelperUri(), _TypeHelperIterable(), ]; /// Returns the decoded [String] value for [element], if its type is supported. /// /// Otherwise, throws an [InvalidGenerationSourceError]. String decodeParameter(ParameterElement element, Set<String> pathParameters) { if (element.isExtraField) { return 'state.${_stateValueAccess(element, pathParameters)}'; } final DartType paramType = element.type; for (final _TypeHelper helper in _helpers) { if (helper._matchesType(paramType)) { String decoded = helper._decode(element, pathParameters); if (element.isOptional && element.hasDefaultValue) { if (element.type.isNullableType) { throw NullableDefaultValueError(element); } decoded += ' ?? ${element.defaultValueCode!}'; } return decoded; } } throw InvalidGenerationSourceError( 'The parameter type ' '`${paramType.getDisplayString(withNullability: false)}` is not supported.', element: element, ); } /// Returns the encoded [String] value for [element], if its type is supported. /// /// Otherwise, throws an [InvalidGenerationSourceError]. String encodeField(PropertyAccessorElement element) { for (final _TypeHelper helper in _helpers) { if (helper._matchesType(element.returnType)) { return helper._encode(element.name, element.returnType); } } throw InvalidGenerationSourceError( 'The return type `${element.returnType}` is not supported.', element: element, ); } /// Gets the name of the `const` map generated to help encode [Enum] types. String enumMapName(InterfaceType type) => '_\$${type.element.name}EnumMap'; String _stateValueAccess(ParameterElement element, Set<String> pathParameters) { if (element.isExtraField) { return 'extra as ${element.type.getDisplayString(withNullability: true)}'; } late String access; if (pathParameters.contains(element.name)) { access = 'pathParameters[${escapeDartString(element.name)}]'; } else { access = 'uri.queryParameters[${escapeDartString(element.name.kebab)}]'; } if (pathParameters.contains(element.name) || (!element.type.isNullableType && !element.hasDefaultValue)) { access += '!'; } return access; } abstract class _TypeHelper { const _TypeHelper(); /// Decodes the value from its string representation in the URL. String _decode(ParameterElement parameterElement, Set<String> pathParameters); /// Encodes the value from its string representation in the URL. String _encode(String fieldName, DartType type); bool _matchesType(DartType type); } class _TypeHelperBigInt extends _TypeHelperWithHelper { const _TypeHelperBigInt(); @override String helperName(DartType paramType) => 'BigInt.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => const TypeChecker.fromRuntime(BigInt).isAssignableFromType(type); } class _TypeHelperBool extends _TypeHelperWithHelper { const _TypeHelperBool(); @override String helperName(DartType paramType) => boolConverterHelperName; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => type.isDartCoreBool; } class _TypeHelperDateTime extends _TypeHelperWithHelper { const _TypeHelperDateTime(); @override String helperName(DartType paramType) => 'DateTime.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => const TypeChecker.fromRuntime(DateTime).isAssignableFromType(type); } class _TypeHelperDouble extends _TypeHelperWithHelper { const _TypeHelperDouble(); @override String helperName(DartType paramType) => 'double.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => type.isDartCoreDouble; } class _TypeHelperEnum extends _TypeHelperWithHelper { const _TypeHelperEnum(); @override String helperName(DartType paramType) => '${enumMapName(paramType as InterfaceType)}.$enumExtensionHelperName'; @override String _encode(String fieldName, DartType type) => '${enumMapName(type as InterfaceType)}[$fieldName${type.ensureNotNull}]'; @override bool _matchesType(DartType type) => type.isEnum; } class _TypeHelperInt extends _TypeHelperWithHelper { const _TypeHelperInt(); @override String helperName(DartType paramType) => 'int.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => type.isDartCoreInt; } class _TypeHelperNum extends _TypeHelperWithHelper { const _TypeHelperNum(); @override String helperName(DartType paramType) => 'num.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => type.isDartCoreNum; } class _TypeHelperString extends _TypeHelper { const _TypeHelperString(); @override String _decode( ParameterElement parameterElement, Set<String> pathParameters) => 'state.${_stateValueAccess(parameterElement, pathParameters)}'; @override String _encode(String fieldName, DartType type) => fieldName; @override bool _matchesType(DartType type) => type.isDartCoreString; } class _TypeHelperUri extends _TypeHelperWithHelper { const _TypeHelperUri(); @override String helperName(DartType paramType) => 'Uri.parse'; @override String _encode(String fieldName, DartType type) => '$fieldName${type.ensureNotNull}.toString()'; @override bool _matchesType(DartType type) => const TypeChecker.fromRuntime(Uri).isAssignableFromType(type); } class _TypeHelperIterable extends _TypeHelper { const _TypeHelperIterable(); @override String _decode( ParameterElement parameterElement, Set<String> pathParameters) { if (parameterElement.type is ParameterizedType) { final DartType iterableType = (parameterElement.type as ParameterizedType).typeArguments.first; // get a type converter for values in iterable String entriesTypeDecoder = '(e) => e'; for (final _TypeHelper helper in _helpers) { if (helper._matchesType(iterableType) && helper is _TypeHelperWithHelper) { entriesTypeDecoder = helper.helperName(iterableType); } } // get correct type for iterable String iterableCaster = ''; if (const TypeChecker.fromRuntime(List) .isAssignableFromType(parameterElement.type)) { iterableCaster = '.toList()'; } else if (const TypeChecker.fromRuntime(Set) .isAssignableFromType(parameterElement.type)) { iterableCaster = '.toSet()'; } return ''' state.uri.queryParametersAll[ ${escapeDartString(parameterElement.name.kebab)}] ?.map($entriesTypeDecoder)$iterableCaster'''; } return ''' state.uri.queryParametersAll[${escapeDartString(parameterElement.name.kebab)}]'''; } @override String _encode(String fieldName, DartType type) { final String nullAwareAccess = type.isNullableType ? '?' : ''; if (type is ParameterizedType) { final DartType iterableType = type.typeArguments.first; // get a type encoder for values in iterable String entriesTypeEncoder = ''; for (final _TypeHelper helper in _helpers) { if (helper._matchesType(iterableType)) { entriesTypeEncoder = ''' $nullAwareAccess.map((e) => ${helper._encode('e', iterableType)}).toList()'''; } } return ''' $fieldName$entriesTypeEncoder'''; } return ''' $fieldName$nullAwareAccess.map((e) => e.toString()).toList()'''; } @override bool _matchesType(DartType type) => const TypeChecker.fromRuntime(Iterable).isAssignableFromType(type); } abstract class _TypeHelperWithHelper extends _TypeHelper { const _TypeHelperWithHelper(); String helperName(DartType paramType); @override String _decode( ParameterElement parameterElement, Set<String> pathParameters) { final DartType paramType = parameterElement.type; final String parameterName = parameterElement.name; if (!pathParameters.contains(parameterName) && (paramType.isNullableType || parameterElement.hasDefaultValue)) { return '$convertMapValueHelperName(' '${escapeDartString(parameterName.kebab)}, ' 'state.uri.queryParameters, ' '${helperName(paramType)})'; } return '${helperName(paramType)}' '(state.${_stateValueAccess(parameterElement, pathParameters)})'; } } /// Extension helpers on [DartType]. extension DartTypeExtension on DartType { /// Convenient helper for nullability checks. String get ensureNotNull => isNullableType ? '!' : ''; } /// Extension helpers on [ParameterElement]. extension ParameterElementExtension on ParameterElement { /// Convenient helper on top of [isRequiredPositional] and [isRequiredNamed]. bool get isRequired => isRequiredPositional || isRequiredNamed; /// Returns `true` if `this` has a name that matches [extraFieldName]; bool get isExtraField => name == extraFieldName; } /// An error thrown when a default value is used with a nullable type. class NullableDefaultValueError extends InvalidGenerationSourceError { /// An error thrown when a default value is used with a nullable type. NullableDefaultValueError( Element element, ) : super( 'Default value used with a nullable type. Only non-nullable type can have a default value.', todo: 'Remove the default value or make the type non-nullable.', element: element, ); }
packages/packages/go_router_builder/lib/src/type_helpers.dart/0
{ "file_path": "packages/packages/go_router_builder/lib/src/type_helpers.dart", "repo_id": "packages", "token_count": 3841 }
973
The @TypedGoRoute annotation must have a type parameter that matches the annotated element.
packages/packages/go_router_builder/test_inputs/missing_type_annotation.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/missing_type_annotation.dart.expect", "repo_id": "packages", "token_count": 20 }
974
RouteBase get $nonNullableRequiredParamNotInPath => GoRouteData.$route( path: 'bob', factory: $NonNullableRequiredParamNotInPathExtension._fromState, ); extension $NonNullableRequiredParamNotInPathExtension on NonNullableRequiredParamNotInPath { static NonNullableRequiredParamNotInPath _fromState(GoRouterState state) => NonNullableRequiredParamNotInPath( id: int.parse(state.uri.queryParameters['id']!), ); String get location => GoRouteData.$location( 'bob', queryParams: { 'id': id.toString(), }, ); 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/required_query_parameter.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/required_query_parameter.dart.expect", "repo_id": "packages", "token_count": 312 }
975
# See https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md#arguments override_platforms: chrome: settings: executable: chrome arguments: --no-sandbox
packages/packages/google_identity_services_web/dart_test.yaml/0
{ "file_path": "packages/packages/google_identity_services_web/dart_test.yaml", "repo_id": "packages", "token_count": 74 }
976
# Tests Use `dart run tool/run_tests.dart` to run tests in this package. ## Failed to run Chrome: No such file or directory Ensure the correct path to the Chrome executable is set in `dart_test.yaml`. It may be other than `chrome` (for example, `google-chrome` in my machine).
packages/packages/google_identity_services_web/test/README.md/0
{ "file_path": "packages/packages/google_identity_services_web/test/README.md", "repo_id": "packages", "token_count": 84 }
977
// 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 _mapWithMarkers(Set<Marker> markers) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ); } void main() { late FakeGoogleMapsFlutterPlatform platform; setUp(() { platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('Initializing a marker', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToAdd.length, 1); final Marker initializedMarker = map.markerUpdates.last.markersToAdd.first; expect(initializedMarker, equals(m1)); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToChange.isEmpty, true); }); testWidgets('Adding a marker', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); const Marker m2 = Marker(markerId: MarkerId('marker_2')); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1})); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1, m2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToAdd.length, 1); final Marker addedMarker = map.markerUpdates.last.markersToAdd.first; expect(addedMarker, equals(m2)); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToChange.isEmpty, true); }); testWidgets('Removing a marker', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1})); await tester.pumpWidget(_mapWithMarkers(<Marker>{})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markerIdsToRemove.length, 1); expect(map.markerUpdates.last.markerIdsToRemove.first, equals(m1.markerId)); expect(map.markerUpdates.last.markersToChange.isEmpty, true); expect(map.markerUpdates.last.markersToAdd.isEmpty, true); }); testWidgets('Updating a marker', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); const Marker m2 = Marker(markerId: MarkerId('marker_1'), alpha: 0.5); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1})); await tester.pumpWidget(_mapWithMarkers(<Marker>{m2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange.length, 1); expect(map.markerUpdates.last.markersToChange.first, equals(m2)); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToAdd.isEmpty, true); }); testWidgets('Updating a marker', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); const Marker m2 = Marker( markerId: MarkerId('marker_1'), infoWindow: InfoWindow(snippet: 'changed'), ); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1})); await tester.pumpWidget(_mapWithMarkers(<Marker>{m2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange.length, 1); final Marker update = map.markerUpdates.last.markersToChange.first; expect(update, equals(m2)); expect(update.infoWindow.snippet, 'changed'); }); testWidgets('Multi Update', (WidgetTester tester) async { Marker m1 = const Marker(markerId: MarkerId('marker_1')); Marker m2 = const Marker(markerId: MarkerId('marker_2')); final Set<Marker> prev = <Marker>{m1, m2}; m1 = const Marker(markerId: MarkerId('marker_1'), visible: false); m2 = const Marker(markerId: MarkerId('marker_2'), draggable: true); final Set<Marker> cur = <Marker>{m1, m2}; await tester.pumpWidget(_mapWithMarkers(prev)); await tester.pumpWidget(_mapWithMarkers(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange, cur); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Marker m2 = const Marker(markerId: MarkerId('marker_2')); const Marker m3 = Marker(markerId: MarkerId('marker_3')); final Set<Marker> prev = <Marker>{m2, m3}; // m1 is added, m2 is updated, m3 is removed. const Marker m1 = Marker(markerId: MarkerId('marker_1')); m2 = const Marker(markerId: MarkerId('marker_2'), draggable: true); final Set<Marker> cur = <Marker>{m1, m2}; await tester.pumpWidget(_mapWithMarkers(prev)); await tester.pumpWidget(_mapWithMarkers(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange.length, 1); expect(map.markerUpdates.last.markersToAdd.length, 1); expect(map.markerUpdates.last.markerIdsToRemove.length, 1); expect(map.markerUpdates.last.markersToChange.first, equals(m2)); expect(map.markerUpdates.last.markersToAdd.first, equals(m1)); expect(map.markerUpdates.last.markerIdsToRemove.first, equals(m3.markerId)); }); testWidgets('Partial Update', (WidgetTester tester) async { const Marker m1 = Marker(markerId: MarkerId('marker_1')); const Marker m2 = Marker(markerId: MarkerId('marker_2')); Marker m3 = const Marker(markerId: MarkerId('marker_3')); final Set<Marker> prev = <Marker>{m1, m2, m3}; m3 = const Marker(markerId: MarkerId('marker_3'), draggable: true); final Set<Marker> cur = <Marker>{m1, m2, m3}; await tester.pumpWidget(_mapWithMarkers(prev)); await tester.pumpWidget(_mapWithMarkers(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange, <Marker>{m3}); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToAdd.isEmpty, true); }); testWidgets('Update non platform related attr', (WidgetTester tester) async { Marker m1 = const Marker(markerId: MarkerId('marker_1')); final Set<Marker> prev = <Marker>{m1}; m1 = Marker( markerId: const MarkerId('marker_1'), onTap: () {}, onDragEnd: (LatLng latLng) {}); final Set<Marker> cur = <Marker>{m1}; await tester.pumpWidget(_mapWithMarkers(prev)); await tester.pumpWidget(_mapWithMarkers(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.last.markersToChange.isEmpty, true); expect(map.markerUpdates.last.markerIdsToRemove.isEmpty, true); expect(map.markerUpdates.last.markersToAdd.isEmpty, true); }); testWidgets('multi-update with delays', (WidgetTester tester) async { platform.simulatePlatformDelay = true; const Marker m1 = Marker(markerId: MarkerId('marker_1')); const Marker m2 = Marker(markerId: MarkerId('marker_2')); const Marker m3 = Marker(markerId: MarkerId('marker_3')); const Marker m3updated = Marker(markerId: MarkerId('marker_3'), draggable: true); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithMarkers(<Marker>{m1, m2})); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1, m3})); await tester.pumpWidget(_mapWithMarkers(<Marker>{m1, m3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.markerUpdates.length, 3); expect(map.markerUpdates[0].markersToChange.isEmpty, true); expect(map.markerUpdates[0].markersToAdd, <Marker>{m1, m2}); expect(map.markerUpdates[0].markerIdsToRemove.isEmpty, true); expect(map.markerUpdates[1].markersToChange.isEmpty, true); expect(map.markerUpdates[1].markersToAdd, <Marker>{m3}); expect(map.markerUpdates[1].markerIdsToRemove, <MarkerId>{m2.markerId}); expect(map.markerUpdates[2].markersToChange, <Marker>{m3updated}); expect(map.markerUpdates[2].markersToAdd.isEmpty, true); expect(map.markerUpdates[2].markerIdsToRemove.isEmpty, true); await tester.pumpAndSettle(); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart", "repo_id": "packages", "token_count": 3425 }
978
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.googlemaps; import android.content.Context; import android.graphics.Rect; import androidx.annotation.Nullable; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLngBounds; import io.flutter.plugin.common.BinaryMessenger; import java.util.List; import java.util.Map; class GoogleMapBuilder implements GoogleMapOptionsSink { private final GoogleMapOptions options = new GoogleMapOptions(); private boolean trackCameraPosition = false; private boolean myLocationEnabled = false; private boolean myLocationButtonEnabled = false; private boolean indoorEnabled = true; private boolean trafficEnabled = false; private boolean buildingsEnabled = true; private Object initialMarkers; private Object initialPolygons; private Object initialPolylines; private Object initialCircles; private List<Map<String, ?>> initialTileOverlays; private Rect padding = new Rect(0, 0, 0, 0); private @Nullable String style; GoogleMapController build( int id, Context context, BinaryMessenger binaryMessenger, LifecycleProvider lifecycleProvider) { final GoogleMapController controller = new GoogleMapController(id, context, binaryMessenger, lifecycleProvider, options); controller.init(); controller.setMyLocationEnabled(myLocationEnabled); controller.setMyLocationButtonEnabled(myLocationButtonEnabled); controller.setIndoorEnabled(indoorEnabled); controller.setTrafficEnabled(trafficEnabled); controller.setBuildingsEnabled(buildingsEnabled); controller.setTrackCameraPosition(trackCameraPosition); controller.setInitialMarkers(initialMarkers); controller.setInitialPolygons(initialPolygons); controller.setInitialPolylines(initialPolylines); controller.setInitialCircles(initialCircles); controller.setPadding(padding.top, padding.left, padding.bottom, padding.right); controller.setInitialTileOverlays(initialTileOverlays); controller.setMapStyle(style); return controller; } void setInitialCameraPosition(CameraPosition position) { options.camera(position); } public void setMapId(String mapId) { options.mapId(mapId); } @Override public void setCompassEnabled(boolean compassEnabled) { options.compassEnabled(compassEnabled); } @Override public void setMapToolbarEnabled(boolean setMapToolbarEnabled) { options.mapToolbarEnabled(setMapToolbarEnabled); } @Override public void setCameraTargetBounds(LatLngBounds bounds) { options.latLngBoundsForCameraTarget(bounds); } @Override public void setMapType(int mapType) { options.mapType(mapType); } @Override public void setMinMaxZoomPreference(Float min, Float max) { if (min != null) { options.minZoomPreference(min); } if (max != null) { options.maxZoomPreference(max); } } @Override public void setPadding(float top, float left, float bottom, float right) { this.padding = new Rect((int) left, (int) top, (int) right, (int) bottom); } @Override public void setTrackCameraPosition(boolean trackCameraPosition) { this.trackCameraPosition = trackCameraPosition; } @Override public void setRotateGesturesEnabled(boolean rotateGesturesEnabled) { options.rotateGesturesEnabled(rotateGesturesEnabled); } @Override public void setScrollGesturesEnabled(boolean scrollGesturesEnabled) { options.scrollGesturesEnabled(scrollGesturesEnabled); } @Override public void setTiltGesturesEnabled(boolean tiltGesturesEnabled) { options.tiltGesturesEnabled(tiltGesturesEnabled); } @Override public void setZoomGesturesEnabled(boolean zoomGesturesEnabled) { options.zoomGesturesEnabled(zoomGesturesEnabled); } @Override public void setLiteModeEnabled(boolean liteModeEnabled) { options.liteMode(liteModeEnabled); } @Override public void setIndoorEnabled(boolean indoorEnabled) { this.indoorEnabled = indoorEnabled; } @Override public void setTrafficEnabled(boolean trafficEnabled) { this.trafficEnabled = trafficEnabled; } @Override public void setBuildingsEnabled(boolean buildingsEnabled) { this.buildingsEnabled = buildingsEnabled; } @Override public void setMyLocationEnabled(boolean myLocationEnabled) { this.myLocationEnabled = myLocationEnabled; } @Override public void setZoomControlsEnabled(boolean zoomControlsEnabled) { options.zoomControlsEnabled(zoomControlsEnabled); } @Override public void setMyLocationButtonEnabled(boolean myLocationButtonEnabled) { this.myLocationButtonEnabled = myLocationButtonEnabled; } @Override public void setInitialMarkers(Object initialMarkers) { this.initialMarkers = initialMarkers; } @Override public void setInitialPolygons(Object initialPolygons) { this.initialPolygons = initialPolygons; } @Override public void setInitialPolylines(Object initialPolylines) { this.initialPolylines = initialPolylines; } @Override public void setInitialCircles(Object initialCircles) { this.initialCircles = initialCircles; } @Override public void setInitialTileOverlays(List<Map<String, ?>> initialTileOverlays) { this.initialTileOverlays = initialTileOverlays; } @Override public void setMapStyle(@Nullable String style) { this.style = style; } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapBuilder.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapBuilder.java", "repo_id": "packages", "token_count": 1737 }
979
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.googlemaps; import com.google.android.gms.maps.model.Cap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PatternItem; import com.google.android.gms.maps.model.PolylineOptions; import java.util.List; class PolylineBuilder implements PolylineOptionsSink { private final PolylineOptions polylineOptions; private boolean consumeTapEvents; private final float density; PolylineBuilder(float density) { this.polylineOptions = new PolylineOptions(); this.density = density; } PolylineOptions build() { return polylineOptions; } boolean consumeTapEvents() { return consumeTapEvents; } @Override public void setColor(int color) { polylineOptions.color(color); } @Override public void setEndCap(Cap endCap) { polylineOptions.endCap(endCap); } @Override public void setJointType(int jointType) { polylineOptions.jointType(jointType); } @Override public void setPattern(List<PatternItem> pattern) { polylineOptions.pattern(pattern); } @Override public void setPoints(List<LatLng> points) { polylineOptions.addAll(points); } @Override public void setConsumeTapEvents(boolean consumeTapEvents) { this.consumeTapEvents = consumeTapEvents; polylineOptions.clickable(consumeTapEvents); } @Override public void setGeodesic(boolean geodisc) { polylineOptions.geodesic(geodisc); } @Override public void setStartCap(Cap startCap) { polylineOptions.startCap(startCap); } @Override public void setVisible(boolean visible) { polylineOptions.visible(visible); } @Override public void setWidth(float width) { polylineOptions.width(width * density); } @Override public void setZIndex(float zIndex) { polylineOptions.zIndex(zIndex); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineBuilder.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineBuilder.java", "repo_id": "packages", "token_count": 652 }
980
// 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.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import com.google.android.gms.internal.maps.zzag; import com.google.android.gms.maps.model.Polygon; import org.junit.Test; import org.mockito.Mockito; public class PolygonControllerTest { @Test public void controller_SetsStrokeDensity() { final zzag z = mock(zzag.class); final Polygon polygon = spy(new Polygon(z)); final float density = 5; final float strokeWidth = 3; final PolygonController controller = new PolygonController(polygon, false, density); controller.setStrokeWidth(strokeWidth); Mockito.verify(polygon).setStrokeWidth(density * strokeWidth); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolygonControllerTest.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolygonControllerTest.java", "repo_id": "packages", "token_count": 294 }
981
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; import 'google_maps_tests.dart' show googleMapsTests; void main() { late AndroidMapRenderer initializedRenderer; IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async { final GoogleMapsFlutterAndroid instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; initializedRenderer = await instance.initializeWithRenderer(AndroidMapRenderer.latest); }); testWidgets('initialized with latest renderer', (WidgetTester _) async { // There is no guarantee that the server will return the latest renderer // even when requested, so there's no way to deterministically test that. // Instead, just test that the request succeeded and returned a valid // value. expect( initializedRenderer == AndroidMapRenderer.latest || initializedRenderer == AndroidMapRenderer.legacy, true); }); testWidgets('throws PlatformException on multiple renderer initializations', (WidgetTester _) async { final GoogleMapsFlutterAndroid instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; expect( () async => instance.initializeWithRenderer(AndroidMapRenderer.latest), throwsA(isA<PlatformException>().having((PlatformException e) => e.code, 'code', 'Renderer already initialized'))); }); // Run tests. googleMapsTests(); }
packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/latest_renderer_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/latest_renderer_test.dart", "repo_id": "packages", "token_count": 603 }
982
## 2.5.1 * Makes the tile overlay callback invoke the platform channel on the platform thread. ## 2.5.0 * Adds support for `MapConfiguration.style`. * Adds support for `getStyleError`. ## 2.4.2 * Fixes a bug in "takeSnapshot" function that incorrectly returns a blank image on iOS 17. ## 2.4.1 * Restores the workaround to exclude arm64 simulator builds, as it is still necessary for applications targeting iOS 12. ## 2.4.0 * Adds support for arm64 simulators. * Updates minimum supported SDK version to Flutter 3.16.6. * Removes support for iOS 11. ## 2.3.6 * Adds privacy manifest. ## 2.3.5 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 2.3.4 * Fixes new lint warnings. ## 2.3.3 * Adds support for version 8 of the Google Maps SDK in apps targeting iOS 14+. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.3.2 * Fixes an issue where the onDragEnd callback for marker is not called. ## 2.3.1 * Adds pub topics to package metadata. ## 2.3.0 * Adds implementation for `cloudMapId` parameter to support cloud-based maps styling. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Fixes unawaited_futures violations. ## 2.2.3 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.2.2 * Sets an upper bound on the `GoogleMaps` SDK version that can be used, to avoid future breakage. ## 2.2.1 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.2.0 * Updates minimum Flutter version to 3.3 and iOS 11. ## 2.1.14 * Updates links for the merge of flutter/plugins into flutter/packages. ## 2.1.13 * Updates code for stricter lint checks. * Updates code for new analysis options. * Re-enable XCUITests: testUserInterface. * Remove unnecessary `RunnerUITests` target from Podfile of the example app. ## 2.1.12 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes violations of new analysis option use_named_constants. * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 2.1.11 * Precaches Google Maps services initialization and syncing. ## 2.1.10 * Splits iOS implementation out of `google_maps_flutter` as a federated implementation.
packages/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md", "repo_id": "packages", "token_count": 718 }
983
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import XCTest; @import GoogleMaps; @import google_maps_flutter_ios; #import <OCMock/OCMock.h> @interface FLTTileProviderControllerTests : XCTestCase @end @implementation FLTTileProviderControllerTests - (void)testCallChannelOnPlatformThread { id channel = OCMClassMock(FlutterMethodChannel.class); FLTTileProviderController *controller = [[FLTTileProviderController alloc] init:channel withTileOverlayIdentifier:@"foo"]; XCTAssertNotNil(controller); XCTestExpectation *expectation = [self expectationWithDescription:@"invokeMethod"]; OCMStub([channel invokeMethod:[OCMArg any] arguments:[OCMArg any] result:[OCMArg any]]) .andDo(^(NSInvocation *invocation) { XCTAssertTrue([[NSThread currentThread] isMainThread]); [expectation fulfill]; }); id receiver = OCMProtocolMock(@protocol(GMSTileReceiver)); [controller requestTileForX:0 y:0 zoom:0 receiver:receiver]; [self waitForExpectations:@[ expectation ] timeout:10.0]; } @end
packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/ios/RunnerTests/FLTTileProviderControllerTests.m/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/ios/RunnerTests/FLTTileProviderControllerTests.m", "repo_id": "packages", "token_count": 435 }
984
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CADisableMinimumFrameDurationOnPhone</key> <true/> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>google_maps_flutter_example</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>NSLocationWhenInUseUsageDescription</key> <string>This app needs your location to test the location feature of the Google Maps plugin.</string> <key>UIApplicationSupportsIndirectInputEvents</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>arm64</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner/Info.plist/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner/Info.plist", "repo_id": "packages", "token_count": 674 }
985
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'page.dart'; /// MapsDemo is the Main Application. class MapsDemo extends StatelessWidget { /// Default Constructor const MapsDemo(this.pages, {super.key}); /// The list of demo pages. final List<GoogleMapExampleAppPage> pages; void _pushPage(BuildContext context, GoogleMapExampleAppPage page) { Navigator.of(context).push(MaterialPageRoute<void>( builder: (_) => Scaffold( appBar: AppBar(title: Text(page.title)), body: page, ))); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('GoogleMaps examples')), body: ListView.builder( itemCount: pages.length, itemBuilder: (_, int index) => ListTile( leading: pages[index].leading, title: Text(pages[index].title), onTap: () => _pushPage(context, pages[index]), ), ), ); } }
packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart", "repo_id": "packages", "token_count": 431 }
986
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'types.dart'; /// A container object for configuration options when building a widget. /// /// This is intended for use as a parameter in platform interface methods, to /// allow adding new configuration options to existing methods. @immutable class MapWidgetConfiguration { /// Creates a new configuration with all the given settings. const MapWidgetConfiguration({ required this.initialCameraPosition, required this.textDirection, this.gestureRecognizers = const <Factory<OneSequenceGestureRecognizer>>{}, }); /// The initial camera position to display. final CameraPosition initialCameraPosition; /// The text direction for the widget. final TextDirection textDirection; /// Gesture recognizers to add to the widget. final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers; }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_widget_configuration.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_widget_configuration.dart", "repo_id": "packages", "token_count": 294 }
987
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'types.dart'; /// Type of map tiles to display. // Enum constants must be indexed to match the corresponding int constants of // the Android platform API, see // <https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#MAP_TYPE_NORMAL> enum MapType { /// Do not display map tiles. none, /// Normal tiles (traffic and labels, subtle terrain information). normal, /// Satellite imaging tiles (aerial photos) satellite, /// Terrain tiles (indicates type and height of terrain) terrain, /// Hybrid tiles (satellite images with some labels/overlays) hybrid, } /// Bounds for the map camera target. // Used with [GoogleMapOptions] to wrap a [LatLngBounds] value. This allows // distinguishing between specifying an unbounded target (null `LatLngBounds`) // from not specifying anything (null `CameraTargetBounds`). @immutable class CameraTargetBounds { /// Creates a camera target bounds with the specified bounding box, or null /// to indicate that the camera target is not bounded. const CameraTargetBounds(this.bounds); /// The geographical bounding box for the map camera target. /// /// A null value means the camera target is unbounded. final LatLngBounds? bounds; /// Unbounded camera target. static const CameraTargetBounds unbounded = CameraTargetBounds(null); /// Converts this object to something serializable in JSON. Object toJson() => <Object?>[bounds?.toJson()]; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is CameraTargetBounds && bounds == other.bounds; } @override int get hashCode => bounds.hashCode; @override String toString() { return 'CameraTargetBounds(bounds: $bounds)'; } } /// Preferred bounds for map camera zoom level. // Used with [GoogleMapOptions] to wrap min and max zoom. This allows // distinguishing between specifying unbounded zooming (null `minZoom` and // `maxZoom`) from not specifying anything (null `MinMaxZoomPreference`). @immutable class MinMaxZoomPreference { /// Creates a immutable representation of the preferred minimum and maximum zoom values for the map camera. /// /// [AssertionError] will be thrown if [minZoom] > [maxZoom]. const MinMaxZoomPreference(this.minZoom, this.maxZoom) : assert(minZoom == null || maxZoom == null || minZoom <= maxZoom); /// The preferred minimum zoom level or null, if unbounded from below. final double? minZoom; /// The preferred maximum zoom level or null, if unbounded from above. final double? maxZoom; /// Unbounded zooming. static const MinMaxZoomPreference unbounded = MinMaxZoomPreference(null, null); /// Converts this object to something serializable in JSON. Object toJson() => <Object?>[minZoom, maxZoom]; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is MinMaxZoomPreference && minZoom == other.minZoom && maxZoom == other.maxZoom; } @override int get hashCode => Object.hash(minZoom, maxZoom); @override String toString() { return 'MinMaxZoomPreference(minZoom: $minZoom, maxZoom: $maxZoom)'; } } /// Exception when a map style is invalid or was unable to be set. /// /// See also: `setStyle` on [GoogleMapController] for why this exception /// might be thrown. class MapStyleException implements Exception { /// Default constructor for [MapStyleException]. const MapStyleException(this.cause); /// The reason `GoogleMapController.setStyle` would throw this exception. final String cause; }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart", "repo_id": "packages", "token_count": 1208 }
988
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$ClusterManager', () { test('constructor defaults', () { const ClusterManager manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); expect(manager.clusterManagerId, const ClusterManagerId('1234')); }); test('toJson', () { const ClusterManager manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final Map<String, Object> json = manager.toJson() as Map<String, Object>; expect(json, <String, Object>{ 'clusterManagerId': '1234', }); }); test('clone', () { const ClusterManager manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final ClusterManager clone = manager.clone(); expect(identical(clone, manager), isFalse); expect(clone, equals(manager)); }); test('copyWith', () { const ClusterManager manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final List<String> log = <String>[]; final ClusterManager copy = manager.copyWith( onClusterTapParam: (Cluster cluster) { log.add('onTapParam'); }, ); copy.onClusterTap!(Cluster( manager.clusterManagerId, const <MarkerId>[MarkerId('5678')], position: const LatLng(11.0, 22.0), bounds: LatLngBounds( southwest: const LatLng(22.0, 33.0), northeast: const LatLng(33.0, 88.0)))); expect(log, contains('onTapParam')); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart", "repo_id": "packages", "token_count": 736 }
989
# google_maps_flutter_web The web implementation of [google_maps_flutter](https://pub.dev/packages/google_maps_flutter). Powered by [a14n](https://github.com/a14n)'s [google_maps](https://pub.dev/packages/google_maps) Dart JS interop layer. ## Usage This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin), which means you can simply use `google_maps_flutter` 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. ### Modify web/index.html Get an API Key for Google Maps JavaScript API. Get started [here](https://developers.google.com/maps/documentation/javascript/get-api-key). Modify the `<head>` tag of your `web/index.html` to load the Google Maps JavaScript API, like so: ```html <head> <!-- // Other stuff --> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> </head> ``` The Google Maps Web SDK splits some of its functionality in [separate libraries](https://developers.google.com/maps/documentation/javascript/libraries#libraries-for-dynamic-library-import). If your app needs the `drawing` library (to draw polygons, rectangles, polylines, circles or markers on a map), include it like this: ```html <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing"> </script> ``` To request multiple libraries, separate them with commas: ```html <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing,visualization,places"> </script> ``` Now you should be able to use the Google Maps plugin normally. ## Limitations of the web version The following map options are not available in web, because the map doesn't rotate there: * `compassEnabled` * `rotateGesturesEnabled` * `tiltGesturesEnabled` There's no "Map Toolbar" in web, so the `mapToolbarEnabled` option is unused. There's no "My Location" widget in web ([tracking issue](https://github.com/flutter/flutter/issues/64073)), so the following options are ignored, for now: * `myLocationButtonEnabled` * `myLocationEnabled` There's no `defaultMarkerWithHue` in web. If you need colored pins/markers, you may need to use your own asset images. Indoor and building layers are still not available on the web. Traffic is. Only Android supports "[Lite Mode](https://developers.google.com/maps/documentation/android-sdk/lite)", so the `liteModeEnabled` constructor argument can't be set to `true` on web apps. Google Maps for web uses `HtmlElementView` to render maps. When a `GoogleMap` is stacked below other widgets, [`package:pointer_interceptor`](https://www.pub.dev/packages/pointer_interceptor) must be used to capture mouse events on the Flutter overlays. See issue [#73830](https://github.com/flutter/flutter/issues/73830).
packages/packages/google_maps_flutter/google_maps_flutter_web/README.md/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/README.md", "repo_id": "packages", "token_count": 911 }
990
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of '../google_maps_flutter_web.dart'; /// This wraps a [TileOverlay] in a [gmaps.MapType]. class TileOverlayController { /// Creates a `TileOverlayController` that wraps a [TileOverlay] object and its corresponding [gmaps.MapType]. TileOverlayController({ required TileOverlay tileOverlay, }) { update(tileOverlay); } /// The size in pixels of the (square) tiles passed to the Maps SDK. /// /// Even though the web supports any size, and rectangular tiles, for /// for consistency with mobile, this is not configurable on the web. /// (Both Android and iOS prefer square 256px tiles @ 1x DPI) /// /// For higher DPI screens, the Tile that is actually returned can be larger /// than 256px square. static const int logicalTileSize = 256; /// Updates the [gmaps.MapType] and cached properties with an updated /// [TileOverlay]. void update(TileOverlay tileOverlay) { _tileOverlay = tileOverlay; _gmMapType = gmaps.MapType() ..tileSize = gmaps.Size(logicalTileSize, logicalTileSize) ..getTile = _getTile; } /// Renders a Tile for gmaps; delegating to the configured [TileProvider]. HTMLElement? _getTile( gmaps.Point? tileCoord, num? zoom, Document? ownerDocument, ) { if (_tileOverlay.tileProvider == null) { return null; } final HTMLImageElement img = ownerDocument!.createElement('img') as HTMLImageElement; img.width = img.height = logicalTileSize; img.hidden = true.toJS; img.setAttribute('decoding', 'async'); _tileOverlay.tileProvider! .getTile(tileCoord!.x!.toInt(), tileCoord.y!.toInt(), zoom?.toInt()) .then((Tile tile) { if (tile.data == null) { return; } // Using img lets us take advantage of native decoding. final String src = URL.createObjectURL( Blob(<JSUint8Array>[tile.data!.toJS].toJS) as JSObject, ); img.src = src; img.onload = (JSAny? _) { img.hidden = false.toJS; URL.revokeObjectURL(src); }.toJS; }); return img; } /// The [gmaps.MapType] produced by this controller. gmaps.MapType get gmMapType => _gmMapType; late gmaps.MapType _gmMapType; /// The [TileOverlay] providing data for this controller. TileOverlay get tileOverlay => _tileOverlay; late TileOverlay _tileOverlay; }
packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart", "repo_id": "packages", "token_count": 893 }
991
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/google_sign_in/google_sign_in/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
992
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon #import "messages.g.h" #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSArray *wrapResult(id result, FlutterError *error) { if (error) { return @[ error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] ]; } return @[ result ?: [NSNull null] ]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @interface FSIInitParams () + (FSIInitParams *)fromList:(NSArray *)list; + (nullable FSIInitParams *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FSIUserData () + (FSIUserData *)fromList:(NSArray *)list; + (nullable FSIUserData *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FSITokenData () + (FSITokenData *)fromList:(NSArray *)list; + (nullable FSITokenData *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @implementation FSIInitParams + (instancetype)makeWithScopes:(NSArray<NSString *> *)scopes hostedDomain:(nullable NSString *)hostedDomain clientId:(nullable NSString *)clientId serverClientId:(nullable NSString *)serverClientId { FSIInitParams *pigeonResult = [[FSIInitParams alloc] init]; pigeonResult.scopes = scopes; pigeonResult.hostedDomain = hostedDomain; pigeonResult.clientId = clientId; pigeonResult.serverClientId = serverClientId; return pigeonResult; } + (FSIInitParams *)fromList:(NSArray *)list { FSIInitParams *pigeonResult = [[FSIInitParams alloc] init]; pigeonResult.scopes = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.scopes != nil, @""); pigeonResult.hostedDomain = GetNullableObjectAtIndex(list, 1); pigeonResult.clientId = GetNullableObjectAtIndex(list, 2); pigeonResult.serverClientId = GetNullableObjectAtIndex(list, 3); return pigeonResult; } + (nullable FSIInitParams *)nullableFromList:(NSArray *)list { return (list) ? [FSIInitParams fromList:list] : nil; } - (NSArray *)toList { return @[ (self.scopes ?: [NSNull null]), (self.hostedDomain ?: [NSNull null]), (self.clientId ?: [NSNull null]), (self.serverClientId ?: [NSNull null]), ]; } @end @implementation FSIUserData + (instancetype)makeWithDisplayName:(nullable NSString *)displayName email:(NSString *)email userId:(NSString *)userId photoUrl:(nullable NSString *)photoUrl serverAuthCode:(nullable NSString *)serverAuthCode idToken:(nullable NSString *)idToken { FSIUserData *pigeonResult = [[FSIUserData alloc] init]; pigeonResult.displayName = displayName; pigeonResult.email = email; pigeonResult.userId = userId; pigeonResult.photoUrl = photoUrl; pigeonResult.serverAuthCode = serverAuthCode; pigeonResult.idToken = idToken; return pigeonResult; } + (FSIUserData *)fromList:(NSArray *)list { FSIUserData *pigeonResult = [[FSIUserData alloc] init]; pigeonResult.displayName = GetNullableObjectAtIndex(list, 0); pigeonResult.email = GetNullableObjectAtIndex(list, 1); NSAssert(pigeonResult.email != nil, @""); pigeonResult.userId = GetNullableObjectAtIndex(list, 2); NSAssert(pigeonResult.userId != nil, @""); pigeonResult.photoUrl = GetNullableObjectAtIndex(list, 3); pigeonResult.serverAuthCode = GetNullableObjectAtIndex(list, 4); pigeonResult.idToken = GetNullableObjectAtIndex(list, 5); return pigeonResult; } + (nullable FSIUserData *)nullableFromList:(NSArray *)list { return (list) ? [FSIUserData fromList:list] : nil; } - (NSArray *)toList { return @[ (self.displayName ?: [NSNull null]), (self.email ?: [NSNull null]), (self.userId ?: [NSNull null]), (self.photoUrl ?: [NSNull null]), (self.serverAuthCode ?: [NSNull null]), (self.idToken ?: [NSNull null]), ]; } @end @implementation FSITokenData + (instancetype)makeWithIdToken:(nullable NSString *)idToken accessToken:(nullable NSString *)accessToken { FSITokenData *pigeonResult = [[FSITokenData alloc] init]; pigeonResult.idToken = idToken; pigeonResult.accessToken = accessToken; return pigeonResult; } + (FSITokenData *)fromList:(NSArray *)list { FSITokenData *pigeonResult = [[FSITokenData alloc] init]; pigeonResult.idToken = GetNullableObjectAtIndex(list, 0); pigeonResult.accessToken = GetNullableObjectAtIndex(list, 1); return pigeonResult; } + (nullable FSITokenData *)nullableFromList:(NSArray *)list { return (list) ? [FSITokenData fromList:list] : nil; } - (NSArray *)toList { return @[ (self.idToken ?: [NSNull null]), (self.accessToken ?: [NSNull null]), ]; } @end @interface FSIGoogleSignInApiCodecReader : FlutterStandardReader @end @implementation FSIGoogleSignInApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FSIInitParams fromList:[self readValue]]; case 129: return [FSITokenData fromList:[self readValue]]; case 130: return [FSIUserData fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FSIGoogleSignInApiCodecWriter : FlutterStandardWriter @end @implementation FSIGoogleSignInApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FSIInitParams class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FSITokenData class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FSIUserData class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FSIGoogleSignInApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FSIGoogleSignInApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FSIGoogleSignInApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FSIGoogleSignInApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FSIGoogleSignInApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FSIGoogleSignInApiCodecReaderWriter *readerWriter = [[FSIGoogleSignInApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void FSIGoogleSignInApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FSIGoogleSignInApi> *api) { /// Initializes a sign in request with the given parameters. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.init" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(initializeSignInWithParameters:error:)], @"FSIGoogleSignInApi api (%@) doesn't respond to " @"@selector(initializeSignInWithParameters:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FSIInitParams *arg_params = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api initializeSignInWithParameters:arg_params error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Starts a silent sign in. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signInSilently" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(signInSilentlyWithCompletion:)], @"FSIGoogleSignInApi api (%@) doesn't respond to " @"@selector(signInSilentlyWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api signInSilentlyWithCompletion:^(FSIUserData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Starts a sign in with user interaction. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signIn" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(signInWithCompletion:)], @"FSIGoogleSignInApi api (%@) doesn't respond to @selector(signInWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api signInWithCompletion:^(FSIUserData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Requests the access token for the current sign in. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.getAccessToken" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(getAccessTokenWithCompletion:)], @"FSIGoogleSignInApi api (%@) doesn't respond to " @"@selector(getAccessTokenWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api getAccessTokenWithCompletion:^(FSITokenData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Signs out the current user. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signOut" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(signOutWithError:)], @"FSIGoogleSignInApi api (%@) doesn't respond to @selector(signOutWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api signOutWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Revokes scope grants to the application. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.disconnect" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(disconnectWithCompletion:)], @"FSIGoogleSignInApi api (%@) doesn't respond to @selector(disconnectWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api disconnectWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns whether the user is currently signed in. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.isSignedIn" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(isSignedInWithError:)], @"FSIGoogleSignInApi api (%@) doesn't respond to @selector(isSignedInWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; NSNumber *output = [api isSignedInWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Requests access to the given scopes. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.requestScopes" binaryMessenger:binaryMessenger codec:FSIGoogleSignInApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(requestScopes:completion:)], @"FSIGoogleSignInApi api (%@) doesn't respond to @selector(requestScopes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<NSString *> *arg_scopes = GetNullableObjectAtIndex(args, 0); [api requestScopes:arg_scopes completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } }
packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/messages.g.m/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/messages.g.m", "repo_id": "packages", "token_count": 5735 }
993
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart' show PlatformException; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:google_sign_in_web/google_sign_in_web.dart'; import 'package:google_sign_in_web/src/gis_client.dart'; import 'package:google_sign_in_web/src/people.dart'; import 'package:integration_test/integration_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart' as mockito; import 'package:web/web.dart' as web; import 'google_sign_in_web_test.mocks.dart'; import 'src/person.dart'; // Mock GisSdkClient so we can simulate any response from the JS side. @GenerateMocks(<Type>[], customMocks: <MockSpec<dynamic>>[ MockSpec<GisSdkClient>(onMissingStub: OnMissingStub.returnDefault), ]) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('Constructor', () { const String expectedClientId = '3xp3c73d_c113n7_1d'; testWidgets('Loads clientId when set in a meta', (_) async { final GoogleSignInPlugin plugin = GoogleSignInPlugin( debugOverrideLoader: true, ); expect(plugin.autoDetectedClientId, isNull); // Add it to the test page now, and try again final web.HTMLMetaElement meta = web.document.createElement('meta') as web.HTMLMetaElement ..name = clientIdMetaName ..content = expectedClientId; web.document.head!.appendChild(meta); final GoogleSignInPlugin another = GoogleSignInPlugin( debugOverrideLoader: true, ); expect(another.autoDetectedClientId, expectedClientId); // cleanup meta.remove(); }); }); group('initWithParams', () { late GoogleSignInPlugin plugin; late MockGisSdkClient mockGis; setUp(() { mockGis = MockGisSdkClient(); plugin = GoogleSignInPlugin( debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis, ); }); testWidgets('initializes if all is OK', (_) async { await plugin.initWithParams( const SignInInitParameters( clientId: 'some-non-null-client-id', scopes: <String>['ok1', 'ok2', 'ok3'], ), ); expect(plugin.initialized, completes); }); testWidgets('asserts clientId is not null', (_) async { expect(() async { await plugin.initWithParams( const SignInInitParameters(), ); }, throwsAssertionError); }); testWidgets('asserts serverClientId must be null', (_) async { expect(() async { await plugin.initWithParams( const SignInInitParameters( clientId: 'some-non-null-client-id', serverClientId: 'unexpected-non-null-client-id', ), ); }, throwsAssertionError); }); testWidgets('asserts no scopes have any spaces', (_) async { expect(() async { await plugin.initWithParams( const SignInInitParameters( clientId: 'some-non-null-client-id', scopes: <String>['ok1', 'ok2', 'not ok', 'ok3'], ), ); }, throwsAssertionError); }); testWidgets('must be called for most of the API to work', (_) async { expect(() async { await plugin.signInSilently(); }, throwsStateError); expect(() async { await plugin.signIn(); }, throwsStateError); expect(() async { await plugin.getTokens(email: ''); }, throwsStateError); expect(() async { await plugin.signOut(); }, throwsStateError); expect(() async { await plugin.disconnect(); }, throwsStateError); expect(() async { await plugin.isSignedIn(); }, throwsStateError); expect(() async { await plugin.clearAuthCache(token: ''); }, throwsStateError); expect(() async { await plugin.requestScopes(<String>[]); }, throwsStateError); expect(() async { await plugin.canAccessScopes(<String>[]); }, throwsStateError); }); }); group('(with mocked GIS)', () { late GoogleSignInPlugin plugin; late MockGisSdkClient mockGis; const SignInInitParameters options = SignInInitParameters( clientId: 'some-non-null-client-id', scopes: <String>['ok1', 'ok2', 'ok3'], ); setUp(() { mockGis = MockGisSdkClient(); plugin = GoogleSignInPlugin( debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis, ); }); group('signInSilently', () { setUp(() { plugin.initWithParams(options); }); testWidgets('returns the GIS response', (_) async { final GoogleSignInUserData someUser = extractUserData(person)!; mockito .when(mockGis.signInSilently()) .thenAnswer((_) => Future<GoogleSignInUserData?>.value(someUser)); expect(await plugin.signInSilently(), someUser); mockito .when(mockGis.signInSilently()) .thenAnswer((_) => Future<GoogleSignInUserData?>.value()); expect(await plugin.signInSilently(), isNull); }); }); group('signIn', () { setUp(() { plugin.initWithParams(options); }); testWidgets('returns the signed-in user', (_) async { final GoogleSignInUserData someUser = extractUserData(person)!; mockito .when(mockGis.signIn()) .thenAnswer((_) => Future<GoogleSignInUserData>.value(someUser)); expect(await plugin.signIn(), someUser); }); testWidgets('returns null if no user is signed in', (_) async { mockito .when(mockGis.signIn()) .thenAnswer((_) => Future<GoogleSignInUserData?>.value()); expect(await plugin.signIn(), isNull); }); testWidgets('converts inner errors to PlatformException', (_) async { mockito.when(mockGis.signIn()).thenThrow('popup_closed'); try { await plugin.signIn(); fail('signIn should have thrown an exception'); } catch (exception) { expect(exception, isA<PlatformException>()); expect((exception as PlatformException).code, 'popup_closed'); } }); }); group('canAccessScopes', () { const String someAccessToken = '50m3_4cc35_70k3n'; const List<String> scopes = <String>['scope1', 'scope2']; setUp(() { plugin.initWithParams(options); }); testWidgets('passes-through call to gis client', (_) async { mockito .when( mockGis.canAccessScopes(mockito.captureAny, mockito.captureAny), ) .thenAnswer((_) => Future<bool>.value(true)); final bool canAccess = await plugin.canAccessScopes(scopes, accessToken: someAccessToken); final List<Object?> arguments = mockito .verify( mockGis.canAccessScopes(mockito.captureAny, mockito.captureAny), ) .captured; expect(canAccess, isTrue); expect(arguments.first, scopes); expect(arguments.elementAt(1), someAccessToken); }); }); group('requestServerAuthCode', () { const String someAuthCode = '50m3_4u7h_c0d3'; setUp(() { plugin.initWithParams(options); }); testWidgets('passes-through call to gis client', (_) async { mockito .when(mockGis.requestServerAuthCode()) .thenAnswer((_) => Future<String>.value(someAuthCode)); final String? serverAuthCode = await plugin.requestServerAuthCode(); expect(serverAuthCode, someAuthCode); }); }); }); group('userDataEvents', () { final StreamController<GoogleSignInUserData?> controller = StreamController<GoogleSignInUserData?>.broadcast(); late GoogleSignInPlugin plugin; setUp(() { plugin = GoogleSignInPlugin( debugOverrideLoader: true, debugOverrideUserDataController: controller, ); }); testWidgets('accepts async user data events from GIS.', (_) async { final Future<GoogleSignInUserData?> data = plugin.userDataEvents!.first; final GoogleSignInUserData expected = extractUserData(person)!; controller.add(expected); expect(await data, expected, reason: 'Sign-in events should be propagated'); final Future<GoogleSignInUserData?> more = plugin.userDataEvents!.first; controller.add(null); expect(await more, isNull, reason: 'Sign-out events can also be propagated'); }); }); }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart", "repo_id": "packages", "token_count": 3680 }
994
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:google_identity_services_web/id.dart' as id; /// Converts user-facing `GisButtonConfiguration` into the JS-Interop `id.GsiButtonConfiguration`. id.GsiButtonConfiguration? convertButtonConfiguration( GSIButtonConfiguration? config, ) { if (config == null) { return null; } return id.GsiButtonConfiguration( type: _idType[config.type], theme: _idTheme[config.theme], size: _idSize[config.size], text: _idText[config.text], shape: _idShape[config.shape], logo_alignment: _idLogoAlignment[config.logoAlignment], width: config.minimumWidth, locale: config.locale, ); } /// A class to configure the Google Sign-In Button for web. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#GsiButtonConfiguration class GSIButtonConfiguration { /// Constructs a button configuration object. GSIButtonConfiguration({ this.type, this.theme, this.size, this.text, this.shape, this.logoAlignment, this.minimumWidth, this.locale, }) : assert(minimumWidth == null || minimumWidth > 0); /// The button type: icon, or standard button. final GSIButtonType? type; /// The button theme. /// /// For example, filledBlue or filledBlack. final GSIButtonTheme? theme; /// The button size. /// /// For example, small or large. final GSIButtonSize? size; /// The button text. /// /// For example "Sign in with Google" or "Sign up with Google". final GSIButtonText? text; /// The button shape. /// /// For example, rectangular or circular. final GSIButtonShape? shape; /// The Google logo alignment: left or center. final GSIButtonLogoAlignment? logoAlignment; /// The minimum button width, in pixels. /// /// The maximum width is 400 pixels. final double? minimumWidth; /// The pre-set locale of the button text. /// /// If not set, the browser's default locale or the Google session user's /// preference is used. /// /// Different users might see different versions of localized buttons, possibly /// with different sizes. final String? locale; } /// The type of button to be rendered. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#type enum GSIButtonType { /// A button with text or personalized information. standard, /// An icon button without text. icon; } const Map<GSIButtonType, id.ButtonType> _idType = <GSIButtonType, id.ButtonType>{ GSIButtonType.icon: id.ButtonType.icon, GSIButtonType.standard: id.ButtonType.standard, }; /// The theme of the button to be rendered. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#theme enum GSIButtonTheme { /// A standard button theme. outline, /// A blue-filled button theme. filledBlue, /// A black-filled button theme. filledBlack; } const Map<GSIButtonTheme, id.ButtonTheme> _idTheme = <GSIButtonTheme, id.ButtonTheme>{ GSIButtonTheme.outline: id.ButtonTheme.outline, GSIButtonTheme.filledBlue: id.ButtonTheme.filled_blue, GSIButtonTheme.filledBlack: id.ButtonTheme.filled_black, }; /// The size of the button to be rendered. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#size enum GSIButtonSize { /// A large button (about 40px tall). large, /// A medium-sized button (about 32px tall). medium, /// A small button (about 20px tall). small; } const Map<GSIButtonSize, id.ButtonSize> _idSize = <GSIButtonSize, id.ButtonSize>{ GSIButtonSize.large: id.ButtonSize.large, GSIButtonSize.medium: id.ButtonSize.medium, GSIButtonSize.small: id.ButtonSize.small, }; /// The button text. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#text enum GSIButtonText { /// The button text is "Sign in with Google". signinWith, /// The button text is "Sign up with Google". signupWith, /// The button text is "Continue with Google". continueWith, /// The button text is "Sign in". signin; } const Map<GSIButtonText, id.ButtonText> _idText = <GSIButtonText, id.ButtonText>{ GSIButtonText.signinWith: id.ButtonText.signin_with, GSIButtonText.signupWith: id.ButtonText.signup_with, GSIButtonText.continueWith: id.ButtonText.continue_with, GSIButtonText.signin: id.ButtonText.signin, }; /// The button shape. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#shape enum GSIButtonShape { /// The rectangular-shaped button. rectangular, /// The circle-shaped button. pill; // Does this need circle and square? } const Map<GSIButtonShape, id.ButtonShape> _idShape = <GSIButtonShape, id.ButtonShape>{ GSIButtonShape.rectangular: id.ButtonShape.rectangular, GSIButtonShape.pill: id.ButtonShape.pill, }; /// The alignment of the Google logo. The default value is left. This attribute only applies to the standard button type. /// /// See: /// * https://developers.google.com/identity/gsi/web/reference/js-reference#logo_alignment enum GSIButtonLogoAlignment { /// Left-aligns the Google logo. left, /// Center-aligns the Google logo. center; } const Map<GSIButtonLogoAlignment, id.ButtonLogoAlignment> _idLogoAlignment = <GSIButtonLogoAlignment, id.ButtonLogoAlignment>{ GSIButtonLogoAlignment.left: id.ButtonLogoAlignment.left, GSIButtonLogoAlignment.center: id.ButtonLogoAlignment.center, };
packages/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart", "repo_id": "packages", "token_count": 1833 }
995
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.imagepickerexample; import android.content.ContentProvider; import android.content.ContentValues; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.MediaStore; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class DummyContentProvider extends ContentProvider { @Override public boolean onCreate() { return true; } @Nullable @Override public AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode) { return getContext().getResources().openRawResourceFd(R.raw.ic_launcher); } @Nullable @Override public Cursor query( @NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { MatrixCursor cursor = new MatrixCursor(new String[] {MediaStore.MediaColumns.DISPLAY_NAME}); cursor.addRow(new Object[] {"dummy.png"}); return cursor; } @Nullable @Override public String getType(@NonNull Uri uri) { return "image/png"; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete( @NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update( @NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } }
packages/packages/image_picker/image_picker_android/example/android/app/src/main/java/io/flutter/plugins/imagepickerexample/DummyContentProvider.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/example/android/app/src/main/java/io/flutter/plugins/imagepickerexample/DummyContentProvider.java", "repo_id": "packages", "token_count": 589 }
996
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'src/messages.g.dart'; /// An Android implementation of [ImagePickerPlatform]. class ImagePickerAndroid extends ImagePickerPlatform { /// Creates a new plugin implementation instance. ImagePickerAndroid({@visibleForTesting ImagePickerApi? api}) : _hostApi = api ?? ImagePickerApi(); final ImagePickerApi _hostApi; /// Sets [ImagePickerAndroid] to use Android 13 Photo Picker. /// /// Currently defaults to false, but the default is subject to change. bool useAndroidPhotoPicker = false; /// Registers this class as the default platform implementation. static void registerWith() { ImagePickerPlatform.instance = ImagePickerAndroid(); } @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } @override Future<List<PickedFile>?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic> paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths.isEmpty) { return null; } return paths.map((dynamic path) => PickedFile(path as String)).toList(); } Future<List<dynamic>> _getMultiImagePath({ double? maxWidth, double? maxHeight, int? imageQuality, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return _hostApi.pickImages( SourceSpecification(type: SourceType.gallery), ImageSelectionOptions( maxWidth: maxWidth, maxHeight: maxHeight, quality: imageQuality ?? 100), GeneralOptions( allowMultiple: true, usePhotoPicker: useAndroidPhotoPicker), ); } Future<String?> _getImagePath({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, bool requestFullMetadata = true, }) async { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } final List<String?> paths = await _hostApi.pickImages( _buildSourceSpec(source, preferredCameraDevice), ImageSelectionOptions( maxWidth: maxWidth, maxHeight: maxHeight, quality: imageQuality ?? 100), GeneralOptions( allowMultiple: false, usePhotoPicker: useAndroidPhotoPicker, ), ); return paths.isEmpty ? null : paths.first; } @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } Future<String?> _getVideoPath({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final List<String?> paths = await _hostApi.pickVideos( _buildSourceSpec(source, preferredCameraDevice), VideoSelectionOptions(maxDurationSeconds: maxDuration?.inSeconds), GeneralOptions( allowMultiple: false, usePhotoPicker: useAndroidPhotoPicker, ), ); return paths.isEmpty ? null : paths.first; } @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { final String? path = await _getImagePath( source: source, maxHeight: options.maxHeight, maxWidth: options.maxWidth, imageQuality: options.imageQuality, preferredCameraDevice: options.preferredCameraDevice, requestFullMetadata: options.requestFullMetadata, ); return path != null ? XFile(path) : null; } @override Future<List<XFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic> paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths.isEmpty) { return null; } return paths.map((dynamic path) => XFile(path as String)).toList(); } @override Future<List<XFile>> getMedia({ required MediaOptions options, }) async { return (await _hostApi.pickMedia( _mediaOptionsToMediaSelectionOptions(options), GeneralOptions( allowMultiple: options.allowMultiple, usePhotoPicker: useAndroidPhotoPicker, ), )) .map((String? path) => XFile(path!)) .toList(); } @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } MediaSelectionOptions _mediaOptionsToMediaSelectionOptions( MediaOptions mediaOptions) { final ImageSelectionOptions imageSelectionOptions = _imageOptionsToImageSelectionOptionsWithValidator( mediaOptions.imageOptions); return MediaSelectionOptions( imageSelectionOptions: imageSelectionOptions, ); } ImageSelectionOptions _imageOptionsToImageSelectionOptionsWithValidator( ImageOptions? imageOptions) { final double? maxHeight = imageOptions?.maxHeight; final double? maxWidth = imageOptions?.maxWidth; final int? imageQuality = imageOptions?.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return ImageSelectionOptions( quality: imageQuality ?? 100, maxHeight: maxHeight, maxWidth: maxWidth); } @override Future<LostData> retrieveLostData() async { final LostDataResponse result = await getLostData(); if (result.isEmpty) { return LostData.empty(); } return LostData( file: result.file != null ? PickedFile(result.file!.path) : null, exception: result.exception, type: result.type, ); } @override Future<LostDataResponse> getLostData() async { final CacheRetrievalResult? result = await _hostApi.retrieveLostResults(); if (result == null) { return LostDataResponse.empty(); } // There must either be data or an error if the response wasn't null. assert(result.paths.isEmpty != (result.error == null)); final CacheRetrievalError? error = result.error; final PlatformException? exception = error == null ? null : PlatformException(code: error.code, message: error.message); // Entries are guaranteed not to be null, even though that's not currently // expressible in Pigeon. final List<XFile> pickedFileList = result.paths.map((String? path) => XFile(path!)).toList(); return LostDataResponse( file: pickedFileList.isEmpty ? null : pickedFileList.last, exception: exception, type: _retrieveTypeForCacheType(result.type), files: pickedFileList, ); } SourceSpecification _buildSourceSpec( ImageSource source, CameraDevice device) { return SourceSpecification( type: _sourceSpecTypeForSource(source), camera: _sourceSpecCameraForDevice(device)); } SourceType _sourceSpecTypeForSource(ImageSource source) { switch (source) { case ImageSource.camera: return SourceType.camera; case ImageSource.gallery: return SourceType.gallery; } // The enum comes from a different package, which could get a new value at // any time, so provide a fallback that ensures this won't break when used // with a version that contains new values. This is deliberately outside // the switch rather than a `default` so that the linter will flag the // switch as needing an update. // ignore: dead_code return SourceType.gallery; } SourceCamera _sourceSpecCameraForDevice(CameraDevice device) { switch (device) { case CameraDevice.front: return SourceCamera.front; case CameraDevice.rear: return SourceCamera.rear; } // The enum comes from a different package, which could get a new value at // any time, so provide a fallback that ensures this won't break when used // with a version that contains new values. This is deliberately outside // the switch rather than a `default` so that the linter will flag the // switch as needing an update. // ignore: dead_code return SourceCamera.rear; } RetrieveType _retrieveTypeForCacheType(CacheRetrievalType type) { switch (type) { case CacheRetrievalType.image: return RetrieveType.image; case CacheRetrievalType.video: return RetrieveType.video; } // The enum comes from a different package, which could get a new value at // any time, so provide a fallback that ensures this won't break when used // with a version that contains new values. This is deliberately outside // the switch rather than a `default` so that the linter will flag the // switch as needing an update. // ignore: dead_code return RetrieveType.image; } }
packages/packages/image_picker/image_picker_android/lib/image_picker_android.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_android/lib/image_picker_android.dart", "repo_id": "packages", "token_count": 4034 }
997
// 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 "FLTImagePickerMetaDataUtil.h" #import <Photos/Photos.h> static const uint8_t kFirstByteJPEG = 0xFF; static const uint8_t kFirstBytePNG = 0x89; static const uint8_t kFirstByteGIF = 0x47; NSString *const kFLTImagePickerDefaultSuffix = @".jpg"; const FLTImagePickerMIMEType kFLTImagePickerMIMETypeDefault = FLTImagePickerMIMETypeJPEG; @implementation FLTImagePickerMetaDataUtil + (FLTImagePickerMIMEType)getImageMIMETypeFromImageData:(NSData *)imageData { uint8_t firstByte; [imageData getBytes:&firstByte length:1]; switch (firstByte) { case kFirstByteJPEG: return FLTImagePickerMIMETypeJPEG; case kFirstBytePNG: return FLTImagePickerMIMETypePNG; case kFirstByteGIF: return FLTImagePickerMIMETypeGIF; } return FLTImagePickerMIMETypeOther; } + (NSString *)imageTypeSuffixFromType:(FLTImagePickerMIMEType)type { switch (type) { case FLTImagePickerMIMETypeJPEG: return @".jpg"; case FLTImagePickerMIMETypePNG: return @".png"; case FLTImagePickerMIMETypeGIF: return @".gif"; default: return nil; } } + (NSDictionary *)getMetaDataFromImageData:(NSData *)imageData { CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); NSDictionary *metadata = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source, 0, NULL)); CFRelease(source); return metadata; } + (NSData *)imageFromImage:(NSData *)imageData withMetaData:(NSDictionary *)metadata { NSMutableData *targetData = [NSMutableData data]; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); if (source == NULL) { return nil; } CGImageDestinationRef destination = NULL; CFStringRef sourceType = CGImageSourceGetType(source); if (sourceType != NULL) { destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)targetData, sourceType, 1, nil); } if (destination == NULL) { CFRelease(source); return nil; } CGImageDestinationAddImageFromSource(destination, source, 0, (__bridge CFDictionaryRef)metadata); CGImageDestinationFinalize(destination); CFRelease(source); CFRelease(destination); return targetData; } + (NSData *)convertImage:(UIImage *)image usingType:(FLTImagePickerMIMEType)type quality:(nullable NSNumber *)quality { if (quality && type != FLTImagePickerMIMETypeJPEG) { NSLog(@"image_picker: compressing is not supported for type %@. Returning the image with " @"original quality", [FLTImagePickerMetaDataUtil imageTypeSuffixFromType:type]); } switch (type) { case FLTImagePickerMIMETypeJPEG: { CGFloat qualityFloat = (quality != nil) ? quality.floatValue : 1; return UIImageJPEGRepresentation(image, qualityFloat); } case FLTImagePickerMIMETypePNG: return UIImagePNGRepresentation(image); default: { // converts to JPEG by default. CGFloat qualityFloat = (quality != nil) ? quality.floatValue : 1; return UIImageJPEGRepresentation(image, qualityFloat); } } } @end
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerMetaDataUtil.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerMetaDataUtil.m", "repo_id": "packages", "token_count": 1216 }
998
# image_picker_platform_interface A common platform interface for the [`image_picker`][1] plugin. This interface allows platform-specific implementations of the `image_picker` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `image_picker`, extend [`ImagePickerPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `ImagePickerPlatform` by calling `ImagePickerPlatform.instance = MyImagePickerPlatform()`. # Note on breaking changes Strongly prefer non-breaking changes (such as adding a method to the interface) over breaking changes for this package. See https://flutter.dev/go/platform-interface-breaking-changes for a discussion on why a less-clean interface is preferable to a breaking change. [1]: ../image_picker [2]: lib/image_picker_platform_interface.dart
packages/packages/image_picker/image_picker_platform_interface/README.md/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/README.md", "repo_id": "packages", "token_count": 246 }
999
name: example description: Example for image_picker_windows implementation. publish_to: 'none' version: 1.0.0 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter image_picker_platform_interface: ^2.8.0 image_picker_windows: # When depending on this package from a real application you should use: # image_picker_windows: ^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: .. mime: ^1.0.4 video_player: ^2.1.4 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
packages/packages/image_picker/image_picker_windows/example/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker_windows/example/pubspec.yaml", "repo_id": "packages", "token_count": 274 }
1,000
# in\_app\_purchase\_android The Android implementation of [`in_app_purchase`][1]. ## Usage This package is [endorsed][2], which means you can simply use `in_app_purchase` 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][3]. ## Migrating to 0.3.0 To migrate to version 0.3.0 from 0.2.x, have a look at the [migration guide](migration_guide.md). ## Contributing This plugin uses [json_serializable](https://pub.dev/packages/json_serializable) for the many data structs passed between the underlying platform layers and Dart. After editing any of the serialized data structs, rebuild the serializers by running `flutter packages pub run build_runner build --delete-conflicting-outputs`. `flutter packages pub run build_runner watch --delete-conflicting-outputs` will watch the filesystem for changes. If you would like to contribute to the plugin, check out our [contribution guide](https://github.com/flutter/packages/blob/main/CONTRIBUTING.md). [1]: https://pub.dev/packages/in_app_purchase [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://pub.dev/packages/in_app_purchase_android/install
packages/packages/in_app_purchase/in_app_purchase_android/README.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/README.md", "repo_id": "packages", "token_count": 417 }
1,001
# Platform Implementation Test App This is a test app for manual testing and automated integration testing of this platform implementation. It is not intended to demonstrate actual use of this package, since the intent is that plugin clients use the app-facing package. Unless you are making changes to this implementation package, this example is very unlikely to be relevant. # In App Purchase Example ### 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 the Play Developer Console. Google Play requires developers to configure an app with in-app items for purchase to call their in-app-purchase APIs. The Google Play Store has extensive documentation on how to do this, and we've also included a high level guide below. * [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 of 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 [keystore](https://developer.android.com/studio/publish/app-signing#secure-shared-keystore) and [signing](https://developer.android.com/studio/publish/app-signing#sign-apk) and [flutter-android](https://docs.flutter.dev/deployment/android#signing-the-app) 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.
packages/packages/in_app_purchase/in_app_purchase_android/example/README.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/README.md", "repo_id": "packages", "token_count": 780 }
1,002
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/in_app_purchase/in_app_purchase_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,003
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:json_annotation/json_annotation.dart'; import '../../billing_client_wrappers.dart'; import '../channel.dart'; import 'billing_config_wrapper.dart'; part 'billing_client_wrapper.g.dart'; /// Method identifier for the OnPurchaseUpdated method channel method. @visibleForTesting const String kOnPurchasesUpdated = 'PurchasesUpdatedListener#onPurchasesUpdated(BillingResult, List<Purchase>)'; /// Method identifier for the userSelectedAlternativeBilling method channel method. @visibleForTesting const String kUserSelectedAlternativeBilling = 'UserChoiceBillingListener#userSelectedAlternativeBilling(UserChoiceDetails)'; const String _kOnBillingServiceDisconnected = 'BillingClientStateListener#onBillingServiceDisconnected()'; /// Callback triggered by Play in response to purchase activity. /// /// This callback is triggered in response to all purchase activity while an /// instance of `BillingClient` is active. This includes purchases initiated by /// the app ([BillingClient.launchBillingFlow]) as well as purchases made in /// Play itself while this app is open. /// /// This does not provide any hooks for purchases made in the past. See /// [BillingClient.queryPurchases] and [BillingClient.queryPurchaseHistory]. /// /// 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). /// /// Wraps a /// [`PurchasesUpdatedListener`](https://developer.android.com/reference/com/android/billingclient/api/PurchasesUpdatedListener.html). typedef PurchasesUpdatedListener = void Function( PurchasesResultWrapper purchasesResult); /// Wraps a [UserChoiceBillingListener](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceBillingListener) typedef UserSelectedAlternativeBillingListener = void Function( UserChoiceDetailsWrapper userChoiceDetailsWrapper); /// This class can be used directly instead of [InAppPurchaseConnection] to call /// Play-specific billing APIs. /// /// Wraps a /// [`com.android.billingclient.api.BillingClient`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient) /// instance. /// /// /// In general this API conforms to the Java /// `com.android.billingclient.api.BillingClient` API as much as possible, with /// some minor changes to account for language differences. Callbacks have been /// converted to futures where appropriate. /// /// Connection to [BillingClient] may be lost at any time (see /// `onBillingServiceDisconnected` param of [startConnection] and /// [BillingResponse.serviceDisconnected]). /// Consider using [BillingClientManager] that handles these disconnections /// transparently. class BillingClient { /// Creates a billing client. BillingClient(PurchasesUpdatedListener onPurchasesUpdated, UserSelectedAlternativeBillingListener? alternativeBillingListener) { channel.setMethodCallHandler(callHandler); _callbacks[kOnPurchasesUpdated] = <PurchasesUpdatedListener>[ onPurchasesUpdated ]; _callbacks[kUserSelectedAlternativeBilling] = alternativeBillingListener == null ? <UserSelectedAlternativeBillingListener>[] : <UserSelectedAlternativeBillingListener>[alternativeBillingListener]; } // Occasionally methods in the native layer require a Dart callback to be // triggered in response to a Java callback. For example, // [startConnection] registers an [OnBillingServiceDisconnected] callback. // This list of names to callbacks is used to trigger Dart callbacks in // response to those Java callbacks. Dart sends the Java layer a handle to the // matching callback here to remember, and then once its twin is triggered it // sends the handle back over the platform channel. We then access that handle // in this array and call it in Dart code. See also [_callHandler]. final Map<String, List<Function>> _callbacks = <String, List<Function>>{}; /// Calls /// [`BillingClient#isReady()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#isReady()) /// to get the ready status of the BillingClient instance. Future<bool> isReady() async { final bool? ready = await channel.invokeMethod<bool>('BillingClient#isReady()'); return ready ?? false; } /// Enable the [BillingClientWrapper] to handle pending purchases. /// /// **Deprecation warning:** it is no longer required to call /// [enablePendingPurchases] when initializing your application. @Deprecated( 'The requirement to call `enablePendingPurchases()` has become obsolete ' "since Google Play no longer accepts app submissions that don't support " 'pending purchases.') void enablePendingPurchases() { // No-op, until it is time to completely remove this method from the API. } /// Calls /// [`BillingClient#startConnection(BillingClientStateListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#startconnection) /// to create and connect a `BillingClient` instance. /// /// [onBillingServiceConnected] has been converted from a callback parameter /// to the Future result returned by this function. This returns the /// `BillingClient.BillingResultWrapper` describing the connection result. /// /// This triggers the creation of a new `BillingClient` instance in Java if /// one doesn't already exist. Future<BillingResultWrapper> startConnection( {required OnBillingServiceDisconnected onBillingServiceDisconnected, BillingChoiceMode billingChoiceMode = BillingChoiceMode.playBillingOnly}) async { final List<Function> disconnectCallbacks = _callbacks[_kOnBillingServiceDisconnected] ??= <Function>[]; _callbacks[_kOnBillingServiceDisconnected] ?.add(onBillingServiceDisconnected); return BillingResultWrapper.fromJson((await channel .invokeMapMethod<String, dynamic>( 'BillingClient#startConnection(BillingClientStateListener)', <String, dynamic>{ 'handle': disconnectCallbacks.length - 1, 'billingChoiceMode': const BillingChoiceModeConverter().toJson(billingChoiceMode), })) ?? <String, dynamic>{}); } /// Calls /// [`BillingClient#endConnection(BillingClientStateListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#endconnect /// to disconnect a `BillingClient` instance. /// /// Will trigger the [OnBillingServiceDisconnected] callback passed to [startConnection]. /// /// This triggers the destruction of the `BillingClient` instance in Java. Future<void> endConnection() async { return channel.invokeMethod<void>('BillingClient#endConnection()'); } /// Returns a list of [ProductDetailsResponseWrapper]s that have /// [ProductDetailsWrapper.productId] and [ProductDetailsWrapper.productType] /// in `productList`. /// /// Calls through to /// [`BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryProductDetailsAsync(com.android.billingclient.api.QueryProductDetailsParams,%20com.android.billingclient.api.ProductDetailsResponseListener). /// Instead of taking a callback parameter, it returns a Future /// [ProductDetailsResponseWrapper]. It also takes the values of /// `ProductDetailsParams` as direct arguments instead of requiring it /// constructed and passed in as a class. Future<ProductDetailsResponseWrapper> queryProductDetails({ required List<ProductWrapper> productList, }) async { final Map<String, dynamic> arguments = <String, dynamic>{ 'productList': productList.map((ProductWrapper product) => product.toJson()).toList() }; return ProductDetailsResponseWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( 'BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener)', arguments, )) ?? <String, dynamic>{}); } /// Attempt to launch the Play Billing Flow for a given [productDetails]. /// /// The [productDetails] needs to have already been fetched in a [queryProductDetails] /// call. The [accountId] is an optional hashed string associated with the user /// that's unique to your app. It's used by Google to detect unusual behavior. /// Do not pass in a cleartext [accountId], and do not use this field to store any Personally Identifiable Information (PII) /// such as emails in cleartext. Attempting to store PII in this field will result in purchases being blocked. /// Google Play recommends that you use either encryption or a one-way hash to generate an obfuscated identifier to send to Google Play. /// /// Specifies an optional [obfuscatedProfileId] that is uniquely associated with the user's profile in your app. /// Some applications allow users to have multiple profiles within a single account. Use this method to send the user's profile identifier to Google. /// Setting this field requests the user's obfuscated account id. /// /// Calling this attemps to show the Google Play purchase UI. The user is free /// to complete the transaction there. /// /// This method returns a [BillingResultWrapper] representing the initial attempt /// to show the Google Play billing flow. Actual purchase updates are /// delivered via the [PurchasesUpdatedListener]. /// /// This method calls through to /// [`BillingClient#launchBillingFlow`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#launchbillingflow). /// It constructs a /// [`BillingFlowParams`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams) /// instance by [setting the given productDetails](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setProductDetailsParamsList(java.util.List%3Ccom.android.billingclient.api.BillingFlowParams.ProductDetailsParams%3E)), /// [the given accountId](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setObfuscatedAccountId(java.lang.String)) /// and the [obfuscatedProfileId] (https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.Builder#setobfuscatedprofileid). /// /// When this method is called to purchase a subscription through an offer, an /// [`offerToken` can be passed in](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProductDetailsParams.Builder#setOfferToken(java.lang.String)). /// /// When this method is called to purchase a subscription, an optional /// `oldProduct` can be passed in. This will tell Google Play that rather than /// purchasing a new subscription, the user needs to upgrade/downgrade the /// existing subscription. /// The [oldProduct](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setOldPurchaseToken(java.lang.String)) and [purchaseToken] are the product id and purchase token that the user is upgrading or downgrading from. /// [purchaseToken] must not be `null` if [oldProduct] is not `null`. /// The [prorationMode](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.Builder#setReplaceProrationMode(int)) is the mode of proration during subscription upgrade/downgrade. /// This value will only be effective if the `oldProduct` is also set. Future<BillingResultWrapper> launchBillingFlow( {required String product, String? offerToken, String? accountId, String? obfuscatedProfileId, String? oldProduct, String? purchaseToken, ProrationMode? prorationMode}) async { assert((oldProduct == null) == (purchaseToken == null), 'oldProduct and purchaseToken must both be set, or both be null.'); final Map<String, dynamic> arguments = <String, dynamic>{ 'product': product, 'offerToken': offerToken, 'accountId': accountId, 'obfuscatedProfileId': obfuscatedProfileId, 'oldProduct': oldProduct, 'purchaseToken': purchaseToken, 'prorationMode': const ProrationModeConverter().toJson(prorationMode ?? ProrationMode.unknownSubscriptionUpgradeDowngradePolicy) }; return BillingResultWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( 'BillingClient#launchBillingFlow(Activity, BillingFlowParams)', arguments)) ?? <String, dynamic>{}); } /// Fetches recent purchases for the given [ProductType]. /// /// Unlike [queryPurchaseHistory], This does not make a network request and /// does not return items that are no longer owned. /// /// 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 /// [`BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchasesAsync(com.android.billingclient.api.QueryPurchasesParams,%20com.android.billingclient.api.PurchasesResponseListener)). Future<PurchasesResultWrapper> queryPurchases(ProductType productType) async { return PurchasesResultWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( 'BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)', <String, dynamic>{ 'productType': const ProductTypeConverter().toJson(productType) }, )) ?? <String, dynamic>{}); } /// Fetches purchase history for the given [ProductType]. /// /// Unlike [queryPurchases], this makes a network request via Play and returns /// the most recent purchase for each [ProductDetailsWrapper] of the given /// [ProductType] even if the item is no longer owned. /// /// 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 /// [`BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(com.android.billingclient.api.QueryPurchaseHistoryParams,%20com.android.billingclient.api.PurchaseHistoryResponseListener)). Future<PurchasesHistoryResult> queryPurchaseHistory( ProductType productType) async { return PurchasesHistoryResult.fromJson((await channel.invokeMapMethod< String, dynamic>( 'BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener)', <String, dynamic>{ 'productType': const ProductTypeConverter().toJson(productType) })) ?? <String, dynamic>{}); } /// Consumes a given in-app product. /// /// Consuming can only be done on an item that's owned, and as a result of consumption, the user will no longer own it. /// Consumption is done asynchronously. The method returns a Future containing a [BillingResultWrapper]. /// /// This wraps /// [`BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#consumeAsync(java.lang.String,%20com.android.billingclient.api.ConsumeResponseListener)) Future<BillingResultWrapper> consumeAsync(String purchaseToken) async { return BillingResultWrapper.fromJson((await channel.invokeMapMethod<String, dynamic>( 'BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)', <String, dynamic>{ 'purchaseToken': purchaseToken, })) ?? <String, dynamic>{}); } /// Acknowledge an in-app purchase. /// /// The developer must acknowledge all in-app purchases after they have been granted to the user. /// If this doesn't happen within three days of the purchase, the purchase will be refunded. /// /// Consumables are already implicitly acknowledged by calls to [consumeAsync] and /// do not need to be explicitly acknowledged by using this method. /// However this method can be called for them in order to explicitly acknowledge them if desired. /// /// Be sure to only acknowledge a purchase after it has been granted to the user. /// [PurchaseWrapper.purchaseState] should be [PurchaseStateWrapper.purchased] and /// the purchase should be validated. See [Verify a purchase](https://developer.android.com/google/play/billing/billing_library_overview#Verify) on verifying purchases. /// /// Please refer to [acknowledge](https://developer.android.com/google/play/billing/billing_library_overview#acknowledge) for more /// details. /// /// This wraps /// [`BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#acknowledgePurchase(com.android.billingclient.api.AcknowledgePurchaseParams,%20com.android.billingclient.api.AcknowledgePurchaseResponseListener)) Future<BillingResultWrapper> acknowledgePurchase(String purchaseToken) async { return BillingResultWrapper.fromJson((await channel.invokeMapMethod<String, dynamic>( 'BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)', <String, dynamic>{ 'purchaseToken': purchaseToken, })) ?? <String, dynamic>{}); } /// Checks if the specified feature or capability is supported by the Play Store. /// Call this to check if a [BillingClientFeature] is supported by the device. Future<bool> isFeatureSupported(BillingClientFeature feature) async { final bool? result = await channel.invokeMethod<bool>( 'BillingClient#isFeatureSupported(String)', <String, dynamic>{ 'feature': const BillingClientFeatureConverter().toJson(feature), }); return result ?? false; } /// BillingConfig method channel string identifier. // // Must match the value of GET_BILLING_CONFIG in // ../../../android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java @visibleForTesting static const String getBillingConfigMethodString = 'BillingClient#getBillingConfig()'; /// Fetches billing config info into a [BillingConfigWrapper] object. Future<BillingConfigWrapper> getBillingConfig() async { return BillingConfigWrapper.fromJson((await channel .invokeMapMethod<String, dynamic>(getBillingConfigMethodString)) ?? <String, dynamic>{}); } /// isAlternativeBillingOnlyAvailable method channel string identifier. // // Must match the value of IS_ALTERNATIVE_BILLING_ONLY_AVAILABLE in // ../../../android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java @visibleForTesting static const String isAlternativeBillingOnlyAvailableMethodString = 'BillingClient#isAlternativeBillingOnlyAvailable()'; /// Checks if "AlterntitiveBillingOnly" feature is available. Future<BillingResultWrapper> isAlternativeBillingOnlyAvailable() async { return BillingResultWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( isAlternativeBillingOnlyAvailableMethodString)) ?? <String, dynamic>{}); } /// showAlternativeBillingOnlyInformationDialog method channel string identifier. // // Must match the value of SHOW_ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG in // ../../../android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java @visibleForTesting static const String showAlternativeBillingOnlyInformationDialogMethodString = 'BillingClient#showAlternativeBillingOnlyInformationDialog()'; /// Shows the alternative billing only information dialog on top of the calling app. Future<BillingResultWrapper> showAlternativeBillingOnlyInformationDialog() async { return BillingResultWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( showAlternativeBillingOnlyInformationDialogMethodString)) ?? <String, dynamic>{}); } /// createAlternativeBillingOnlyReportingDetails method channel string identifier. // // Must match the value of CREATE_ALTERNATIVE_BILLING_ONLY_REPORTING_DETAILS in // ../../../android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java @visibleForTesting static const String createAlternativeBillingOnlyReportingDetailsMethodString = 'BillingClient#createAlternativeBillingOnlyReportingDetails()'; /// The details used to report transactions made via alternative billing /// without user choice to use Google Play billing. Future<AlternativeBillingOnlyReportingDetailsWrapper> createAlternativeBillingOnlyReportingDetails() async { return AlternativeBillingOnlyReportingDetailsWrapper.fromJson( (await channel.invokeMapMethod<String, dynamic>( createAlternativeBillingOnlyReportingDetailsMethodString)) ?? <String, dynamic>{}); } /// The method call handler for [channel]. @visibleForTesting Future<void> callHandler(MethodCall call) async { switch (call.method) { case kOnPurchasesUpdated: // The purchases updated listener is a singleton. assert(_callbacks[kOnPurchasesUpdated]!.length == 1); final PurchasesUpdatedListener listener = _callbacks[kOnPurchasesUpdated]!.first as PurchasesUpdatedListener; listener(PurchasesResultWrapper.fromJson( (call.arguments as Map<dynamic, dynamic>).cast<String, dynamic>())); case _kOnBillingServiceDisconnected: final int handle = (call.arguments as Map<Object?, Object?>)['handle']! as int; final List<OnBillingServiceDisconnected> onDisconnected = _callbacks[_kOnBillingServiceDisconnected]! .cast<OnBillingServiceDisconnected>(); onDisconnected[handle](); case kUserSelectedAlternativeBilling: if (_callbacks[kUserSelectedAlternativeBilling]!.isNotEmpty) { final UserSelectedAlternativeBillingListener listener = _callbacks[kUserSelectedAlternativeBilling]!.first as UserSelectedAlternativeBillingListener; listener(UserChoiceDetailsWrapper.fromJson( (call.arguments as Map<dynamic, dynamic>) .cast<String, dynamic>())); } } } } /// Callback triggered when the [BillingClientWrapper] is disconnected. /// /// Wraps /// [`com.android.billingclient.api.BillingClientStateListener.onServiceDisconnected()`](https://developer.android.com/reference/com/android/billingclient/api/BillingClientStateListener.html#onBillingServiceDisconnected()) /// to call back on `BillingClient` disconnect. typedef OnBillingServiceDisconnected = void Function(); /// Possible `BillingClient` response statuses. /// /// Wraps /// [`BillingClient.BillingResponse`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse). /// See the `BillingResponse` docs for more explanation of the different /// constants. @JsonEnum(alwaysCreate: true) enum BillingResponse { // WARNING: Changes to this class need to be reflected in our generated code. // Run `flutter packages pub run build_runner watch` to rebuild and watch for // further changes. /// The request has reached the maximum timeout before Google Play responds. @JsonValue(-3) serviceTimeout, /// The requested feature is not supported by Play Store on the current device. @JsonValue(-2) featureNotSupported, /// The Play Store service is not connected now - potentially transient state. @JsonValue(-1) serviceDisconnected, /// Success. @JsonValue(0) ok, /// The user pressed back or canceled a dialog. @JsonValue(1) userCanceled, /// The network connection is down. @JsonValue(2) serviceUnavailable, /// The billing API version is not supported for the type requested. @JsonValue(3) billingUnavailable, /// The requested product is not available for purchase. @JsonValue(4) itemUnavailable, /// Invalid arguments provided to the API. @JsonValue(5) developerError, /// Fatal error during the API action. @JsonValue(6) error, /// Failure to purchase since item is already owned. @JsonValue(7) itemAlreadyOwned, /// Failure to consume since item is not owned. @JsonValue(8) itemNotOwned, /// Network connection failure between the device and Play systems. @JsonValue(12) networkError, } /// Plugin concept to cover billing modes. /// /// [playBillingOnly] (google Play billing only). /// [alternativeBillingOnly] (app provided billing with reporting to Play). @JsonEnum(alwaysCreate: true) enum BillingChoiceMode { // WARNING: Changes to this class need to be reflected in our generated code. // Run `flutter packages pub run build_runner watch` to rebuild and watch for // further changes. // Values must match what is used in // in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java /// Billing through google Play. Default state. @JsonValue(0) playBillingOnly, /// Billing through app provided flow. @JsonValue(1) alternativeBillingOnly, /// Users can choose Play billing or alternative billing. @JsonValue(2) userChoiceBilling, } /// Serializer for [BillingChoiceMode]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@BillingChoiceModeConverter()`. class BillingChoiceModeConverter implements JsonConverter<BillingChoiceMode, int?> { /// Default const constructor. const BillingChoiceModeConverter(); @override BillingChoiceMode fromJson(int? json) { if (json == null) { return BillingChoiceMode.playBillingOnly; } return $enumDecode(_$BillingChoiceModeEnumMap, json); } @override int toJson(BillingChoiceMode object) => _$BillingChoiceModeEnumMap[object]!; } /// Serializer for [BillingResponse]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@BillingResponseConverter()`. class BillingResponseConverter implements JsonConverter<BillingResponse, int?> { /// Default const constructor. const BillingResponseConverter(); @override BillingResponse fromJson(int? json) { if (json == null) { return BillingResponse.error; } return $enumDecode(_$BillingResponseEnumMap, json); } @override int toJson(BillingResponse object) => _$BillingResponseEnumMap[object]!; } /// Enum representing potential [ProductDetailsWrapper.productType]s. /// /// Wraps /// [`BillingClient.ProductType`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.ProductType) /// See the linked documentation for an explanation of the different constants. @JsonEnum(alwaysCreate: true) enum ProductType { // WARNING: Changes to this class need to be reflected in our generated code. // Run `flutter packages pub run build_runner watch` to rebuild and watch for // further changes. /// A one time product. Acquired in a single transaction. @JsonValue('inapp') inapp, /// A product requiring a recurring charge over time. @JsonValue('subs') subs, } /// Serializer for [ProductType]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@ProductTypeConverter()`. class ProductTypeConverter implements JsonConverter<ProductType, String?> { /// Default const constructor. const ProductTypeConverter(); @override ProductType fromJson(String? json) { if (json == null) { return ProductType.inapp; } return $enumDecode(_$ProductTypeEnumMap, json); } @override String toJson(ProductType object) => _$ProductTypeEnumMap[object]!; } /// Enum representing the proration mode. /// /// When upgrading or downgrading a subscription, set this mode to provide details /// about the proration that will be applied when the subscription changes. /// /// Wraps [`BillingFlowParams.ProrationMode`](https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode) /// See the linked documentation for an explanation of the different constants. @JsonEnum(alwaysCreate: true) enum ProrationMode { // WARNING: Changes to this class need to be reflected in our generated code. // Run `flutter packages pub run build_runner watch` to rebuild and watch for // further changes. /// Unknown upgrade or downgrade policy. @JsonValue(0) unknownSubscriptionUpgradeDowngradePolicy, /// Replacement takes effect immediately, and the remaining time will be prorated /// and credited to the user. /// /// This is the current default behavior. @JsonValue(1) immediateWithTimeProration, /// Replacement takes effect immediately, and the billing cycle remains the same. /// /// The price for the remaining period will be charged. /// This option is only available for subscription upgrade. @JsonValue(2) immediateAndChargeProratedPrice, /// Replacement takes effect immediately, and the new price will be charged on next /// recurrence time. /// /// The billing cycle stays the same. @JsonValue(3) immediateWithoutProration, /// Replacement takes effect when the old plan expires, and the new price will /// be charged at the same time. @JsonValue(4) deferred, /// Replacement takes effect immediately, and the user is charged full price /// of new plan and is given a full billing cycle of subscription, plus /// remaining prorated time from the old plan. @JsonValue(5) immediateAndChargeFullPrice, } /// Serializer for [ProrationMode]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@ProrationModeConverter()`. class ProrationModeConverter implements JsonConverter<ProrationMode, int?> { /// Default const constructor. const ProrationModeConverter(); @override ProrationMode fromJson(int? json) { if (json == null) { return ProrationMode.unknownSubscriptionUpgradeDowngradePolicy; } return $enumDecode(_$ProrationModeEnumMap, json); } @override int toJson(ProrationMode object) => _$ProrationModeEnumMap[object]!; } /// Features/capabilities supported by [BillingClient.isFeatureSupported()](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType). @JsonEnum(alwaysCreate: true) enum BillingClientFeature { // WARNING: Changes to this class need to be reflected in our generated code. // Run `flutter packages pub run build_runner watch` to rebuild and watch for // further changes. // // JsonValues need to match constant values defined in https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType#summary /// Purchase/query for in-app items on VR. @JsonValue('inAppItemsOnVr') inAppItemsOnVR, /// Launch a price change confirmation flow. @JsonValue('priceChangeConfirmation') priceChangeConfirmation, /// Play billing library support for querying and purchasing with ProductDetails. @JsonValue('fff') productDetails, /// Purchase/query for subscriptions. @JsonValue('subscriptions') subscriptions, /// Purchase/query for subscriptions on VR. @JsonValue('subscriptionsOnVr') subscriptionsOnVR, /// Subscriptions update/replace. @JsonValue('subscriptionsUpdate') subscriptionsUpdate } /// Serializer for [BillingClientFeature]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@BillingClientFeatureConverter()`. class BillingClientFeatureConverter implements JsonConverter<BillingClientFeature, String> { /// Default const constructor. const BillingClientFeatureConverter(); @override BillingClientFeature fromJson(String json) { return $enumDecode<BillingClientFeature, dynamic>( _$BillingClientFeatureEnumMap.cast<BillingClientFeature, dynamic>(), json); } @override String toJson(BillingClientFeature object) => _$BillingClientFeatureEnumMap[object]!; }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart", "repo_id": "packages", "token_count": 10039 }
1,004
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.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 'user_choice_details_wrapper.g.dart'; /// This wraps [`com.android.billingclient.api.UserChoiceDetails`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceDetails) // See https://docs.flutter.dev/data-and-backend/serialization/json#generating-code-for-nested-classes // for explination for why this uses explicitToJson. @JsonSerializable(createToJson: true, explicitToJson: true) @immutable class UserChoiceDetailsWrapper { /// Creates a purchase wrapper with the given purchase details. @visibleForTesting const UserChoiceDetailsWrapper({ required this.originalExternalTransactionId, required this.externalTransactionToken, required this.products, }); /// Factory for creating a [UserChoiceDetailsWrapper] from a [Map] with /// the user choice details. factory UserChoiceDetailsWrapper.fromJson(Map<String, dynamic> map) => _$UserChoiceDetailsWrapperFromJson(map); /// Creates a JSON representation of this product. Map<String, dynamic> toJson() => _$UserChoiceDetailsWrapperToJson(this); @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is UserChoiceDetailsWrapper && other.originalExternalTransactionId == originalExternalTransactionId && other.externalTransactionToken == externalTransactionToken && listEquals(other.products, products); } @override int get hashCode => Object.hash( originalExternalTransactionId, externalTransactionToken, products.hashCode, ); /// Returns the external transaction Id of the originating subscription, if /// the purchase is a subscription upgrade/downgrade. @JsonKey(defaultValue: '') final String originalExternalTransactionId; /// Returns a token that represents the user's prospective purchase via /// user choice alternative billing. @JsonKey(defaultValue: '') final String externalTransactionToken; /// Returns a list of [UserChoiceDetailsProductWrapper] to be purchased in /// the user choice alternative billing flow. @JsonKey(defaultValue: <UserChoiceDetailsProductWrapper>[]) final List<UserChoiceDetailsProductWrapper> products; } /// Data structure representing a UserChoiceDetails product. /// /// This wraps [`com.android.billingclient.api.UserChoiceDetails.Product`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceDetails.Product) // // See https://docs.flutter.dev/data-and-backend/serialization/json#generating-code-for-nested-classes // for explination for why this uses explicitToJson. @JsonSerializable(createToJson: true, explicitToJson: true) @ProductTypeConverter() @immutable class UserChoiceDetailsProductWrapper { /// Creates a [UserChoiceDetailsProductWrapper] with the given record details. @visibleForTesting const UserChoiceDetailsProductWrapper({ required this.id, required this.offerToken, required this.productType, }); /// Factory for creating a [UserChoiceDetailsProductWrapper] from a [Map] with the record details. factory UserChoiceDetailsProductWrapper.fromJson(Map<String, dynamic> map) => _$UserChoiceDetailsProductWrapperFromJson(map); /// Creates a JSON representation of this product. Map<String, dynamic> toJson() => _$UserChoiceDetailsProductWrapperToJson(this); /// Returns the id of the product being purchased. @JsonKey(defaultValue: '') final String id; /// Returns the offer token that was passed in launchBillingFlow to purchase the product. @JsonKey(defaultValue: '') final String offerToken; /// Returns the [ProductType] of the product being purchased. final ProductType productType; @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is UserChoiceDetailsProductWrapper && other.id == id && other.offerToken == offerToken && other.productType == productType; } @override int get hashCode => Object.hash( id, offerToken, productType, ); }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart", "repo_id": "packages", "token_count": 1436 }
1,005
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/src/billing_client_wrappers/billing_config_wrapper.dart'; import 'package:in_app_purchase_android/src/channel.dart'; import '../stub_in_app_purchase_platform.dart'; import 'product_details_wrapper_test.dart'; import 'purchase_wrapper_test.dart'; const PurchaseWrapper dummyOldPurchase = PurchaseWrapper( orderId: 'oldOrderId', packageName: 'oldPackageName', purchaseTime: 0, signature: 'oldSignature', products: <String>['oldProduct'], purchaseToken: 'oldPurchaseToken', isAutoRenewing: false, originalJson: '', developerPayload: 'old dummy payload', isAcknowledged: true, purchaseState: PurchaseStateWrapper.purchased, ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform(); late BillingClient billingClient; setUpAll(() => TestDefaultBinaryMessengerBinding .instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, stubPlatform.fakeMethodCallHandler)); setUp(() { billingClient = BillingClient( (PurchasesResultWrapper _) {}, (UserChoiceDetailsWrapper _) {}); stubPlatform.reset(); }); group('isReady', () { test('true', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: true); expect(await billingClient.isReady(), isTrue); }); test('false', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: false); expect(await billingClient.isReady(), isFalse); }); }); // Make sure that the enum values are supported and that the converter call // does not fail test('response states', () async { const BillingResponseConverter converter = BillingResponseConverter(); converter.fromJson(-3); converter.fromJson(-2); converter.fromJson(-1); converter.fromJson(0); converter.fromJson(1); converter.fromJson(2); converter.fromJson(3); converter.fromJson(4); converter.fromJson(5); converter.fromJson(6); converter.fromJson(7); converter.fromJson(8); converter.fromJson(12); }); group('startConnection', () { const String methodName = 'BillingClient#startConnection(BillingClientStateListener)'; test('returns BillingResultWrapper', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; stubPlatform.addResponse( name: methodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, ); const BillingResultWrapper billingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); expect( await billingClient.startConnection( onBillingServiceDisconnected: () {}), equals(billingResult)); }); test('passes handle to onBillingServiceDisconnected', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; stubPlatform.addResponse( name: methodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, ); await billingClient.startConnection(onBillingServiceDisconnected: () {}); final MethodCall call = stubPlatform.previousCallMatching(methodName); expect( call.arguments, equals(<dynamic, dynamic>{ 'handle': 0, 'billingChoiceMode': 0, })); }); test('passes billingChoiceMode alternativeBillingOnly when set', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; stubPlatform.addResponse( name: methodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, ); await billingClient.startConnection( onBillingServiceDisconnected: () {}, billingChoiceMode: BillingChoiceMode.alternativeBillingOnly); final MethodCall call = stubPlatform.previousCallMatching(methodName); expect( call.arguments, equals(<dynamic, dynamic>{ 'handle': 0, 'billingChoiceMode': 1, })); }); test('passes billingChoiceMode userChoiceBilling when set', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; stubPlatform.addResponse( name: methodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, ); final Completer<UserChoiceDetailsWrapper> completer = Completer<UserChoiceDetailsWrapper>(); billingClient = BillingClient((PurchasesResultWrapper _) {}, (UserChoiceDetailsWrapper details) => completer.complete(details)); stubPlatform.reset(); await billingClient.startConnection( onBillingServiceDisconnected: () {}, billingChoiceMode: BillingChoiceMode.userChoiceBilling); final MethodCall call = stubPlatform.previousCallMatching(methodName); expect( call.arguments, equals(<dynamic, dynamic>{ 'handle': 0, 'billingChoiceMode': 2, })); const UserChoiceDetailsWrapper expected = UserChoiceDetailsWrapper( originalExternalTransactionId: 'TransactionId', externalTransactionToken: 'TransactionToken', products: <UserChoiceDetailsProductWrapper>[ UserChoiceDetailsProductWrapper( id: 'id1', offerToken: 'offerToken1', productType: ProductType.inapp), UserChoiceDetailsProductWrapper( id: 'id2', offerToken: 'offerToken2', productType: ProductType.inapp), ], ); await billingClient.callHandler( MethodCall(kUserSelectedAlternativeBilling, expected.toJson())); expect(completer.isCompleted, isTrue); expect(await completer.future, expected); }); test('UserChoiceDetailsWrapper searilization check', () async { // Test ensures that changes to UserChoiceDetailsWrapper#toJson are // compatible with code in Translator.java. const String transactionIdKey = 'originalExternalTransactionId'; const String transactionTokenKey = 'externalTransactionToken'; const String productsKey = 'products'; const String productIdKey = 'id'; const String productOfferTokenKey = 'offerToken'; const String productTypeKey = 'productType'; const UserChoiceDetailsProductWrapper expectedProduct1 = UserChoiceDetailsProductWrapper( id: 'id1', offerToken: 'offerToken1', productType: ProductType.inapp); const UserChoiceDetailsProductWrapper expectedProduct2 = UserChoiceDetailsProductWrapper( id: 'id2', offerToken: 'offerToken2', productType: ProductType.inapp); const UserChoiceDetailsWrapper expected = UserChoiceDetailsWrapper( originalExternalTransactionId: 'TransactionId', externalTransactionToken: 'TransactionToken', products: <UserChoiceDetailsProductWrapper>[ expectedProduct1, expectedProduct2, ], ); final Map<String, dynamic> detailsJson = expected.toJson(); expect(detailsJson.keys, contains(transactionIdKey)); expect(detailsJson.keys, contains(transactionTokenKey)); expect(detailsJson.keys, contains(productsKey)); final Map<String, dynamic> productJson = expectedProduct1.toJson(); expect(productJson, contains(productIdKey)); expect(productJson, contains(productOfferTokenKey)); expect(productJson, contains(productTypeKey)); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: methodName, ); expect( await billingClient.startConnection( onBillingServiceDisconnected: () {}), equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); }); }); test('endConnection', () async { const String endConnectionName = 'BillingClient#endConnection()'; expect(stubPlatform.countPreviousCalls(endConnectionName), equals(0)); stubPlatform.addResponse(name: endConnectionName); await billingClient.endConnection(); expect(stubPlatform.countPreviousCalls(endConnectionName), equals(1)); }); group('queryProductDetails', () { const String queryMethodName = 'BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener)'; test('handles empty productDetails', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; stubPlatform.addResponse(name: queryMethodName, value: <dynamic, dynamic>{ 'billingResult': <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, 'productDetailsList': <Map<String, dynamic>>[] }); final ProductDetailsResponseWrapper response = await billingClient .queryProductDetails(productList: <ProductWrapper>[ const ProductWrapper( productId: 'invalid', productType: ProductType.inapp) ]); const BillingResultWrapper billingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); expect(response.billingResult, equals(billingResult)); expect(response.productDetailsList, isEmpty); }); test('returns ProductDetailsResponseWrapper', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; stubPlatform.addResponse(name: queryMethodName, value: <String, dynamic>{ 'billingResult': <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, 'productDetailsList': <Map<String, dynamic>>[ buildProductMap(dummyOneTimeProductDetails) ], }); final ProductDetailsResponseWrapper response = await billingClient.queryProductDetails( productList: <ProductWrapper>[ const ProductWrapper( productId: 'invalid', productType: ProductType.inapp), ], ); const BillingResultWrapper billingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); expect(response.billingResult, equals(billingResult)); expect(response.productDetailsList, contains(dummyOneTimeProductDetails)); }); test('handles null method channel response', () async { stubPlatform.addResponse(name: queryMethodName); final ProductDetailsResponseWrapper response = await billingClient.queryProductDetails( productList: <ProductWrapper>[ const ProductWrapper( productId: 'invalid', productType: ProductType.inapp), ], ); const BillingResultWrapper billingResult = BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage); expect(response.billingResult, equals(billingResult)); expect(response.productDetailsList, isEmpty); }); }); group('launchBillingFlow', () { const String launchMethodName = 'BillingClient#launchBillingFlow(Activity, BillingFlowParams)'; test('serializes and deserializes data', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String profileId = 'hashedProfileId'; expect( await billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId), equals(expectedBillingResult)); final Map<dynamic, dynamic> arguments = stubPlatform .previousCallMatching(launchMethodName) .arguments as Map<dynamic, dynamic>; expect(arguments['product'], equals(productDetails.productId)); expect(arguments['accountId'], equals(accountId)); expect(arguments['obfuscatedProfileId'], equals(profileId)); }); test( 'Change subscription throws assertion error `oldProduct` and `purchaseToken` has different nullability', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String profileId = 'hashedProfileId'; expect( billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId, oldProduct: dummyOldPurchase.products.first), throwsAssertionError); expect( billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId, purchaseToken: dummyOldPurchase.purchaseToken), throwsAssertionError); }); test( 'serializes and deserializes data on change subscription without proration', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String profileId = 'hashedProfileId'; expect( await billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId, oldProduct: dummyOldPurchase.products.first, purchaseToken: dummyOldPurchase.purchaseToken), equals(expectedBillingResult)); final Map<dynamic, dynamic> arguments = stubPlatform .previousCallMatching(launchMethodName) .arguments as Map<dynamic, dynamic>; expect(arguments['product'], equals(productDetails.productId)); expect(arguments['accountId'], equals(accountId)); expect(arguments['oldProduct'], equals(dummyOldPurchase.products.first)); expect( arguments['purchaseToken'], equals(dummyOldPurchase.purchaseToken)); expect(arguments['obfuscatedProfileId'], equals(profileId)); }); test( 'serializes and deserializes data on change subscription with proration', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String profileId = 'hashedProfileId'; const ProrationMode prorationMode = ProrationMode.immediateAndChargeProratedPrice; expect( await billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId, oldProduct: dummyOldPurchase.products.first, prorationMode: prorationMode, purchaseToken: dummyOldPurchase.purchaseToken), equals(expectedBillingResult)); final Map<dynamic, dynamic> arguments = stubPlatform .previousCallMatching(launchMethodName) .arguments as Map<dynamic, dynamic>; expect(arguments['product'], equals(productDetails.productId)); expect(arguments['accountId'], equals(accountId)); expect(arguments['oldProduct'], equals(dummyOldPurchase.products.first)); expect(arguments['obfuscatedProfileId'], equals(profileId)); expect( arguments['purchaseToken'], equals(dummyOldPurchase.purchaseToken)); expect(arguments['prorationMode'], const ProrationModeConverter().toJson(prorationMode)); }); test( 'serializes and deserializes data when using immediateAndChargeFullPrice', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String profileId = 'hashedProfileId'; const ProrationMode prorationMode = ProrationMode.immediateAndChargeFullPrice; expect( await billingClient.launchBillingFlow( product: productDetails.productId, accountId: accountId, obfuscatedProfileId: profileId, oldProduct: dummyOldPurchase.products.first, prorationMode: prorationMode, purchaseToken: dummyOldPurchase.purchaseToken), equals(expectedBillingResult)); final Map<dynamic, dynamic> arguments = stubPlatform .previousCallMatching(launchMethodName) .arguments as Map<dynamic, dynamic>; expect(arguments['product'], equals(productDetails.productId)); expect(arguments['accountId'], equals(accountId)); expect(arguments['oldProduct'], equals(dummyOldPurchase.products.first)); expect(arguments['obfuscatedProfileId'], equals(profileId)); expect( arguments['purchaseToken'], equals(dummyOldPurchase.purchaseToken)); expect(arguments['prorationMode'], const ProrationModeConverter().toJson(prorationMode)); }); test('handles null accountId', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; expect( await billingClient.launchBillingFlow( product: productDetails.productId), equals(expectedBillingResult)); final Map<dynamic, dynamic> arguments = stubPlatform .previousCallMatching(launchMethodName) .arguments as Map<dynamic, dynamic>; expect(arguments['product'], equals(productDetails.productId)); expect(arguments['accountId'], isNull); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: launchMethodName, ); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; expect( await billingClient.launchBillingFlow( product: productDetails.productId), equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); }); }); group('queryPurchases', () { const String queryPurchasesMethodName = 'BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)'; test('serializes and deserializes data', () async { const BillingResponse expectedCode = BillingResponse.ok; final List<PurchaseWrapper> expectedList = <PurchaseWrapper>[ dummyPurchase ]; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform .addResponse(name: queryPurchasesMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(expectedCode), 'purchasesList': expectedList .map((PurchaseWrapper purchase) => buildPurchaseMap(purchase)) .toList(), }); final PurchasesResultWrapper response = await billingClient.queryPurchases(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); expect(response.responseCode, equals(expectedCode)); expect(response.purchasesList, equals(expectedList)); }); test('handles empty purchases', () async { const BillingResponse expectedCode = BillingResponse.userCanceled; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform .addResponse(name: queryPurchasesMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(expectedCode), 'purchasesList': <dynamic>[], }); final PurchasesResultWrapper response = await billingClient.queryPurchases(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); expect(response.responseCode, equals(expectedCode)); expect(response.purchasesList, isEmpty); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: queryPurchasesMethodName, ); final PurchasesResultWrapper response = await billingClient.queryPurchases(ProductType.inapp); expect( response.billingResult, equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); expect(response.responseCode, BillingResponse.error); expect(response.purchasesList, isEmpty); }); }); group('queryPurchaseHistory', () { const String queryPurchaseHistoryMethodName = 'BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener)'; test('serializes and deserializes data', () async { const BillingResponse expectedCode = BillingResponse.ok; final List<PurchaseHistoryRecordWrapper> expectedList = <PurchaseHistoryRecordWrapper>[ dummyPurchaseHistoryRecord, ]; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: queryPurchaseHistoryMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'purchaseHistoryRecordList': expectedList .map((PurchaseHistoryRecordWrapper purchaseHistoryRecord) => buildPurchaseHistoryRecordMap(purchaseHistoryRecord)) .toList(), }); final PurchasesHistoryResult response = await billingClient.queryPurchaseHistory(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); expect(response.purchaseHistoryRecordList, equals(expectedList)); }); test('handles empty purchases', () async { const BillingResponse expectedCode = BillingResponse.userCanceled; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: queryPurchaseHistoryMethodName, value: <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'purchaseHistoryRecordList': <dynamic>[], }); final PurchasesHistoryResult response = await billingClient.queryPurchaseHistory(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); expect(response.purchaseHistoryRecordList, isEmpty); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: queryPurchaseHistoryMethodName, ); final PurchasesHistoryResult response = await billingClient.queryPurchaseHistory(ProductType.inapp); expect( response.billingResult, equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); expect(response.purchaseHistoryRecordList, isEmpty); }); }); group('consume purchases', () { const String consumeMethodName = 'BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)'; test('consume purchase async success', () async { const BillingResponse expectedCode = BillingResponse.ok; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResult)); final BillingResultWrapper billingResult = await billingClient.consumeAsync('dummy token'); expect(billingResult, equals(expectedBillingResult)); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: consumeMethodName, ); final BillingResultWrapper billingResult = await billingClient.consumeAsync('dummy token'); expect( billingResult, equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); }); }); group('acknowledge purchases', () { const String acknowledgeMethodName = 'BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)'; test('acknowledge purchase success', () async { const BillingResponse expectedCode = BillingResponse.ok; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: acknowledgeMethodName, value: buildBillingResultMap(expectedBillingResult)); final BillingResultWrapper billingResult = await billingClient.acknowledgePurchase('dummy token'); expect(billingResult, equals(expectedBillingResult)); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: acknowledgeMethodName, ); final BillingResultWrapper billingResult = await billingClient.acknowledgePurchase('dummy token'); expect( billingResult, equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); }); }); group('isFeatureSupported', () { const String isFeatureSupportedMethodName = 'BillingClient#isFeatureSupported(String)'; test('isFeatureSupported returns false', () async { late Map<Object?, Object?> arguments; stubPlatform.addResponse( name: isFeatureSupportedMethodName, value: false, additionalStepBeforeReturn: (dynamic value) => arguments = value as Map<dynamic, dynamic>, ); final bool isSupported = await billingClient .isFeatureSupported(BillingClientFeature.subscriptions); expect(isSupported, isFalse); expect(arguments['feature'], equals('subscriptions')); }); test('isFeatureSupported returns true', () async { late Map<Object?, Object?> arguments; stubPlatform.addResponse( name: isFeatureSupportedMethodName, value: true, additionalStepBeforeReturn: (dynamic value) => arguments = value as Map<dynamic, dynamic>, ); final bool isSupported = await billingClient .isFeatureSupported(BillingClientFeature.subscriptions); expect(isSupported, isTrue); expect(arguments['feature'], equals('subscriptions')); }); }); group('billingConfig', () { test('billingConfig returns object', () async { const BillingConfigWrapper expected = BillingConfigWrapper( countryCode: 'US', responseCode: BillingResponse.ok, debugMessage: ''); stubPlatform.addResponse( name: BillingClient.getBillingConfigMethodString, value: buildBillingConfigMap(expected), ); final BillingConfigWrapper result = await billingClient.getBillingConfig(); expect(result.countryCode, 'US'); expect(result, expected); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: BillingClient.getBillingConfigMethodString, ); final BillingConfigWrapper result = await billingClient.getBillingConfig(); expect( result, equals(const BillingConfigWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingConfigErrorMessage, ))); }); }); group('isAlternativeBillingOnlyAvailable', () { test('returns object', () async { const BillingResultWrapper expected = BillingResultWrapper(responseCode: BillingResponse.ok); stubPlatform.addResponse( name: BillingClient.isAlternativeBillingOnlyAvailableMethodString, value: buildBillingResultMap(expected)); final BillingResultWrapper result = await billingClient.isAlternativeBillingOnlyAvailable(); expect(result, expected); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: BillingClient.isAlternativeBillingOnlyAvailableMethodString, ); final BillingResultWrapper result = await billingClient.isAlternativeBillingOnlyAvailable(); expect(result.responseCode, BillingResponse.error); }); }); group('createAlternativeBillingOnlyReportingDetails', () { test('returns object', () async { const AlternativeBillingOnlyReportingDetailsWrapper expected = AlternativeBillingOnlyReportingDetailsWrapper( responseCode: BillingResponse.ok, debugMessage: 'debug', externalTransactionToken: 'abc123youandme'); stubPlatform.addResponse( name: BillingClient .createAlternativeBillingOnlyReportingDetailsMethodString, value: buildAlternativeBillingOnlyReportingDetailsMap(expected)); final AlternativeBillingOnlyReportingDetailsWrapper result = await billingClient.createAlternativeBillingOnlyReportingDetails(); expect(result, equals(expected)); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: BillingClient .createAlternativeBillingOnlyReportingDetailsMethodString, ); final AlternativeBillingOnlyReportingDetailsWrapper result = await billingClient.createAlternativeBillingOnlyReportingDetails(); expect(result.responseCode, BillingResponse.error); }); }); group('showAlternativeBillingOnlyInformationDialog', () { test('returns object', () async { const BillingResultWrapper expected = BillingResultWrapper(responseCode: BillingResponse.ok); stubPlatform.addResponse( name: BillingClient .showAlternativeBillingOnlyInformationDialogMethodString, value: buildBillingResultMap(expected)); final BillingResultWrapper result = await billingClient.showAlternativeBillingOnlyInformationDialog(); expect(result, expected); }); test('handles method channel returning null', () async { stubPlatform.addResponse( name: BillingClient .showAlternativeBillingOnlyInformationDialogMethodString, ); final BillingResultWrapper result = await billingClient.showAlternativeBillingOnlyInformationDialog(); expect(result.responseCode, BillingResponse.error); }); }); } Map<String, dynamic> buildBillingConfigMap(BillingConfigWrapper original) { return <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(original.responseCode), 'debugMessage': original.debugMessage, 'countryCode': original.countryCode, }; } Map<String, dynamic> buildAlternativeBillingOnlyReportingDetailsMap( AlternativeBillingOnlyReportingDetailsWrapper original) { return <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(original.responseCode), 'debugMessage': original.debugMessage, // from: io/flutter/plugins/inapppurchase/Translator.java 'externalTransactionToken': original.externalTransactionToken, }; }
packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart", "repo_id": "packages", "token_count": 12955 }
1,006
## 0.3.13+1 * Handle translation of errors nested in dictionaries. ## 0.3.13 * Added new native tests for more complete test coverage. ## 0.3.12+1 * Fixes type of error code returned from native code in SKReceiptManager.retrieveReceiptData. ## 0.3.12 * Converts `refreshReceipt()`, `startObservingPaymentQueue()`, `stopObservingPaymentQueue()`, `registerPaymentQueueDelegate()`, `removePaymentQueueDelegate()`, `showPriceConsentIfNeeded()` to pigeon. ## 0.3.11 * Fixes SKError.userInfo not being nullable. ## 0.3.10 * Converts `startProductRequest()`, `finishTransaction()`, `restoreTransactions()`, `presentCodeRedemptionSheet()` to pigeon. ## 0.3.9 * Converts `storefront()`, `transactions()`, `addPayment()`, `canMakePayment` to pigeon. * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 0.3.8+1 * Adds privacy manifest. ## 0.3.8 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 0.3.7 * Adds `Future<SKStorefrontWrapper?> storefront()` in SKPaymentQueueWrapper class. ## 0.3.6+7 * Updates example code for current versions of Flutter. ## 0.3.6+6 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.3.6+5 * Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters. ## 0.3.6+4 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.3.6+3 * Adds a null check, to prevent a new diagnostic. ## 0.3.6+2 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 0.3.6+1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 0.3.6 * Updates minimum Flutter version to 3.3 and iOS 11. ## 0.3.5+2 * Fixes a crash when `appStoreReceiptURL` is nil. ## 0.3.5+1 * Uses the new `sharedDarwinSource` flag when available. ## 0.3.5 * Updates minimum Flutter version to 3.0. * Ignores a lint in the example app for backwards compatibility. ## 0.3.4+1 * Updates code for stricter lint checks. ## 0.3.4 * Adds macOS as a supported platform. ## 0.3.3 * Supports adding discount information to AppStorePurchaseParam. * Fixes iOS Promotional Offers bug which prevents them from working. ## 0.3.2+2 * Updates imports for `prefer_relative_imports`. ## 0.3.2+1 * Updates minimum Flutter version to 2.10. * Replaces deprecated ThemeData.primaryColor. ## 0.3.2 * Adds the `identifier` and `type` fields to the `SKProductDiscountWrapper` to reflect the changes in the [SKProductDiscount](https://developer.apple.com/documentation/storekit/skproductdiscount?language=objc) in iOS 12.2. ## 0.3.1+1 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 0.3.1 * Adds ability to purchase more than one of a product. ## 0.3.0+10 * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.3.0+9 * Updates references to the obsolete master branch. ## 0.3.0+8 * Fixes a memory leak on iOS. ## 0.3.0+7 * Minor fixes for new analysis options. ## 0.3.0+6 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.3.0+5 * Migrates from `ui.hash*` to `Object.hash*`. ## 0.3.0+4 * Ensures that `NSError` instances with an unexpected value for the `userInfo` field don't crash the app, but send an explanatory message instead. ## 0.3.0+3 * Implements transaction caching for StoreKit ensuring transactions are delivered to the Flutter client. ## 0.3.0+2 * Internal code cleanup for stricter analysis options. ## 0.3.0+1 * Removes dependency on `meta`. ## 0.3.0 * **BREAKING CHANGE:** `InAppPurchaseStoreKitPlatform.restorePurchase()` emits an empty instance of `List<ProductDetails>` when there were no transactions to restore, indicating that the restore procedure has finished. ## 0.2.1 * Renames `in_app_purchase_ios` to `in_app_purchase_storekit` to facilitate future macOS support.
packages/packages/in_app_purchase/in_app_purchase_storekit/CHANGELOG.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/CHANGELOG.md", "repo_id": "packages", "token_count": 1370 }
1,007
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <StoreKit/StoreKit.h> #import "FIAPRequestHandler.h" #import "InAppPurchasePlugin.h" @interface InAppPurchasePlugin () // Holding strong references to FIAPRequestHandlers. Remove the handlers from the set after // the request is finished. @property(strong, nonatomic, readonly) NSMutableSet *requestHandlers; // Callback channel to dart used for when a function from the transaction observer is triggered. @property(strong, nonatomic) FlutterMethodChannel *transactionObserverCallbackChannel; // Callback channel to dart used for when a function from the transaction observer is triggered. @property(copy, nonatomic) FIAPRequestHandler * (^handlerFactory)(SKRequest *); // Convenience initializer with dependancy injection - (instancetype)initWithReceiptManager:(FIAPReceiptManager *)receiptManager handlerFactory:(FIAPRequestHandler * (^)(SKRequest *))handlerFactory; // Transaction observer methods - (void)handleTransactionsUpdated:(NSArray<SKPaymentTransaction *> *)transactions; - (void)handleTransactionsRemoved:(NSArray<SKPaymentTransaction *> *)transactions; - (void)handleTransactionRestoreFailed:(NSError *)error; - (void)restoreCompletedTransactionsFinished; - (BOOL)shouldAddStorePayment:(SKPayment *)payment product:(SKProduct *)product; @end
packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/InAppPurchasePlugin+TestOnly.h/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/InAppPurchasePlugin+TestOnly.h", "repo_id": "packages", "token_count": 409 }
1,008
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_storekit/src/types/app_store_product_details.dart'; import 'package:in_app_purchase_storekit/src/types/app_store_purchase_details.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; import 'package:test/test.dart'; import 'sk_test_stub_objects.dart'; void main() { group('product related object wrapper test', () { test( 'SKProductSubscriptionPeriodWrapper should have property values consistent with map', () { final SKProductSubscriptionPeriodWrapper wrapper = SKProductSubscriptionPeriodWrapper.fromJson( buildSubscriptionPeriodMap(dummySubscription)); expect(wrapper, equals(dummySubscription)); }); test( 'SKProductSubscriptionPeriodWrapper should have properties to be default values if map is empty', () { final SKProductSubscriptionPeriodWrapper wrapper = SKProductSubscriptionPeriodWrapper.fromJson( const <String, dynamic>{}); expect(wrapper.numberOfUnits, 0); expect(wrapper.unit, SKSubscriptionPeriodUnit.day); }); test( 'SKProductDiscountWrapper should have property values consistent with map', () { final SKProductDiscountWrapper wrapper = SKProductDiscountWrapper.fromJson(buildDiscountMap(dummyDiscount)); expect(wrapper, equals(dummyDiscount)); }); test( 'SKProductDiscountWrapper missing identifier and type should have ' 'property values consistent with map', () { final SKProductDiscountWrapper wrapper = SKProductDiscountWrapper.fromJson( buildDiscountMapMissingIdentifierAndType( dummyDiscountMissingIdentifierAndType)); expect(wrapper, equals(dummyDiscountMissingIdentifierAndType)); }); test( 'SKProductDiscountWrapper should have properties to be default if map is empty', () { final SKProductDiscountWrapper wrapper = SKProductDiscountWrapper.fromJson(const <String, dynamic>{}); expect(wrapper.price, ''); expect( wrapper.priceLocale, SKPriceLocaleWrapper( currencyCode: '', currencySymbol: '', countryCode: '', )); expect(wrapper.numberOfPeriods, 0); expect(wrapper.paymentMode, SKProductDiscountPaymentMode.payAsYouGo); expect( wrapper.subscriptionPeriod, SKProductSubscriptionPeriodWrapper( numberOfUnits: 0, unit: SKSubscriptionPeriodUnit.day)); }); test('SKProductWrapper should have property values consistent with map', () { final SKProductWrapper wrapper = SKProductWrapper.fromJson(buildProductMap(dummyProductWrapper)); expect(wrapper, equals(dummyProductWrapper)); }); test( 'SKProductWrapper should have properties to be default if map is empty', () { final SKProductWrapper wrapper = SKProductWrapper.fromJson(const <String, dynamic>{}); expect(wrapper.productIdentifier, ''); expect(wrapper.localizedTitle, ''); expect(wrapper.localizedDescription, ''); expect( wrapper.priceLocale, SKPriceLocaleWrapper( currencyCode: '', currencySymbol: '', countryCode: '', )); expect(wrapper.subscriptionGroupIdentifier, null); expect(wrapper.price, ''); expect(wrapper.subscriptionPeriod, null); expect(wrapper.discounts, <SKProductDiscountWrapper>[]); }); test('toProductDetails() should return correct Product object', () { final SKProductWrapper wrapper = SKProductWrapper.fromJson(buildProductMap(dummyProductWrapper)); final AppStoreProductDetails product = AppStoreProductDetails.fromSKProduct(wrapper); expect(product.title, wrapper.localizedTitle); expect(product.description, wrapper.localizedDescription); expect(product.id, wrapper.productIdentifier); expect(product.price, wrapper.priceLocale.currencySymbol + wrapper.price); expect(product.skProduct, wrapper); }); test('SKProductResponse wrapper should match', () { final SkProductResponseWrapper wrapper = SkProductResponseWrapper.fromJson( buildProductResponseMap(dummyProductResponseWrapper)); expect(wrapper, equals(dummyProductResponseWrapper)); }); test('SKProductResponse wrapper should default to empty list', () { final Map<String, List<dynamic>> productResponseMapEmptyList = <String, List<dynamic>>{ 'products': <Map<String, dynamic>>[], 'invalidProductIdentifiers': <String>[], }; final SkProductResponseWrapper wrapper = SkProductResponseWrapper.fromJson(productResponseMapEmptyList); expect(wrapper.products.length, 0); expect(wrapper.invalidProductIdentifiers.length, 0); }); test('LocaleWrapper should have property values consistent with map', () { final SKPriceLocaleWrapper wrapper = SKPriceLocaleWrapper.fromJson(buildLocaleMap(dollarLocale)); expect(wrapper, equals(dollarLocale)); }); }); group('Payment queue related object tests', () { test('Should construct correct SKPaymentWrapper from json', () { final SKPaymentWrapper payment = SKPaymentWrapper.fromJson(dummyPayment.toMap()); expect(payment, equals(dummyPayment)); }); test('SKPaymentWrapper should have propery values consistent with .toMap()', () { final Map<String, dynamic> mapResult = dummyPaymentWithDiscount.toMap(); expect(mapResult['productIdentifier'], dummyPaymentWithDiscount.productIdentifier); expect(mapResult['applicationUsername'], dummyPaymentWithDiscount.applicationUsername); expect(mapResult['requestData'], dummyPaymentWithDiscount.requestData); expect(mapResult['quantity'], dummyPaymentWithDiscount.quantity); expect(mapResult['simulatesAskToBuyInSandbox'], dummyPaymentWithDiscount.simulatesAskToBuyInSandbox); expect(mapResult['paymentDiscount'], equals(dummyPaymentWithDiscount.paymentDiscount?.toMap())); }); test('Should construct correct SKError from json', () { final SKError error = SKError.fromJson(buildErrorMap(dummyError)); expect(error, equals(dummyError)); }); test('Should construct correct SKTransactionWrapper from json', () { final SKPaymentTransactionWrapper transaction = SKPaymentTransactionWrapper.fromJson( buildTransactionMap(dummyTransaction)); expect(transaction, equals(dummyTransaction)); }); test('toPurchaseDetails() should return correct PurchaseDetail object', () { final AppStorePurchaseDetails details = AppStorePurchaseDetails.fromSKTransaction( dummyTransaction, 'receipt data'); expect(dummyTransaction.transactionIdentifier, details.purchaseID); expect(dummyTransaction.payment.productIdentifier, details.productID); expect(dummyTransaction.transactionTimeStamp, isNotNull); expect((dummyTransaction.transactionTimeStamp! * 1000).toInt().toString(), details.transactionDate); expect(details.verificationData.localVerificationData, 'receipt data'); expect(details.verificationData.serverVerificationData, 'receipt data'); expect(details.verificationData.source, 'app_store'); expect(details.skPaymentTransaction, dummyTransaction); expect(details.pendingCompletePurchase, true); }); test('SKPaymentTransactionWrapper.toFinishMap set correct value', () { final SKPaymentTransactionWrapper transactionWrapper = SKPaymentTransactionWrapper( payment: dummyPayment, transactionState: SKPaymentTransactionStateWrapper.failed, transactionIdentifier: 'abcd'); final Map<String, String?> finishMap = transactionWrapper.toFinishMap(); expect(finishMap['transactionIdentifier'], 'abcd'); expect(finishMap['productIdentifier'], dummyPayment.productIdentifier); }); test( 'SKPaymentTransactionWrapper.toFinishMap should set transactionIdentifier to null when necessary', () { final SKPaymentTransactionWrapper transactionWrapper = SKPaymentTransactionWrapper( payment: dummyPayment, transactionState: SKPaymentTransactionStateWrapper.failed); final Map<String, String?> finishMap = transactionWrapper.toFinishMap(); expect(finishMap['transactionIdentifier'], null); }); test('Should generate correct map of the payment object', () { final Map<String, Object?> map = dummyPayment.toMap(); expect(map['productIdentifier'], dummyPayment.productIdentifier); expect(map['applicationUsername'], dummyPayment.applicationUsername); expect(map['requestData'], dummyPayment.requestData); expect(map['quantity'], dummyPayment.quantity); expect(map['simulatesAskToBuyInSandbox'], dummyPayment.simulatesAskToBuyInSandbox); }); }); }
packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart", "repo_id": "packages", "token_count": 3417 }
1,009
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:ios_platform_images/ios_platform_images.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('resolves URL', (WidgetTester _) async { final String? path = await IosPlatformImages.resolveURL('textfile'); expect(Uri.parse(path!).scheme, 'file'); expect(path.contains('Runner.app'), isTrue); }); testWidgets('loads image', (WidgetTester _) async { final Completer<bool> successCompleter = Completer<bool>(); final ImageProvider<Object> provider = IosPlatformImages.load('flutter'); final ImageStream imageStream = provider.resolve(ImageConfiguration.empty); imageStream.addListener( ImageStreamListener((ImageInfo image, bool synchronousCall) { successCompleter.complete(true); }, onError: (Object e, StackTrace? _) { successCompleter.complete(false); })); final bool succeeded = await successCompleter.future; expect(succeeded, true); }); }
packages/packages/ios_platform_images/example/integration_test/ios_platform_images_test.dart/0
{ "file_path": "packages/packages/ios_platform_images/example/integration_test/ios_platform_images_test.dart", "repo_id": "packages", "token_count": 429 }
1,010
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.localauth; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.Settings; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricPrompt; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleOwner; import java.util.concurrent.Executor; /** * Authenticates the user with biometrics and sends corresponding response back to Flutter. * * <p>One instance per call is generated to ensure readable separation of executable paths across * method calls. */ class AuthenticationHelper extends BiometricPrompt.AuthenticationCallback implements Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver { /** The callback that handles the result of this authentication process. */ interface AuthCompletionHandler { /** Called when authentication attempt is complete. */ void complete(Messages.AuthResult authResult); } // This is null when not using v2 embedding; private final Lifecycle lifecycle; private final FragmentActivity activity; private final AuthCompletionHandler completionHandler; private final boolean useErrorDialogs; private final Messages.AuthStrings strings; private final BiometricPrompt.PromptInfo promptInfo; private final boolean isAuthSticky; private final UiThreadExecutor uiThreadExecutor; private boolean activityPaused = false; private BiometricPrompt biometricPrompt; AuthenticationHelper( Lifecycle lifecycle, FragmentActivity activity, @NonNull Messages.AuthOptions options, @NonNull Messages.AuthStrings strings, @NonNull AuthCompletionHandler completionHandler, boolean allowCredentials) { this.lifecycle = lifecycle; this.activity = activity; this.completionHandler = completionHandler; this.strings = strings; this.isAuthSticky = options.getSticky(); this.useErrorDialogs = options.getUseErrorDialgs(); this.uiThreadExecutor = new UiThreadExecutor(); BiometricPrompt.PromptInfo.Builder promptBuilder = new BiometricPrompt.PromptInfo.Builder() .setDescription(strings.getReason()) .setTitle(strings.getSignInTitle()) .setSubtitle(strings.getBiometricHint()) .setConfirmationRequired(options.getSensitiveTransaction()); int allowedAuthenticators = BiometricManager.Authenticators.BIOMETRIC_WEAK | BiometricManager.Authenticators.BIOMETRIC_STRONG; if (allowCredentials) { allowedAuthenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL; } else { promptBuilder.setNegativeButtonText(strings.getCancelButton()); } promptBuilder.setAllowedAuthenticators(allowedAuthenticators); this.promptInfo = promptBuilder.build(); } /** Start the biometric listener. */ void authenticate() { if (lifecycle != null) { lifecycle.addObserver(this); } else { activity.getApplication().registerActivityLifecycleCallbacks(this); } biometricPrompt = new BiometricPrompt(activity, uiThreadExecutor, this); biometricPrompt.authenticate(promptInfo); } /** Cancels the biometric authentication. */ void stopAuthentication() { if (biometricPrompt != null) { biometricPrompt.cancelAuthentication(); biometricPrompt = null; } } /** Stops the biometric listener. */ private void stop() { if (lifecycle != null) { lifecycle.removeObserver(this); return; } activity.getApplication().unregisterActivityLifecycleCallbacks(this); } @SuppressLint("SwitchIntDef") @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { switch (errorCode) { case BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL: if (useErrorDialogs) { showGoToSettingsDialog( strings.getDeviceCredentialsRequiredTitle(), strings.getDeviceCredentialsSetupDescription()); return; } completionHandler.complete(Messages.AuthResult.ERROR_NOT_AVAILABLE); break; case BiometricPrompt.ERROR_NO_SPACE: case BiometricPrompt.ERROR_NO_BIOMETRICS: if (useErrorDialogs) { showGoToSettingsDialog( strings.getBiometricRequiredTitle(), strings.getGoToSettingsDescription()); return; } completionHandler.complete(Messages.AuthResult.ERROR_NOT_ENROLLED); break; case BiometricPrompt.ERROR_HW_UNAVAILABLE: case BiometricPrompt.ERROR_HW_NOT_PRESENT: completionHandler.complete(Messages.AuthResult.ERROR_NOT_AVAILABLE); break; case BiometricPrompt.ERROR_LOCKOUT: completionHandler.complete(Messages.AuthResult.ERROR_LOCKED_OUT_TEMPORARILY); break; case BiometricPrompt.ERROR_LOCKOUT_PERMANENT: completionHandler.complete(Messages.AuthResult.ERROR_LOCKED_OUT_PERMANENTLY); break; case BiometricPrompt.ERROR_CANCELED: // If we are doing sticky auth and the activity has been paused, // ignore this error. We will start listening again when resumed. if (activityPaused && isAuthSticky) { return; } else { completionHandler.complete(Messages.AuthResult.FAILURE); } break; default: completionHandler.complete(Messages.AuthResult.FAILURE); } stop(); } @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { completionHandler.complete(Messages.AuthResult.SUCCESS); stop(); } @Override public void onAuthenticationFailed() {} /** * If the activity is paused, we keep track because biometric dialog simply returns "User * cancelled" when the activity is paused. */ @Override public void onActivityPaused(Activity ignored) { if (isAuthSticky) { activityPaused = true; } } @Override public void onActivityResumed(Activity ignored) { if (isAuthSticky) { activityPaused = false; final BiometricPrompt prompt = new BiometricPrompt(activity, uiThreadExecutor, this); // When activity is resuming, we cannot show the prompt right away. We need to post it to the // UI queue. uiThreadExecutor.handler.post(() -> prompt.authenticate(promptInfo)); } } @Override public void onPause(@NonNull LifecycleOwner owner) { onActivityPaused(null); } @Override public void onResume(@NonNull LifecycleOwner owner) { onActivityResumed(null); } // Suppress inflateParams lint because dialogs do not need to attach to a parent view. @SuppressLint("InflateParams") private void showGoToSettingsDialog(String title, String descriptionText) { View view = LayoutInflater.from(activity).inflate(R.layout.go_to_setting, null, false); TextView message = view.findViewById(R.id.fingerprint_required); TextView description = view.findViewById(R.id.go_to_setting_description); message.setText(title); description.setText(descriptionText); Context context = new ContextThemeWrapper(activity, R.style.AlertDialogCustom); OnClickListener goToSettingHandler = (dialog, which) -> { completionHandler.complete(Messages.AuthResult.FAILURE); stop(); activity.startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS)); }; OnClickListener cancelHandler = (dialog, which) -> { completionHandler.complete(Messages.AuthResult.FAILURE); stop(); }; new AlertDialog.Builder(context) .setView(view) .setPositiveButton(strings.getGoToSettingsButton(), goToSettingHandler) .setNegativeButton(strings.getCancelButton(), cancelHandler) .setCancelable(false) .show(); } // Unused methods for activity lifecycle. @Override public void onActivityCreated(Activity activity, Bundle bundle) {} @Override public void onActivityStarted(Activity activity) {} @Override public void onActivityStopped(Activity activity) {} @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {} @Override public void onActivityDestroyed(Activity activity) {} @Override public void onDestroy(@NonNull LifecycleOwner owner) {} @Override public void onStop(@NonNull LifecycleOwner owner) {} @Override public void onStart(@NonNull LifecycleOwner owner) {} @Override public void onCreate(@NonNull LifecycleOwner owner) {} static class UiThreadExecutor implements Executor { final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable command) { handler.post(command); } } }
packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/AuthenticationHelper.java/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/AuthenticationHelper.java", "repo_id": "packages", "token_count": 3187 }
1,011
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.0), 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'; /// Possible outcomes of an authentication attempt. enum AuthResult { /// The user authenticated successfully. success, /// The user failed to successfully authenticate. failure, /// An authentication was already in progress. errorAlreadyInProgress, /// There is no foreground activity. errorNoActivity, /// The foreground activity is not a FragmentActivity. errorNotFragmentActivity, /// The authentication system was not available. errorNotAvailable, /// No biometrics are enrolled. errorNotEnrolled, /// The user is locked out temporarily due to too many failed attempts. errorLockedOutTemporarily, /// The user is locked out until they log in another way due to too many /// failed attempts. errorLockedOutPermanently, } /// Pigeon equivalent of the subset of BiometricType used by Android. enum AuthClassification { weak, strong, } /// Pigeon version of AndroidAuthStrings, plus the authorization reason. /// /// See auth_messages_android.dart for details. class AuthStrings { AuthStrings({ required this.reason, required this.biometricHint, required this.biometricNotRecognized, required this.biometricRequiredTitle, required this.cancelButton, required this.deviceCredentialsRequiredTitle, required this.deviceCredentialsSetupDescription, required this.goToSettingsButton, required this.goToSettingsDescription, required this.signInTitle, }); String reason; String biometricHint; String biometricNotRecognized; String biometricRequiredTitle; String cancelButton; String deviceCredentialsRequiredTitle; String deviceCredentialsSetupDescription; String goToSettingsButton; String goToSettingsDescription; String signInTitle; Object encode() { return <Object?>[ reason, biometricHint, biometricNotRecognized, biometricRequiredTitle, cancelButton, deviceCredentialsRequiredTitle, deviceCredentialsSetupDescription, goToSettingsButton, goToSettingsDescription, signInTitle, ]; } static AuthStrings decode(Object result) { result as List<Object?>; return AuthStrings( reason: result[0]! as String, biometricHint: result[1]! as String, biometricNotRecognized: result[2]! as String, biometricRequiredTitle: result[3]! as String, cancelButton: result[4]! as String, deviceCredentialsRequiredTitle: result[5]! as String, deviceCredentialsSetupDescription: result[6]! as String, goToSettingsButton: result[7]! as String, goToSettingsDescription: result[8]! as String, signInTitle: result[9]! as String, ); } } class AuthOptions { AuthOptions({ required this.biometricOnly, required this.sensitiveTransaction, required this.sticky, required this.useErrorDialgs, }); bool biometricOnly; bool sensitiveTransaction; bool sticky; bool useErrorDialgs; Object encode() { return <Object?>[ biometricOnly, sensitiveTransaction, sticky, useErrorDialgs, ]; } static AuthOptions decode(Object result) { result as List<Object?>; return AuthOptions( biometricOnly: result[0]! as bool, sensitiveTransaction: result[1]! as bool, sticky: result[2]! as bool, useErrorDialgs: result[3]! as bool, ); } } class AuthClassificationWrapper { AuthClassificationWrapper({ required this.value, }); AuthClassification value; Object encode() { return <Object?>[ value.index, ]; } static AuthClassificationWrapper decode(Object result) { result as List<Object?>; return AuthClassificationWrapper( value: AuthClassification.values[result[0]! as int], ); } } class _LocalAuthApiCodec extends StandardMessageCodec { const _LocalAuthApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is AuthClassificationWrapper) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is AuthOptions) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is AuthStrings) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return AuthClassificationWrapper.decode(readValue(buffer)!); case 129: return AuthOptions.decode(readValue(buffer)!); case 130: return AuthStrings.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class LocalAuthApi { /// Constructor for [LocalAuthApi]. 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. LocalAuthApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _LocalAuthApiCodec(); /// Returns true if this device supports authentication. Future<bool> isDeviceSupported() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.isDeviceSupported', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Returns true if this device can support biometric authentication, whether /// any biometrics are enrolled or not. Future<bool> deviceCanSupportBiometrics() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.deviceCanSupportBiometrics', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Cancels any in-progress authentication. /// /// Returns true only if authentication was in progress, and was successfully /// cancelled. Future<bool> stopAuthentication() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.stopAuthentication', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Returns the biometric types that are enrolled, and can thus be used /// without additional setup. Future<List<AuthClassificationWrapper?>> getEnrolledBiometrics() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.getEnrolledBiometrics', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)! .cast<AuthClassificationWrapper?>(); } } /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. Future<AuthResult> authenticate( AuthOptions arg_options, AuthStrings arg_strings) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.authenticate', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_options, arg_strings]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return AuthResult.values[replyList[0]! as int]; } } }
packages/packages/local_auth/local_auth_android/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_android/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 4050 }
1,012
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 1.0.10 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 1.0.9 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 1.0.8 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Updates minimum Flutter version to 3.3. * Aligns Dart and Flutter SDK constraints. ## 1.0.7 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 1.0.6 * Removes unused `intl` dependency. ## 1.0.5 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 1.0.4 * Updates references to the obsolete master branch. * Removes unnecessary imports. ## 1.0.3 * Fixes regression in the default method channel implementation of `deviceSupportsBiometrics` from federation that would cause it to return true only if something is enrolled. ## 1.0.2 * Adopts `Object.hash`. ## 1.0.1 * Export externally used types from local_auth_platform_interface.dart directly. ## 1.0.0 * Initial release.
packages/packages/local_auth/local_auth_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/local_auth/local_auth_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 378 }
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. #include <winstring.h> #include "local_auth.h" #include "messages.g.h" namespace { // Returns the window's HWND for a given FlutterView. HWND GetRootWindow(flutter::FlutterView* view) { return ::GetAncestor(view->GetNativeWindow(), GA_ROOT); } // Converts the given UTF-8 string to UTF-16. std::wstring Utf16FromUtf8(const std::string& utf8_string) { if (utf8_string.empty()) { return std::wstring(); } int target_length = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(), static_cast<int>(utf8_string.length()), nullptr, 0); if (target_length == 0) { return std::wstring(); } std::wstring utf16_string; utf16_string.resize(target_length); int converted_length = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(), static_cast<int>(utf8_string.length()), utf16_string.data(), target_length); if (converted_length == 0) { return std::wstring(); } return utf16_string; } } // namespace namespace local_auth_windows { // Creates an instance of the UserConsentVerifier that // calls the native Windows APIs to get the user's consent. class UserConsentVerifierImpl : public UserConsentVerifier { public: explicit UserConsentVerifierImpl(std::function<HWND()> window_provider) : get_root_window_(std::move(window_provider)){}; virtual ~UserConsentVerifierImpl() = default; // Calls the native Windows API to get the user's consent // with the provided reason. winrt::Windows::Foundation::IAsyncOperation< winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult> RequestVerificationForWindowAsync(std::wstring localized_reason) override { winrt::impl::com_ref<IUserConsentVerifierInterop> user_consent_verifier_interop = winrt::get_activation_factory< winrt::Windows::Security::Credentials::UI::UserConsentVerifier, IUserConsentVerifierInterop>(); HWND root_window_handle = get_root_window_(); auto reason = wil::make_unique_string<wil::unique_hstring>( localized_reason.c_str(), localized_reason.size()); winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult consent_result = co_await winrt::capture< winrt::Windows::Foundation::IAsyncOperation< winrt::Windows::Security::Credentials::UI:: UserConsentVerificationResult>>( user_consent_verifier_interop, &::IUserConsentVerifierInterop::RequestVerificationForWindowAsync, root_window_handle, reason.get()); return consent_result; } // Calls the native Windows API to check for the Windows Hello availability. winrt::Windows::Foundation::IAsyncOperation< winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability> CheckAvailabilityAsync() override { return winrt::Windows::Security::Credentials::UI::UserConsentVerifier:: CheckAvailabilityAsync(); } // Disallow copy and move. UserConsentVerifierImpl(const UserConsentVerifierImpl&) = delete; UserConsentVerifierImpl& operator=(const UserConsentVerifierImpl&) = delete; private: // The provider for the root window to attach the dialog to. std::function<HWND()> get_root_window_; }; // static void LocalAuthPlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows* registrar) { auto plugin = std::make_unique<LocalAuthPlugin>( [registrar]() { return GetRootWindow(registrar->GetView()); }); LocalAuthApi::SetUp(registrar->messenger(), plugin.get()); registrar->AddPlugin(std::move(plugin)); } // Default constructor for LocalAuthPlugin. LocalAuthPlugin::LocalAuthPlugin(std::function<HWND()> window_provider) : user_consent_verifier_(std::make_unique<UserConsentVerifierImpl>( std::move(window_provider))) {} LocalAuthPlugin::LocalAuthPlugin( std::unique_ptr<UserConsentVerifier> user_consent_verifier) : user_consent_verifier_(std::move(user_consent_verifier)) {} LocalAuthPlugin::~LocalAuthPlugin() {} void LocalAuthPlugin::IsDeviceSupported( std::function<void(ErrorOr<bool> reply)> result) { IsDeviceSupportedCoroutine(std::move(result)); } void LocalAuthPlugin::Authenticate( const std::string& localized_reason, std::function<void(ErrorOr<bool> reply)> result) { AuthenticateCoroutine(localized_reason, std::move(result)); } // Starts authentication process. winrt::fire_and_forget LocalAuthPlugin::AuthenticateCoroutine( const std::string& localized_reason, std::function<void(ErrorOr<bool> reply)> result) { std::wstring reason = Utf16FromUtf8(localized_reason); winrt::Windows::Security::Credentials::UI::UserConsentVerifierAvailability ucv_availability = co_await user_consent_verifier_->CheckAvailabilityAsync(); if (ucv_availability == winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability::DeviceNotPresent) { result(FlutterError("NoHardware", "No biometric hardware found")); co_return; } else if (ucv_availability == winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability::NotConfiguredForUser) { result( FlutterError("NotEnrolled", "No biometrics enrolled on this device.")); co_return; } else if (ucv_availability != winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability::Available) { result( FlutterError("NotAvailable", "Required security features not enabled")); co_return; } try { winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult consent_result = co_await user_consent_verifier_->RequestVerificationForWindowAsync( reason); result(consent_result == winrt::Windows::Security::Credentials::UI:: UserConsentVerificationResult::Verified); } catch (...) { result(false); } } // Returns whether the device supports Windows Hello or not. winrt::fire_and_forget LocalAuthPlugin::IsDeviceSupportedCoroutine( std::function<void(ErrorOr<bool> reply)> result) { winrt::Windows::Security::Credentials::UI::UserConsentVerifierAvailability ucv_availability = co_await user_consent_verifier_->CheckAvailabilityAsync(); result(ucv_availability == winrt::Windows::Security::Credentials::UI:: UserConsentVerifierAvailability::Available); } } // namespace local_auth_windows
packages/packages/local_auth/local_auth_windows/windows/local_auth_plugin.cpp/0
{ "file_path": "packages/packages/local_auth/local_auth_windows/windows/local_auth_plugin.cpp", "repo_id": "packages", "token_count": 2469 }
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. // ignore_for_file: avoid_print import 'package:googleapis/storage/v1.dart'; /// Global (in terms of earth) mutex using Google Cloud Storage. class GcsLock { /// Create a lock with an authenticated client and a GCS bucket name. /// /// The client is used to communicate with Google Cloud Storage APIs. GcsLock(this._api, this._bucketName); /// Create a temporary lock file in GCS, and use it as a mutex mechanism to /// run a piece of code exclusively. /// /// There must be no existing lock file with the same name in order to /// proceed. If multiple [GcsLock]s with the same `bucketName` and /// `lockFileName` try [protectedRun] simultaneously, only one will proceed /// and create the lock file. All others will be blocked. /// /// When [protectedRun] finishes, the lock file is deleted, and other blocked /// [protectedRun] may proceed. /// /// If the lock file is stuck (e.g., `_unlock` is interrupted unexpectedly), /// one may need to manually delete the lock file from GCS to unblock any /// [protectedRun] that may depend on it. Future<void> protectedRun( String lockFileName, Future<void> Function() f) async { await _lock(lockFileName); try { await f(); } catch (e, stacktrace) { print(stacktrace); rethrow; } finally { await _unlock(lockFileName); } } Future<void> _lock(String lockFileName) async { final Object object = Object(); object.bucket = _bucketName; object.name = lockFileName; final Media content = Media(const Stream<List<int>>.empty(), 0); Duration waitPeriod = const Duration(milliseconds: 10); bool locked = false; while (!locked) { try { await _api.objects.insert(object, _bucketName, ifGenerationMatch: '0', uploadMedia: content); locked = true; } on DetailedApiRequestError catch (e) { if (e.status == 412) { // Status 412 means that the lock file already exists. Wait until // that lock file is deleted. await Future<void>.delayed(waitPeriod); waitPeriod *= 2; if (waitPeriod >= _kWarningThreshold) { print( 'The lock is waiting for a long time: $waitPeriod. ' 'If the lock file $lockFileName in bucket $_bucketName ' 'seems to be stuck (i.e., it was created a long time ago and ' 'no one seems to be owning it currently), delete it manually ' 'to unblock this.', ); } } else { rethrow; } } } } Future<void> _unlock(String lockFileName) async { Duration waitPeriod = const Duration(milliseconds: 10); bool unlocked = false; // Retry in the case of GCS returning an API error, but rethrow if unable // to unlock after a certain period of time. while (!unlocked) { try { await _api.objects.delete(_bucketName, lockFileName); unlocked = true; } on DetailedApiRequestError { if (waitPeriod < _unlockThreshold) { await Future<void>.delayed(waitPeriod); waitPeriod *= 2; } else { rethrow; } } } } final String _bucketName; final StorageApi _api; static const Duration _kWarningThreshold = Duration(seconds: 10); static const Duration _unlockThreshold = Duration(minutes: 1); }
packages/packages/metrics_center/lib/src/gcs_lock.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/gcs_lock.dart", "repo_id": "packages", "token_count": 1320 }
1,015
# Multicast DNS package [![pub package](https://img.shields.io/pub/v/multicast_dns.svg)]( https://pub.dartlang.org/packages/multicast_dns) A Dart package to do service discovery over multicast DNS (mDNS), Bonjour, and Avahi. ## Usage To use this package, add `multicast_dns` as a [dependency in your pubspec.yaml file](https://pub.dev/packages/multicast_dns/install). [The example](https://pub.dev/packages/multicast_dns/example) demonstrates how to use the `MDnsClient` Dart class in your code.
packages/packages/multicast_dns/README.md/0
{ "file_path": "packages/packages/multicast_dns/README.md", "repo_id": "packages", "token_count": 177 }
1,016
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print // Support code to generate the hex-lists in test/decode_test.dart from // a hex-stream. import 'dart:io'; void formatHexStream(String hexStream) { String s = ''; for (int i = 0; i < hexStream.length / 2; i++) { if (s.isNotEmpty) { s += ', '; } s += '0x'; final String x = hexStream.substring(i * 2, i * 2 + 2); s += x; if (((i + 1) % 8) == 0) { s += ','; print(s); s = ''; } } if (s.isNotEmpty) { print(s); } } // Support code for generating the hex-lists in test/decode_test.dart. void hexDumpList(List<int> package) { String s = ''; for (int i = 0; i < package.length; i++) { if (s.isNotEmpty) { s += ', '; } s += '0x'; final String x = package[i].toRadixString(16); if (x.length == 1) { s += '0'; } s += x; if (((i + 1) % 8) == 0) { s += ','; print(s); s = ''; } } if (s.isNotEmpty) { print(s); } } void dumpDatagram(Datagram datagram) { String toHex(List<int> ints) { final StringBuffer buffer = StringBuffer(); for (int i = 0; i < ints.length; i++) { buffer.write(ints[i].toRadixString(16).padLeft(2, '0')); if ((i + 1) % 10 == 0) { buffer.writeln(); } else { buffer.write(' '); } } return buffer.toString(); } print('${datagram.address.address}:${datagram.port}:'); print(toHex(datagram.data)); print(''); }
packages/packages/multicast_dns/tool/packet_gen.dart/0
{ "file_path": "packages/packages/multicast_dns/tool/packet_gen.dart", "repo_id": "packages", "token_count": 730 }
1,017
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.pathproviderexample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="path_provider_example" android:icon="@mipmap/ic_launcher"> <activity android:name="io.flutter.embedding.android.FlutterActivity" android:launchMode="singleTop" android:theme="@android:style/Theme.Black.NoTitleBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> </application> </manifest>
packages/packages/path_provider/path_provider/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/path_provider/path_provider/example/android/app/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 434 }
1,018
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/path_provider/path_provider_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,019
name: path_provider_foundation description: iOS and macOS implementation of the path_provider plugin repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_foundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.3.2 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: path_provider platforms: ios: pluginClass: PathProviderPlugin dartPluginClass: PathProviderFoundation sharedDarwinSource: true macos: pluginClass: PathProviderPlugin dartPluginClass: PathProviderFoundation sharedDarwinSource: true dependencies: flutter: sdk: flutter path_provider_platform_interface: ^2.1.0 dev_dependencies: build_runner: ^2.3.2 flutter_test: sdk: flutter mockito: 5.4.4 path: ^1.8.0 pigeon: ^10.1.3 topics: - files - path-provider - paths
packages/packages/path_provider/path_provider_foundation/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/pubspec.yaml", "repo_id": "packages", "token_count": 396 }
1,020
# pigeon_example_app This demonstrates using Pigeon for platform communication directly in an application, rather than in a plugin. To update the generated code, run: ```sh cd ../.. dart tool/generate.dart ```
packages/packages/pigeon/example/app/README.md/0
{ "file_path": "packages/packages/pigeon/example/app/README.md", "repo_id": "packages", "token_count": 62 }
1,021
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // 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".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } enum Code { one, two, } class MessageData { MessageData({ this.name, this.description, required this.code, required this.data, }); String? name; String? description; Code code; Map<String?, String?> data; Object encode() { return <Object?>[ name, description, code.index, data, ]; } static MessageData decode(Object result) { result as List<Object?>; return MessageData( name: result[0] as String?, description: result[1] as String?, code: Code.values[result[2]! as int], data: (result[3] as Map<Object?, Object?>?)!.cast<String?, String?>(), ); } } class _ExampleHostApiCodec extends StandardMessageCodec { const _ExampleHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class ExampleHostApi { /// Constructor for [ExampleHostApi]. 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. ExampleHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = _ExampleHostApiCodec(); Future<String> getHostLanguage() async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) 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 String?)!; } } Future<int> add(int a, int b) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[a, b]) 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?)!; } } Future<bool> sendMessage(MessageData message) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[message]) 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 bool?)!; } } } abstract class MessageFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); String flutterMethod(String? aString); static void setup(MessageFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_aString = (args[0] as String?); try { final String output = api.flutterMethod(arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/pigeon/example/app/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/pigeon/example/app/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 2961 }
1,022
name: pigeon_example_app description: An example of using Pigeon in an application. publish_to: 'none' version: 1.0.0 environment: sdk: ^3.1.0 dependencies: flutter: sdk: flutter dev_dependencies: build_runner: ^2.1.10 flutter_test: sdk: flutter integration_test: sdk: flutter # When depending on this package from a real application you should use: # file_selector_windows: ^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. pigeon: path: ../../ flutter: uses-material-design: true
packages/packages/pigeon/example/app/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/example/app/pubspec.yaml", "repo_id": "packages", "token_count": 249 }
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 'ast.dart'; import 'functional.dart'; import 'generator.dart'; import 'generator_tools.dart'; import 'pigeon_lib.dart' show Error, TaskQueueType; /// Documentation comment open symbol. const String _docCommentPrefix = '///'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification(_docCommentPrefix); /// Options that control how Objective-C code will be generated. class ObjcOptions { /// Parametric constructor for ObjcOptions. const ObjcOptions({ this.headerIncludePath, this.prefix, this.copyrightHeader, }); /// The path to the header that will get placed in the source filed (example: /// "foo.h"). final String? headerIncludePath; /// Prefix that will be appended before all generated classes and protocols. final String? prefix; /// A copyright header that will get prepended to generated code. final Iterable<String>? copyrightHeader; /// Creates a [ObjcOptions] from a Map representation where: /// `x = ObjcOptions.fromMap(x.toMap())`. static ObjcOptions fromMap(Map<String, Object> map) { final Iterable<dynamic>? copyrightHeader = map['copyrightHeader'] as Iterable<dynamic>?; return ObjcOptions( headerIncludePath: map['header'] as String?, prefix: map['prefix'] as String?, copyrightHeader: copyrightHeader?.cast<String>(), ); } /// Converts a [ObjcOptions] to a Map representation where: /// `x = ObjcOptions.fromMap(x.toMap())`. Map<String, Object> toMap() { final Map<String, Object> result = <String, Object>{ if (headerIncludePath != null) 'header': headerIncludePath!, if (prefix != null) 'prefix': prefix!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, }; return result; } /// Overrides any non-null parameters from [options] into this to make a new /// [ObjcOptions]. ObjcOptions merge(ObjcOptions options) { return ObjcOptions.fromMap(mergeMaps(toMap(), options.toMap())); } } /// Class that manages all Objc code generation. class ObjcGenerator extends Generator<OutputFileOptions<ObjcOptions>> { /// Instantiates a Objc Generator. const ObjcGenerator(); /// Generates Objc file of type specified in [generatorOptions] @override void generate( OutputFileOptions<ObjcOptions> generatorOptions, Root root, StringSink sink, { required String dartPackageName, }) { if (generatorOptions.fileType == FileType.header) { const ObjcHeaderGenerator().generate( generatorOptions.languageOptions, root, sink, dartPackageName: dartPackageName, ); } else if (generatorOptions.fileType == FileType.source) { const ObjcSourceGenerator().generate( generatorOptions.languageOptions, root, sink, dartPackageName: dartPackageName, ); } } } /// Generates Objc .h file. class ObjcHeaderGenerator extends StructuredGenerator<ObjcOptions> { /// Constructor. const ObjcHeaderGenerator(); @override void writeFilePrologue( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.copyrightHeader != null) { addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// '); } indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); indent.newln(); } @override void writeFileImports( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.writeln('#import <Foundation/Foundation.h>'); indent.newln(); indent.writeln('@protocol FlutterBinaryMessenger;'); indent.writeln('@protocol FlutterMessageCodec;'); indent.writeln('@class FlutterError;'); indent.writeln('@class FlutterStandardTypedData;'); indent.newln(); indent.writeln('NS_ASSUME_NONNULL_BEGIN'); } @override void writeEnum( ObjcOptions generatorOptions, Root root, Indent indent, Enum anEnum, { required String dartPackageName, }) { final String enumName = _enumName(anEnum.name, prefix: generatorOptions.prefix); indent.newln(); addDocumentationComments( indent, anEnum.documentationComments, _docCommentSpec); indent.write('typedef NS_ENUM(NSUInteger, $enumName) '); indent.addScoped('{', '};', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( indent, member.documentationComments, _docCommentSpec); // Capitalized first letter to ensure Swift compatibility indent.writeln( '$enumName${member.name[0].toUpperCase()}${member.name.substring(1)} = $index,'); }); }); _writeEnumWrapper(indent, enumName); } void _writeEnumWrapper(Indent indent, String enumName) { indent.newln(); indent.writeln('/// Wrapper for $enumName to allow for nullability.'); indent.writeln( '@interface ${_enumName(enumName, prefix: '', box: true)} : NSObject'); indent.writeln('@property(nonatomic, assign) $enumName value;'); indent.writeln('- (instancetype)initWithValue:($enumName)value;'); indent.writeln('@end'); } @override void writeDataClasses( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.newln(); for (final Class classDefinition in root.classes) { indent.writeln( '@class ${_className(generatorOptions.prefix, classDefinition.name)};'); } indent.newln(); super.writeDataClasses( generatorOptions, root, indent, dartPackageName: dartPackageName, ); } @override void writeDataClass( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { final List<Class> classes = root.classes; final List<Enum> enums = root.enums; final String? prefix = generatorOptions.prefix; addDocumentationComments( indent, classDefinition.documentationComments, _docCommentSpec); indent.writeln( '@interface ${_className(prefix, classDefinition.name)} : NSObject'); if (getFieldsInSerializationOrder(classDefinition).isNotEmpty) { if (getFieldsInSerializationOrder(classDefinition) .map((NamedType e) => !e.type.isNullable) .any((bool e) => e)) { indent.writeln( '$_docCommentPrefix `init` unavailable to enforce nonnull fields, see the `make` class method.'); indent.writeln('- (instancetype)init NS_UNAVAILABLE;'); } _writeObjcSourceClassInitializerDeclaration( indent, generatorOptions, root, classDefinition, classes, enums, prefix, ); indent.addln(';'); } for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), customResolver: field.type.isEnum ? (String x) => _enumName(x, prefix: prefix) : (String x) => '${_className(prefix, x)} *'); late final String propertyType; addDocumentationComments( indent, field.documentationComments, _docCommentSpec); propertyType = _propertyTypeForDartType(field.type, isNullable: field.type.isNullable, isEnum: field.type.isEnum); final String nullability = field.type.isNullable ? ', nullable' : ''; final String fieldType = field.type.isEnum && field.type.isNullable ? _enumName(field.type.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: field.type.isNullable) : hostDatatype.datatype; indent.writeln( '@property(nonatomic, $propertyType$nullability) $fieldType ${field.name};'); } indent.writeln('@end'); indent.newln(); } @override void writeClassEncode( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) {} @override void writeClassDecode( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) {} @override void writeApis( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { super.writeApis(generatorOptions, root, indent, dartPackageName: dartPackageName); indent.writeln('NS_ASSUME_NONNULL_END'); } @override void writeFlutterApi( ObjcOptions generatorOptions, Root root, Indent indent, Api api, { required String dartPackageName, }) { indent.writeln( '$_docCommentPrefix The codec used by ${_className(generatorOptions.prefix, api.name)}.'); indent.writeln( 'NSObject<FlutterMessageCodec> *${_getCodecGetterName(generatorOptions.prefix, api.name)}(void);'); indent.newln(); final String apiName = _className(generatorOptions.prefix, api.name); addDocumentationComments( indent, api.documentationComments, _docCommentSpec); indent.writeln('@interface $apiName : NSObject'); indent.writeln( '- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;'); for (final Method func in api.methods) { final _ObjcType returnType = _objcTypeForDartType( generatorOptions.prefix, func.returnType, // Nullability is required since the return must be nil if NSError is set. forceNullability: true, ); final String callbackType = _callbackForType(func.returnType, returnType, generatorOptions); addDocumentationComments( indent, func.documentationComments, _docCommentSpec); indent.writeln('${_makeObjcSignature( func: func, options: generatorOptions, returnType: 'void', lastArgName: 'completion', lastArgType: callbackType, )};'); } indent.writeln('@end'); indent.newln(); } @override void writeHostApi( ObjcOptions generatorOptions, Root root, Indent indent, Api api, { required String dartPackageName, }) { indent.writeln( '$_docCommentPrefix The codec used by ${_className(generatorOptions.prefix, api.name)}.'); indent.writeln( 'NSObject<FlutterMessageCodec> *${_getCodecGetterName(generatorOptions.prefix, api.name)}(void);'); indent.newln(); final String apiName = _className(generatorOptions.prefix, api.name); addDocumentationComments( indent, api.documentationComments, _docCommentSpec); indent.writeln('@protocol $apiName'); for (final Method func in api.methods) { final _ObjcType returnTypeName = _objcTypeForDartType( generatorOptions.prefix, func.returnType, // Nullability is required since the return must be nil if NSError is // set. forceNullability: true, ); String? lastArgName; String? lastArgType; String? returnType; final String enumReturnType = _enumName( func.returnType.baseName, suffix: ' *_Nullable', prefix: generatorOptions.prefix, box: true, ); if (func.isAsynchronous) { returnType = 'void'; lastArgName = 'completion'; if (func.returnType.isVoid) { lastArgType = 'void (^)(FlutterError *_Nullable)'; } else if (func.returnType.isEnum) { lastArgType = 'void (^)($enumReturnType, FlutterError *_Nullable)'; } else { lastArgType = 'void (^)(${returnTypeName.beforeString}_Nullable, FlutterError *_Nullable)'; } } else { if (func.returnType.isVoid) { returnType = 'void'; } else if (func.returnType.isEnum) { returnType = enumReturnType; } else { returnType = 'nullable $returnTypeName'; } lastArgType = 'FlutterError *_Nullable *_Nonnull'; lastArgName = 'error'; } final List<String> generatorComments = <String>[]; if (!func.returnType.isNullable && !func.returnType.isVoid && !func.isAsynchronous) { generatorComments.add(' @return `nil` only when `error != nil`.'); } addDocumentationComments( indent, func.documentationComments, _docCommentSpec, generatorComments: generatorComments); final String signature = _makeObjcSignature( func: func, options: generatorOptions, returnType: returnType, lastArgName: lastArgName, lastArgType: lastArgType, ); indent.writeln('$signature;'); } indent.writeln('@end'); indent.newln(); indent.writeln( 'extern void SetUp$apiName(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *_Nullable api);'); indent.newln(); } } /// Generates Objc .m file. class ObjcSourceGenerator extends StructuredGenerator<ObjcOptions> { /// Constructor. const ObjcSourceGenerator(); @override void writeFilePrologue( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.copyrightHeader != null) { addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// '); } indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); indent.newln(); } @override void writeFileImports( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.writeln('#import "${generatorOptions.headerIncludePath}"'); indent.newln(); indent.writeln('#if TARGET_OS_OSX'); indent.writeln('#import <FlutterMacOS/FlutterMacOS.h>'); indent.writeln('#else'); indent.writeln('#import <Flutter/Flutter.h>'); indent.writeln('#endif'); indent.newln(); indent.writeln('#if !__has_feature(objc_arc)'); indent.writeln('#error File requires ARC to be enabled.'); indent.writeln('#endif'); indent.newln(); } @override void writeEnum( ObjcOptions generatorOptions, Root root, Indent indent, Enum anEnum, { required String dartPackageName, }) { final String enumName = _enumName(anEnum.name, prefix: generatorOptions.prefix); indent.newln(); addDocumentationComments( indent, anEnum.documentationComments, _docCommentSpec); indent.writeln( '@implementation ${_enumName(enumName, prefix: '', box: true)}'); indent.writeScoped('- (instancetype)initWithValue:($enumName)value {', '}', () { indent.writeln('self = [super init];'); indent.writeScoped('if (self) {', '}', () { indent.writeln('_value = value;'); }); indent.writeln('return self;'); }); indent.writeln('@end'); } @override void writeDataClasses( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { for (final Class classDefinition in root.classes) { _writeObjcSourceDataClassExtension( generatorOptions, indent, classDefinition); } indent.newln(); super.writeDataClasses( generatorOptions, root, indent, dartPackageName: dartPackageName, ); } @override void writeDataClass( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { final Set<String> customClassNames = root.classes.map((Class x) => x.name).toSet(); final Set<String> customEnumNames = root.enums.map((Enum x) => x.name).toSet(); final String className = _className(generatorOptions.prefix, classDefinition.name); indent.writeln('@implementation $className'); _writeObjcSourceClassInitializer(generatorOptions, root, indent, classDefinition, customClassNames, customEnumNames, className); writeClassDecode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); writeClassEncode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); indent.writeln('@end'); indent.newln(); } @override void writeClassEncode( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { indent.write('- (NSArray *)toList '); indent.addScoped('{', '}', () { indent.write('return'); indent.addScoped(' @[', '];', () { for (final NamedType field in classDefinition.fields) { indent.writeln('${_arrayValue(field)},'); } }); }); } @override void writeClassDecode( ObjcOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { final String className = _className(generatorOptions.prefix, classDefinition.name); indent.write('+ ($className *)fromList:(NSArray *)list '); indent.addScoped('{', '}', () { const String resultName = 'pigeonResult'; indent.writeln('$className *$resultName = [[$className alloc] init];'); enumerate(getFieldsInSerializationOrder(classDefinition), (int index, final NamedType field) { final bool isEnumType = field.type.isEnum; final String valueGetter = _listGetter('list', field, index, generatorOptions.prefix); final String? primitiveExtractionMethod = _nsnumberExtractionMethod(field.type); final String ivarValueExpression; if (primitiveExtractionMethod != null) { ivarValueExpression = '[$valueGetter $primitiveExtractionMethod]'; } else if (isEnumType) { indent.writeln('NSNumber *${field.name}AsNumber = $valueGetter;'); indent.writeln( '${_enumName(field.type.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)}${field.name} = ${field.name}AsNumber == nil ? nil : [[${_enumName(field.type.baseName, prefix: generatorOptions.prefix, box: true)} alloc] initWithValue:[${field.name}AsNumber integerValue]];'); ivarValueExpression = field.name; } else { ivarValueExpression = valueGetter; } indent.writeln('$resultName.${field.name} = $ivarValueExpression;'); }); indent.writeln('return $resultName;'); }); indent.write('+ (nullable $className *)nullableFromList:(NSArray *)list '); indent.addScoped('{', '}', () { indent.writeln('return (list) ? [$className fromList:list] : nil;'); }); } void _writeCodecAndGetter( ObjcOptions generatorOptions, Root root, Indent indent, Api api) { final String codecName = _getCodecName(generatorOptions.prefix, api.name); if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(indent, codecName, generatorOptions, api, root); indent.newln(); } _writeCodecGetter(indent, codecName, generatorOptions, api, root); indent.newln(); } @override void writeFlutterApi( ObjcOptions generatorOptions, Root root, Indent indent, AstFlutterApi api, { required String dartPackageName, }) { final String apiName = _className(generatorOptions.prefix, api.name); _writeCodecAndGetter(generatorOptions, root, indent, api); _writeExtension(indent, apiName); indent.newln(); indent.writeln('@implementation $apiName'); indent.newln(); _writeInitializer(indent); for (final Method func in api.methods) { _writeMethod( generatorOptions, root, indent, api, func, dartPackageName: dartPackageName, ); } indent.writeln('@end'); indent.newln(); } @override void writeHostApi( ObjcOptions generatorOptions, Root root, Indent indent, AstHostApi api, { required String dartPackageName, }) { final String apiName = _className(generatorOptions.prefix, api.name); _writeCodecAndGetter(generatorOptions, root, indent, api); const String channelName = 'channel'; indent.write( 'void SetUp$apiName(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *api) '); indent.addScoped('{', '}', () { for (final Method func in api.methods) { addDocumentationComments( indent, func.documentationComments, _docCommentSpec); indent.writeScoped('{', '}', () { String? taskQueue; if (func.taskQueueType != TaskQueueType.serial) { taskQueue = 'taskQueue'; indent.writeln( 'NSObject<FlutterTaskQueue> *$taskQueue = [binaryMessenger makeBackgroundTaskQueue];'); } _writeChannelAllocation( generatorOptions, indent, api, func, channelName, taskQueue, dartPackageName: dartPackageName, ); indent.write('if (api) '); indent.addScoped('{', '}', () { _writeChannelApiBinding( generatorOptions, root, indent, apiName, func, channelName); }, addTrailingNewline: false); indent.add(' else '); indent.addScoped('{', '}', () { indent.writeln('[$channelName setMessageHandler:nil];'); }); }); } }); } @override void writeGeneralUtilities( ObjcOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { final bool hasHostApi = root.apis .whereType<AstHostApi>() .any((Api api) => api.methods.isNotEmpty); final bool hasFlutterApi = root.apis .whereType<AstFlutterApi>() .any((Api api) => api.methods.isNotEmpty); if (hasHostApi) { _writeWrapError(indent); indent.newln(); } if (hasFlutterApi) { _writeCreateConnectionError(indent); indent.newln(); } if (hasHostApi || hasFlutterApi) { _writeGetNullableObjectAtIndex(indent); } } void _writeWrapError(Indent indent) { indent.format(''' static NSArray *wrapResult(id result, FlutterError *error) { \tif (error) { \t\treturn @[ \t\t\terror.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] \t\t]; \t} \treturn @[ result ?: [NSNull null] ]; }'''); } void _writeGetNullableObjectAtIndex(Indent indent) { indent.format(''' static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { \tid result = array[key]; \treturn (result == [NSNull null]) ? nil : result; }'''); } void _writeCreateConnectionError(Indent indent) { indent.format(''' static FlutterError *createConnectionError(NSString *channelName) { \treturn [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: '", channelName, @"'."] details:@""]; }'''); } void _writeChannelApiBinding(ObjcOptions generatorOptions, Root root, Indent indent, String apiName, Method func, String channel) { void unpackArgs(String variable) { indent.writeln('NSArray *args = $variable;'); int count = 0; for (final NamedType arg in func.parameters) { final String argName = _getSafeArgName(count, arg); final String valueGetter = 'GetNullableObjectAtIndex(args, $count)'; final String? primitiveExtractionMethod = _nsnumberExtractionMethod(arg.type); final _ObjcType objcArgType = _objcTypeForDartType( generatorOptions.prefix, arg.type, ); if (primitiveExtractionMethod != null) { indent.writeln( '${objcArgType.beforeString}$argName = [$valueGetter $primitiveExtractionMethod];'); } else if (arg.type.isEnum) { indent.writeln('NSNumber *${argName}AsNumber = $valueGetter;'); indent.writeln( '${_enumName(arg.type.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)}$argName = ${argName}AsNumber == nil ? nil : [[${_enumName(arg.type.baseName, prefix: generatorOptions.prefix, box: true)} alloc] initWithValue:[${argName}AsNumber integerValue]];'); } else { indent.writeln('${objcArgType.beforeString}$argName = $valueGetter;'); } count++; } } void writeAsyncBindings(Iterable<String> selectorComponents, String callSignature, _ObjcType returnType) { if (func.returnType.isVoid) { const String callback = 'callback(wrapResult(nil, error));'; if (func.parameters.isEmpty) { indent.writeScoped( '[api ${selectorComponents.first}:^(FlutterError *_Nullable error) {', '}];', () { indent.writeln(callback); }); } else { indent.writeScoped( '[api $callSignature ${selectorComponents.last}:^(FlutterError *_Nullable error) {', '}];', () { indent.writeln(callback); }); } } else { const String callback = 'callback(wrapResult(output, error));'; String returnTypeString = '${returnType.beforeString}_Nullable output'; const String numberOutput = 'NSNumber *output ='; const String enumConversionExpression = 'enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value];'; if (func.returnType.isEnum) { returnTypeString = '${_enumName(func.returnType.baseName, suffix: ' *_Nullable', prefix: generatorOptions.prefix, box: true)} enumValue'; } if (func.parameters.isEmpty) { indent.writeScoped( '[api ${selectorComponents.first}:^($returnTypeString, FlutterError *_Nullable error) {', '}];', () { if (func.returnType.isEnum) { indent.writeln('$numberOutput $enumConversionExpression'); } indent.writeln(callback); }); } else { indent.writeScoped( '[api $callSignature ${selectorComponents.last}:^($returnTypeString, FlutterError *_Nullable error) {', '}];', () { if (func.returnType.isEnum) { indent.writeln('$numberOutput $enumConversionExpression'); } indent.writeln(callback); }); } } } void writeSyncBindings(String call, _ObjcType returnType) { indent.writeln('FlutterError *error;'); if (func.returnType.isVoid) { indent.writeln('$call;'); indent.writeln('callback(wrapResult(nil, error));'); } else { if (func.returnType.isEnum) { indent.writeln( '${_enumName(func.returnType.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)} enumBox = $call;'); indent.writeln( 'NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value];'); } else { indent.writeln('${returnType.beforeString}output = $call;'); } indent.writeln('callback(wrapResult(output, error));'); } } // TODO(gaaclarke): Incorporate this into _getSelectorComponents. final String lastSelectorComponent = func.isAsynchronous ? 'completion' : 'error'; final String selector = _getSelector(func, lastSelectorComponent); indent.writeln( 'NSCAssert([api respondsToSelector:@selector($selector)], @"$apiName api (%@) doesn\'t respond to @selector($selector)", api);'); indent.write( '[$channel setMessageHandler:^(id _Nullable message, FlutterReply callback) '); indent.addScoped('{', '}];', () { final _ObjcType returnType = _objcTypeForDartType( generatorOptions.prefix, func.returnType, // Nullability is required since the return must be nil if NSError is set. forceNullability: true, ); final Iterable<String> selectorComponents = _getSelectorComponents(func, lastSelectorComponent); final Iterable<String> argNames = indexMap(func.parameters, _getSafeArgName); final String callSignature = map2(selectorComponents.take(argNames.length), argNames, (String selectorComponent, String argName) { return '$selectorComponent:$argName'; }).join(' '); if (func.parameters.isNotEmpty) { unpackArgs('message'); } if (func.isAsynchronous) { writeAsyncBindings(selectorComponents, callSignature, returnType); } else { final String syncCall = func.parameters.isEmpty ? '[api ${selectorComponents.first}:&error]' : '[api $callSignature error:&error]'; writeSyncBindings(syncCall, returnType); } }); } void _writeChannelAllocation( ObjcOptions generatorOptions, Indent indent, Api api, Method func, String varName, String? taskQueue, { required String dartPackageName, }) { indent.writeln('FlutterBasicMessageChannel *$varName ='); indent.nest(1, () { indent.writeln('[[FlutterBasicMessageChannel alloc]'); indent.nest(1, () { indent.writeln( 'initWithName:@"${makeChannelName(api, func, dartPackageName)}"'); indent.writeln('binaryMessenger:binaryMessenger'); indent.write('codec:'); indent .add('${_getCodecGetterName(generatorOptions.prefix, api.name)}()'); if (taskQueue != null) { indent.newln(); indent.addln('taskQueue:$taskQueue];'); } else { indent.addln('];'); } }); }); } void _writeObjcSourceDataClassExtension( ObjcOptions languageOptions, Indent indent, Class classDefinition) { final String className = _className(languageOptions.prefix, classDefinition.name); indent.newln(); indent.writeln('@interface $className ()'); indent.writeln('+ ($className *)fromList:(NSArray *)list;'); indent .writeln('+ (nullable $className *)nullableFromList:(NSArray *)list;'); indent.writeln('- (NSArray *)toList;'); indent.writeln('@end'); } void _writeObjcSourceClassInitializer( ObjcOptions languageOptions, Root root, Indent indent, Class classDefinition, Set<String> customClassNames, Set<String> customEnumNames, String className, ) { _writeObjcSourceClassInitializerDeclaration( indent, languageOptions, root, classDefinition, root.classes, root.enums, languageOptions.prefix, ); indent.writeScoped(' {', '}', () { const String result = 'pigeonResult'; indent.writeln('$className* $result = [[$className alloc] init];'); for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { indent.writeln('$result.${field.name} = ${field.name};'); } indent.writeln('return $result;'); }); } /// Writes the codec that will be used for encoding messages for the [api]. /// /// Example: /// @interface FooHostApiCodecReader : FlutterStandardReader /// ... /// @interface FooHostApiCodecWriter : FlutterStandardWriter /// ... /// @interface FooHostApiCodecReaderWriter : FlutterStandardReaderWriter /// ... /// NSObject<FlutterMessageCodec> *FooHostApiCodecGetCodec(void) {...} void _writeCodec( Indent indent, String name, ObjcOptions options, Api api, Root root) { assert(getCodecClasses(api, root).isNotEmpty); final Iterable<EnumeratedClass> codecClasses = getCodecClasses(api, root); final String readerWriterName = '${name}ReaderWriter'; final String readerName = '${name}Reader'; final String writerName = '${name}Writer'; indent.writeln('@interface $readerName : FlutterStandardReader'); indent.writeln('@end'); indent.writeln('@implementation $readerName'); indent.write('- (nullable id)readValueOfType:(UInt8)type '); indent.addScoped('{', '}', () { indent.write('switch (type) '); indent.addScoped('{', '}', () { for (final EnumeratedClass customClass in codecClasses) { indent.writeln('case ${customClass.enumeration}: '); indent.nest(1, () { indent.writeln( 'return [${_className(options.prefix, customClass.name)} fromList:[self readValue]];'); }); } indent.writeln('default:'); indent.nest(1, () { indent.writeln('return [super readValueOfType:type];'); }); }); }); indent.writeln('@end'); indent.newln(); indent.writeln('@interface $writerName : FlutterStandardWriter'); indent.writeln('@end'); indent.writeln('@implementation $writerName'); indent.write('- (void)writeValue:(id)value '); indent.addScoped('{', '}', () { bool firstClass = true; for (final EnumeratedClass customClass in codecClasses) { if (firstClass) { indent.write(''); firstClass = false; } indent.add( 'if ([value isKindOfClass:[${_className(options.prefix, customClass.name)} class]]) '); indent.addScoped('{', '} else ', () { indent.writeln('[self writeByte:${customClass.enumeration}];'); indent.writeln('[self writeValue:[value toList]];'); }, addTrailingNewline: false); } indent.addScoped('{', '}', () { indent.writeln('[super writeValue:value];'); }); }); indent.writeln('@end'); indent.newln(); indent.format(''' @interface $readerWriterName : FlutterStandardReaderWriter @end @implementation $readerWriterName - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { \treturn [[$writerName alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { \treturn [[$readerName alloc] initWithData:data]; } @end'''); } void _writeCodecGetter( Indent indent, String name, ObjcOptions options, Api api, Root root) { final String readerWriterName = '${name}ReaderWriter'; indent.write( 'NSObject<FlutterMessageCodec> *${_getCodecGetterName(options.prefix, api.name)}(void) '); indent.addScoped('{', '}', () { indent .writeln('static FlutterStandardMessageCodec *sSharedObject = nil;'); if (getCodecClasses(api, root).isNotEmpty) { indent.writeln('static dispatch_once_t sPred = 0;'); indent.write('dispatch_once(&sPred, ^'); indent.addScoped('{', '});', () { indent.writeln( '$readerWriterName *readerWriter = [[$readerWriterName alloc] init];'); indent.writeln( 'sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];'); }); } else { indent.writeln( 'sSharedObject = [FlutterStandardMessageCodec sharedInstance];'); } indent.writeln('return sSharedObject;'); }); } void _writeMethod( ObjcOptions languageOptions, Root root, Indent indent, Api api, Method func, { required String dartPackageName, }) { final _ObjcType returnType = _objcTypeForDartType( languageOptions.prefix, func.returnType, // Nullability is required since the return must be nil if NSError is set. forceNullability: true, ); final String callbackType = _callbackForType(func.returnType, returnType, languageOptions); String argNameFunc(int count, NamedType arg) => _getSafeArgName(count, arg); String sendArgument; if (func.parameters.isEmpty) { sendArgument = 'nil'; } else { int count = 0; String makeVarOrNSNullExpression(NamedType arg) { final String argName = argNameFunc(count, arg); String varExpression = _collectionSafeExpression(argName, arg.type); if (arg.type.isEnum) { if (arg.type.isNullable) { varExpression = '${argNameFunc(count, arg)} == nil ? [NSNull null] : [NSNumber numberWithInteger:$argName.value]'; } else { varExpression = '[NSNumber numberWithInteger:$argName]'; } } count++; return varExpression; } sendArgument = '@[${func.parameters.map(makeVarOrNSNullExpression).join(', ')}]'; } indent.write(_makeObjcSignature( func: func, options: languageOptions, returnType: 'void', lastArgName: 'completion', lastArgType: callbackType, argNameFunc: argNameFunc, )); indent.addScoped(' {', '}', () { indent.writeln( 'NSString *channelName = @"${makeChannelName(api, func, dartPackageName)}";'); indent.writeln('FlutterBasicMessageChannel *channel ='); indent.nest(1, () { indent.writeln('[FlutterBasicMessageChannel'); indent.nest(1, () { indent.writeln('messageChannelWithName:channelName'); indent.writeln('binaryMessenger:self.binaryMessenger'); indent.write( 'codec:${_getCodecGetterName(languageOptions.prefix, api.name)}()'); indent.addln('];'); }); }); final String valueOnErrorResponse = func.returnType.isVoid ? '' : 'nil, '; indent.write( '[channel sendMessage:$sendArgument reply:^(NSArray<id> *reply) '); indent.addScoped('{', '}];', () { indent.writeScoped('if (reply != nil) {', '} ', () { indent.writeScoped('if (reply.count > 1) {', '} ', () { indent.writeln( 'completion($valueOnErrorResponse[FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]);'); }, addTrailingNewline: false); indent.addScoped('else {', '}', () { const String nullCheck = 'reply[0] == [NSNull null] ? nil : reply[0]'; if (func.returnType.isVoid) { indent.writeln('completion(nil);'); } else { if (func.returnType.isEnum) { final String enumName = _enumName(func.returnType.baseName, prefix: languageOptions.prefix, box: true); indent.writeln('NSNumber *outputAsNumber = $nullCheck;'); indent.writeln( '$enumName *output = outputAsNumber == nil ? nil : [[$enumName alloc] initWithValue:[outputAsNumber integerValue]];'); } else { indent .writeln('${returnType.beforeString}output = $nullCheck;'); } indent.writeln('completion(output, nil);'); } }); }, addTrailingNewline: false); indent.addScoped('else {', '} ', () { indent.writeln( 'completion(${valueOnErrorResponse}createConnectionError(channelName));'); }); }); }); } } /// Writes the method declaration for the initializer. /// /// Example '+ (instancetype)makeWithFoo:(NSString *)foo' void _writeObjcSourceClassInitializerDeclaration( Indent indent, ObjcOptions generatorOptions, Root root, Class classDefinition, List<Class> classes, List<Enum> enums, String? prefix) { indent.write('+ (instancetype)makeWith'); bool isFirst = true; indent.nest(2, () { for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { final String label = isFirst ? _capitalize(field.name) : field.name; final void Function(String) printer = isFirst ? indent.add : (String x) { indent.newln(); indent.write(x); }; isFirst = false; final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), customResolver: field.type.isEnum ? (String x) => field.type.isNullable ? _enumName(x, suffix: ' *', prefix: prefix, box: true) : _enumName(x, prefix: prefix) : (String x) => '${_className(prefix, x)} *'); final String nullable = field.type.isNullable ? 'nullable ' : ''; printer('$label:($nullable${hostDatatype.datatype})${field.name}'); } }); } String _enumName(String name, {required String? prefix, String suffix = '', bool box = false}) => '${prefix ?? ''}$name${box ? 'Box' : ''}$suffix'; /// Calculates the ObjC class name, possibly prefixed. String _className(String? prefix, String className) { if (prefix != null) { return '$prefix$className'; } else { return className; } } /// Calculates callback block signature for async methods. String _callbackForType( TypeDeclaration type, _ObjcType objcType, ObjcOptions options) { if (type.isVoid) { return 'void (^)(FlutterError *_Nullable)'; } else if (type.isEnum) { return 'void (^)(${_enumName(type.baseName, suffix: ' *_Nullable', prefix: options.prefix, box: true)}, FlutterError *_Nullable)'; } else { return 'void (^)(${objcType.beforeString}_Nullable, FlutterError *_Nullable)'; } } /// Represents an Objective-C type, including pointer (id, NSString*, etc.) and /// primitive (BOOL, NSInteger, etc.) types. class _ObjcType { const _ObjcType({required this.baseName, bool isPointer = true}) : hasAsterisk = isPointer && baseName != 'id'; final String baseName; final bool hasAsterisk; @override String toString() => hasAsterisk ? '$baseName *' : baseName; /// Returns a version of the string form that can be used directly before /// another string (e.g., a variable name) and handle spacing correctly for /// a right-aligned pointer format. String get beforeString => hasAsterisk ? toString() : '$this '; } /// Maps between Dart types to ObjC pointer types (ex 'String' => 'NSString *'). const Map<String, _ObjcType> _objcTypeForNullableDartTypeMap = <String, _ObjcType>{ 'bool': _ObjcType(baseName: 'NSNumber'), 'int': _ObjcType(baseName: 'NSNumber'), 'String': _ObjcType(baseName: 'NSString'), 'double': _ObjcType(baseName: 'NSNumber'), 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'List': _ObjcType(baseName: 'NSArray'), 'Map': _ObjcType(baseName: 'NSDictionary'), 'Object': _ObjcType(baseName: 'id'), }; /// Maps between Dart types to ObjC pointer types (ex 'String' => 'NSString *'). const Map<String, _ObjcType> _objcTypeForNonNullableDartTypeMap = <String, _ObjcType>{ 'bool': _ObjcType(baseName: 'BOOL', isPointer: false), 'int': _ObjcType(baseName: 'NSInteger', isPointer: false), 'String': _ObjcType(baseName: 'NSString'), 'double': _ObjcType(baseName: 'double', isPointer: false), 'Uint8List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Int32List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Int64List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'Float64List': _ObjcType(baseName: 'FlutterStandardTypedData'), 'List': _ObjcType(baseName: 'NSArray'), 'Map': _ObjcType(baseName: 'NSDictionary'), 'Object': _ObjcType(baseName: 'id'), }; bool _usesPrimitive(TypeDeclaration type) { // Only non-nullable types are unboxed. if (!type.isNullable) { if (type.isEnum) { return true; } switch (type.baseName) { case 'bool': case 'int': case 'double': return true; } } return false; } String _collectionSafeExpression( String expression, TypeDeclaration type, ) { return _usesPrimitive(type) ? '@($expression)' : '$expression ?: [NSNull null]'; } /// Returns the method to convert [type] from a boxed NSNumber to its /// corresponding primitive value, if any. String? _nsnumberExtractionMethod( TypeDeclaration type, ) { // Only non-nullable types are unboxed. if (!type.isNullable) { if (type.isEnum) { return 'integerValue'; } switch (type.baseName) { case 'bool': return 'boolValue'; case 'int': return 'integerValue'; case 'double': return 'doubleValue'; } } return null; } /// Converts list of [TypeDeclaration] to a code string representing the type /// arguments for use in generics. /// Example: ('FOO', ['Foo', 'Bar']) -> 'FOOFoo *, FOOBar *'). String _flattenTypeArguments(String? classPrefix, List<TypeDeclaration> args) { final String result = args .map<String>((TypeDeclaration e) => _objcTypeForDartType(classPrefix, e).toString()) .join(', '); return result; } _ObjcType? _objcTypeForPrimitiveDartType(TypeDeclaration type, {bool forceNullability = false}) { return forceNullability || type.isNullable ? _objcTypeForNullableDartTypeMap[type.baseName] : _objcTypeForNonNullableDartTypeMap[type.baseName]; } String? _objcTypeStringForPrimitiveDartType( String? classPrefix, TypeDeclaration type, {required bool beforeString, bool forceNullability = false}) { final _ObjcType? objcType; if (forceNullability || type.isNullable) { objcType = _objcTypeForNullableDartTypeMap.containsKey(type.baseName) ? _objcTypeForDartType(classPrefix, type) : null; } else { objcType = _objcTypeForNonNullableDartTypeMap.containsKey(type.baseName) ? _objcTypeForDartType(classPrefix, type) : null; } return beforeString ? objcType?.beforeString : objcType?.toString(); } /// Returns the Objective-C type for a Dart [field], prepending the /// [classPrefix] for generated classes. _ObjcType _objcTypeForDartType(String? classPrefix, TypeDeclaration field, {bool forceNullability = false}) { final _ObjcType? primitiveType = _objcTypeForPrimitiveDartType(field, forceNullability: forceNullability); return primitiveType == null ? _ObjcType( baseName: _className(classPrefix, field.baseName), // Non-nullable enums are non-pointer types. isPointer: !field.isEnum || (field.isNullable || forceNullability)) : field.typeArguments.isEmpty ? primitiveType : _ObjcType( baseName: '${primitiveType.baseName}<${_flattenTypeArguments(classPrefix, field.typeArguments)}>'); } /// Maps a type to a properties memory semantics (ie strong, copy). String _propertyTypeForDartType(TypeDeclaration type, {required bool isNullable, required bool isEnum}) { if (isEnum) { // Only the nullable versions are objects. return isNullable ? 'strong' : 'assign'; } switch (type.baseName) { case 'List': case 'Map': case 'String': // Standard Objective-C practice is to copy strings and collections to // avoid unexpected mutation if set to mutable versions. return 'copy'; case 'double': case 'bool': case 'int': // Only the nullable versions are objects. return isNullable ? 'strong' : 'assign'; } // Anything else is a standard object, and should therefore be strong. return 'strong'; } /// Generates the name of the codec that will be generated. String _getCodecName(String? prefix, String className) => '${_className(prefix, className)}Codec'; /// Generates the name of the function for accessing the codec instance used by /// the api class named [className]. String _getCodecGetterName(String? prefix, String className) => '${_className(prefix, className)}GetCodec'; String _capitalize(String str) => (str.isEmpty) ? '' : str[0].toUpperCase() + str.substring(1); /// Returns the components of the objc selector that will be generated from /// [func], ie the strings between the semicolons. [lastSelectorComponent] is /// the last component of the selector aka the label of the last parameter which /// isn't included in [func]. /// Example: /// f('void add(int x, int y)', 'count') -> ['addX', 'y', 'count'] Iterable<String> _getSelectorComponents( Method func, String lastSelectorComponent) sync* { if (func.objcSelector.isEmpty) { final Iterator<NamedType> it = func.parameters.iterator; final bool hasArguments = it.moveNext(); final String namePostfix = (lastSelectorComponent.isNotEmpty && func.parameters.isEmpty) ? 'With${_capitalize(lastSelectorComponent)}' : ''; yield '${func.name}${hasArguments ? _capitalize(func.parameters[0].name) : namePostfix}'; while (it.moveNext()) { yield it.current.name; } } else { assert(':'.allMatches(func.objcSelector).length == func.parameters.length); final Iterable<String> customComponents = func.objcSelector .split(':') .where((String element) => element.isNotEmpty); yield* customComponents; } if (lastSelectorComponent.isNotEmpty && func.parameters.isNotEmpty) { yield lastSelectorComponent; } } /// Generates the objc source code method signature for [func]. [returnType] is /// the return value of method, this may not match the return value in [func] /// since [func] may be asynchronous. The function requires you specify a /// [lastArgType] and [lastArgName] for arguments that aren't represented in /// [func]. This is typically used for passing in 'error' or 'completion' /// arguments that don't exist in the pigeon file but are required in the objc /// output. [argNameFunc] is the function used to generate the argument name /// [func.parameters]. String _makeObjcSignature({ required Method func, required ObjcOptions options, required String returnType, required String lastArgType, required String lastArgName, String Function(int, NamedType)? argNameFunc, }) { argNameFunc = argNameFunc ?? (int _, NamedType e) => e.type.isNullable && e.type.isEnum ? '${e.name}Boxed' : e.name; final Iterable<String> argNames = followedByOne(indexMap(func.parameters, argNameFunc), lastArgName); final Iterable<String> selectorComponents = _getSelectorComponents(func, lastArgName); final Iterable<String> argTypes = followedByOne( func.parameters.map((NamedType arg) { if (arg.type.isEnum) { return '${arg.type.isNullable ? 'nullable ' : ''}${_enumName(arg.type.baseName, suffix: arg.type.isNullable ? ' *' : '', prefix: options.prefix, box: arg.type.isNullable)}'; } else { final String nullable = arg.type.isNullable ? 'nullable ' : ''; final _ObjcType argType = _objcTypeForDartType(options.prefix, arg.type); return '$nullable$argType'; } }), lastArgType, ); final String argSignature = map3( selectorComponents, argTypes, argNames, (String component, String argType, String argName) => '$component:($argType)$argName', ).join(' '); return '- ($returnType)$argSignature'; } /// Generates the ".h" file for the AST represented by [root] to [sink] with the /// provided [options]. void generateObjcHeader(ObjcOptions options, Root root, Indent indent) {} String _listGetter(String list, NamedType field, int index, String? prefix) { if (field.type.isClass) { String className = field.type.baseName; if (prefix != null) { className = '$prefix$className'; } return '[$className nullableFromList:(GetNullableObjectAtIndex($list, $index))]'; } else { return 'GetNullableObjectAtIndex($list, $index)'; } } String _arrayValue(NamedType field) { if (field.type.isClass) { return '(self.${field.name} ? [self.${field.name} toList] : [NSNull null])'; } else if (field.type.isEnum) { if (field.type.isNullable) { return '(self.${field.name} == nil ? [NSNull null] : [NSNumber numberWithInteger:self.${field.name}.value])'; } return '@(self.${field.name})'; } else { return _collectionSafeExpression( 'self.${field.name}', field.type, ); } } String _getSelector(Method func, String lastSelectorComponent) => '${_getSelectorComponents(func, lastSelectorComponent).join(':')}:'; /// Returns an argument name that can be used in a context where it is possible to collide. String _getSafeArgName(int count, NamedType arg) => arg.name.isEmpty ? 'arg$count' : 'arg_${arg.name}'; void _writeExtension(Indent indent, String apiName) { indent.writeln('@interface $apiName ()'); indent.writeln( '@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;'); indent.writeln('@end'); } void _writeInitializer(Indent indent) { indent.write( '- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger '); indent.addScoped('{', '}', () { indent.writeln('self = [super init];'); indent.write('if (self) '); indent.addScoped('{', '}', () { indent.writeln('_binaryMessenger = binaryMessenger;'); }); indent.writeln('return self;'); }); } /// Looks through the AST for features that aren't supported by the ObjC /// generator. List<Error> validateObjc(ObjcOptions options, Root root) { final List<Error> errors = <Error>[]; for (final Api api in root.apis) { for (final Method method in api.methods) { for (final NamedType arg in method.parameters) { if (arg.type.isEnum && arg.type.isNullable) { // TODO(gaaclarke): Add line number. errors.add(Error( message: "Nullable enum types aren't support in ObjC arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).")); } } } } return errors; }
packages/packages/pigeon/lib/objc_generator.dart/0
{ "file_path": "packages/packages/pigeon/lib/objc_generator.dart", "repo_id": "packages", "token_count": 21387 }
1,024
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @HostApi() abstract class PrimitiveHostApi { int anInt(int value); bool aBool(bool value); String aString(String value); double aDouble(double value); // ignore: always_specify_types, strict_raw_type Map aMap(Map value); // ignore: always_specify_types, strict_raw_type List aList(List value); Int32List anInt32List(Int32List value); List<bool?> aBoolList(List<bool?> value); Map<String?, int?> aStringIntMap(Map<String?, int?> value); } @FlutterApi() abstract class PrimitiveFlutterApi { int anInt(int value); bool aBool(bool value); String aString(String value); double aDouble(double value); // ignore: always_specify_types, strict_raw_type Map aMap(Map value); // ignore: always_specify_types, strict_raw_type List aList(List value); Int32List anInt32List(Int32List value); List<bool?> aBoolList(List<bool?> value); Map<String?, int?> aStringIntMap(Map<String?, int?> value); }
packages/packages/pigeon/pigeons/primitive.dart/0
{ "file_path": "packages/packages/pigeon/pigeons/primitive.dart", "repo_id": "packages", "token_count": 390 }
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. package com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.example.alternate_language_test_plugin.CoreTests.FlutterSmallApi; import com.example.alternate_language_test_plugin.CoreTests.TestMessage; import io.flutter.plugin.common.BinaryMessenger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; public class ListTest { @Test public void listInList() { TestMessage top = new TestMessage(); TestMessage inside = new TestMessage(); inside.setTestList(Arrays.asList(1, 2, 3)); top.setTestList(Arrays.asList(inside)); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); doAnswer( invocation -> { ByteBuffer message = invocation.getArgument(1); BinaryMessenger.BinaryReply reply = invocation.getArgument(2); message.position(0); @SuppressWarnings("unchecked") ArrayList<Object> args = (ArrayList<Object>) FlutterSmallApi.getCodec().decodeMessage(message); ByteBuffer replyData = FlutterSmallApi.getCodec().encodeMessage(args); replyData.position(0); reply.reply(replyData); return null; }) .when(binaryMessenger) .send(anyString(), any(), any()); FlutterSmallApi api = new FlutterSmallApi(binaryMessenger); boolean[] didCall = {false}; api.echoWrappedList( top, new CoreTests.Result<TestMessage>() { public void success(TestMessage result) { didCall[0] = true; assertEquals(result.getTestList().size(), 1); assertTrue(result.getTestList().get(0) instanceof TestMessage); TestMessage readInside = (TestMessage) result.getTestList().get(0); assertEquals(readInside.getTestList().size(), 3); } public void error(Throwable error) { assertEquals(error, null); } }); assertTrue(didCall[0]); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/ListTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/ListTest.java", "repo_id": "packages", "token_count": 928 }
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. @import Flutter; @import XCTest; @import alternate_language_test_plugin; #import "EchoMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface NullFieldsSearchRequest () + (NullFieldsSearchRequest *)fromList:(NSArray *)list; - (NSArray *)toList; @end /////////////////////////////////////////////////////////////////////////////////////////// @interface NullFieldsSearchReply () + (NullFieldsSearchReply *)fromList:(NSArray *)list; - (NSArray *)toList; @end /////////////////////////////////////////////////////////////////////////////////////////// @interface NullFieldsTest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation NullFieldsTest - (void)testMakeWithValues { NullFieldsSearchRequest *request = [NullFieldsSearchRequest makeWithQuery:@"hello" identifier:1]; NullFieldsSearchReplyTypeBox *typeWrapper = [[NullFieldsSearchReplyTypeBox alloc] initWithValue:NullFieldsSearchReplyTypeSuccess]; NullFieldsSearchReply *reply = [NullFieldsSearchReply makeWithResult:@"result" error:@"error" indices:@[ @1, @2, @3 ] request:request type:typeWrapper]; NSArray *indices = @[ @1, @2, @3 ]; XCTAssertEqualObjects(@"result", reply.result); XCTAssertEqualObjects(@"error", reply.error); XCTAssertEqualObjects(indices, reply.indices); XCTAssertEqualObjects(@"hello", reply.request.query); XCTAssertEqual(typeWrapper.value, reply.type.value); } - (void)testMakeRequestWithNulls { NullFieldsSearchRequest *request = [NullFieldsSearchRequest makeWithQuery:nil identifier:1]; XCTAssertNil(request.query); } - (void)testMakeReplyWithNulls { NullFieldsSearchReply *reply = [NullFieldsSearchReply makeWithResult:nil error:nil indices:nil request:nil type:nil]; XCTAssertNil(reply.result); XCTAssertNil(reply.error); XCTAssertNil(reply.indices); XCTAssertNil(reply.request); XCTAssertNil(reply.type); } - (void)testRequestFromListWithValues { NSArray *list = @[ @"hello", @1, ]; NullFieldsSearchRequest *request = [NullFieldsSearchRequest fromList:list]; XCTAssertEqualObjects(@"hello", request.query); } - (void)testRequestFromListWithNulls { NSArray *list = @[ [NSNull null], @1, ]; NullFieldsSearchRequest *request = [NullFieldsSearchRequest fromList:list]; XCTAssertNil(request.query); } - (void)testReplyFromListWithValues { NSArray *list = @[ @"result", @"error", @[ @1, @2, @3 ], @[ @"hello", @1, ], @0, ]; NSArray *indices = @[ @1, @2, @3 ]; NullFieldsSearchReply *reply = [NullFieldsSearchReply fromList:list]; XCTAssertEqualObjects(@"result", reply.result); XCTAssertEqualObjects(@"error", reply.error); XCTAssertEqualObjects(indices, reply.indices); XCTAssertEqualObjects(@"hello", reply.request.query); XCTAssertEqual(NullFieldsSearchReplyTypeSuccess, reply.type.value); } - (void)testReplyFromListWithNulls { NSArray *list = @[ [NSNull null], [NSNull null], [NSNull null], [NSNull null], [NSNull null], ]; NullFieldsSearchReply *reply = [NullFieldsSearchReply fromList:list]; XCTAssertNil(reply.result); XCTAssertNil(reply.error); XCTAssertNil(reply.indices); XCTAssertNil(reply.request.query); XCTAssertNil(reply.type); } - (void)testRequestToListWithValuess { NullFieldsSearchRequest *request = [NullFieldsSearchRequest makeWithQuery:@"hello" identifier:1]; NSArray *list = [request toList]; XCTAssertEqual(@"hello", list[0]); } - (void)testRequestToListWithNulls { NullFieldsSearchRequest *request = [NullFieldsSearchRequest makeWithQuery:nil identifier:1]; NSArray *list = [request toList]; XCTAssertEqual([NSNull null], list[0]); } - (void)testReplyToListWithValuess { NullFieldsSearchReplyTypeBox *typeWrapper = [[NullFieldsSearchReplyTypeBox alloc] initWithValue:NullFieldsSearchReplyTypeSuccess]; NullFieldsSearchReply *reply = [NullFieldsSearchReply makeWithResult:@"result" error:@"error" indices:@[ @1, @2, @3 ] request:[NullFieldsSearchRequest makeWithQuery:@"hello" identifier:1] type:typeWrapper]; NSArray *list = [reply toList]; NSArray *indices = @[ @1, @2, @3 ]; XCTAssertEqualObjects(@"result", list[0]); XCTAssertEqualObjects(@"error", list[1]); XCTAssertEqualObjects(indices, list[2]); XCTAssertEqualObjects(@"hello", list[3][0]); NSNumber *typeNumber = list[4]; NullFieldsSearchReplyTypeBox *output = [[NullFieldsSearchReplyTypeBox alloc] initWithValue:[typeNumber integerValue]]; XCTAssertEqual(typeWrapper.value, output.value); } - (void)testReplyToListWithNulls { NullFieldsSearchReply *reply = [NullFieldsSearchReply makeWithResult:nil error:nil indices:nil request:nil type:nil]; NSArray *list = [reply toList]; XCTAssertEqual([NSNull null], list[0]); XCTAssertEqual([NSNull null], list[1]); XCTAssertEqual([NSNull null], list[2]); XCTAssertEqual([NSNull null], list[3]); XCTAssertEqual([NSNull null], list[4]); } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NullFieldsTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NullFieldsTest.m", "repo_id": "packages", "token_count": 2618 }
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. import Cocoa import FlutterMacOS import XCTest @testable import alternate_language_test_plugin class RunnerTests: XCTestCase { // Currently there are no macOS Objective-C unit tests, since the expectation // is that the iOS Objective-C unit tests provide sufficient native unit test // coverage. If macOS-specific issue come up, they can be tested here. }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/RunnerTests/RunnerTests.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/RunnerTests/RunnerTests.swift", "repo_id": "packages", "token_count": 137 }
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. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon #import "CoreTests.gen.h" #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSArray *wrapResult(id result, FlutterError *error) { if (error) { return @[ error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] ]; } return @[ result ?: [NSNull null] ]; } static FlutterError *createConnectionError(NSString *channelName) { return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: '", channelName, @"'."] details:@""]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @implementation AnEnumBox - (instancetype)initWithValue:(AnEnum)value { self = [super init]; if (self) { _value = value; } return self; } @end @interface AllTypes () + (AllTypes *)fromList:(NSArray *)list; + (nullable AllTypes *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface AllNullableTypes () + (AllNullableTypes *)fromList:(NSArray *)list; + (nullable AllNullableTypes *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface AllClassesWrapper () + (AllClassesWrapper *)fromList:(NSArray *)list; + (nullable AllClassesWrapper *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface TestMessage () + (TestMessage *)fromList:(NSArray *)list; + (nullable TestMessage *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @implementation AllTypes + (instancetype)makeWithABool:(BOOL)aBool anInt:(NSInteger)anInt anInt64:(NSInteger)anInt64 aDouble:(double)aDouble aByteArray:(FlutterStandardTypedData *)aByteArray a4ByteArray:(FlutterStandardTypedData *)a4ByteArray a8ByteArray:(FlutterStandardTypedData *)a8ByteArray aFloatArray:(FlutterStandardTypedData *)aFloatArray aList:(NSArray *)aList aMap:(NSDictionary *)aMap anEnum:(AnEnum)anEnum aString:(NSString *)aString anObject:(id)anObject { AllTypes *pigeonResult = [[AllTypes alloc] init]; pigeonResult.aBool = aBool; pigeonResult.anInt = anInt; pigeonResult.anInt64 = anInt64; pigeonResult.aDouble = aDouble; pigeonResult.aByteArray = aByteArray; pigeonResult.a4ByteArray = a4ByteArray; pigeonResult.a8ByteArray = a8ByteArray; pigeonResult.aFloatArray = aFloatArray; pigeonResult.aList = aList; pigeonResult.aMap = aMap; pigeonResult.anEnum = anEnum; pigeonResult.aString = aString; pigeonResult.anObject = anObject; return pigeonResult; } + (AllTypes *)fromList:(NSArray *)list { AllTypes *pigeonResult = [[AllTypes alloc] init]; pigeonResult.aBool = [GetNullableObjectAtIndex(list, 0) boolValue]; pigeonResult.anInt = [GetNullableObjectAtIndex(list, 1) integerValue]; pigeonResult.anInt64 = [GetNullableObjectAtIndex(list, 2) integerValue]; pigeonResult.aDouble = [GetNullableObjectAtIndex(list, 3) doubleValue]; pigeonResult.aByteArray = GetNullableObjectAtIndex(list, 4); pigeonResult.a4ByteArray = GetNullableObjectAtIndex(list, 5); pigeonResult.a8ByteArray = GetNullableObjectAtIndex(list, 6); pigeonResult.aFloatArray = GetNullableObjectAtIndex(list, 7); pigeonResult.aList = GetNullableObjectAtIndex(list, 8); pigeonResult.aMap = GetNullableObjectAtIndex(list, 9); pigeonResult.anEnum = [GetNullableObjectAtIndex(list, 10) integerValue]; pigeonResult.aString = GetNullableObjectAtIndex(list, 11); pigeonResult.anObject = GetNullableObjectAtIndex(list, 12); return pigeonResult; } + (nullable AllTypes *)nullableFromList:(NSArray *)list { return (list) ? [AllTypes fromList:list] : nil; } - (NSArray *)toList { return @[ @(self.aBool), @(self.anInt), @(self.anInt64), @(self.aDouble), self.aByteArray ?: [NSNull null], self.a4ByteArray ?: [NSNull null], self.a8ByteArray ?: [NSNull null], self.aFloatArray ?: [NSNull null], self.aList ?: [NSNull null], self.aMap ?: [NSNull null], @(self.anEnum), self.aString ?: [NSNull null], self.anObject ?: [NSNull null], ]; } @end @implementation AllNullableTypes + (instancetype)makeWithANullableBool:(nullable NSNumber *)aNullableBool aNullableInt:(nullable NSNumber *)aNullableInt aNullableInt64:(nullable NSNumber *)aNullableInt64 aNullableDouble:(nullable NSNumber *)aNullableDouble aNullableByteArray:(nullable FlutterStandardTypedData *)aNullableByteArray aNullable4ByteArray:(nullable FlutterStandardTypedData *)aNullable4ByteArray aNullable8ByteArray:(nullable FlutterStandardTypedData *)aNullable8ByteArray aNullableFloatArray:(nullable FlutterStandardTypedData *)aNullableFloatArray aNullableList:(nullable NSArray *)aNullableList aNullableMap:(nullable NSDictionary *)aNullableMap nullableNestedList:(nullable NSArray<NSArray<NSNumber *> *> *)nullableNestedList nullableMapWithAnnotations: (nullable NSDictionary<NSString *, NSString *> *)nullableMapWithAnnotations nullableMapWithObject:(nullable NSDictionary<NSString *, id> *)nullableMapWithObject aNullableEnum:(nullable AnEnumBox *)aNullableEnum aNullableString:(nullable NSString *)aNullableString aNullableObject:(nullable id)aNullableObject { AllNullableTypes *pigeonResult = [[AllNullableTypes alloc] init]; pigeonResult.aNullableBool = aNullableBool; pigeonResult.aNullableInt = aNullableInt; pigeonResult.aNullableInt64 = aNullableInt64; pigeonResult.aNullableDouble = aNullableDouble; pigeonResult.aNullableByteArray = aNullableByteArray; pigeonResult.aNullable4ByteArray = aNullable4ByteArray; pigeonResult.aNullable8ByteArray = aNullable8ByteArray; pigeonResult.aNullableFloatArray = aNullableFloatArray; pigeonResult.aNullableList = aNullableList; pigeonResult.aNullableMap = aNullableMap; pigeonResult.nullableNestedList = nullableNestedList; pigeonResult.nullableMapWithAnnotations = nullableMapWithAnnotations; pigeonResult.nullableMapWithObject = nullableMapWithObject; pigeonResult.aNullableEnum = aNullableEnum; pigeonResult.aNullableString = aNullableString; pigeonResult.aNullableObject = aNullableObject; return pigeonResult; } + (AllNullableTypes *)fromList:(NSArray *)list { AllNullableTypes *pigeonResult = [[AllNullableTypes alloc] init]; pigeonResult.aNullableBool = GetNullableObjectAtIndex(list, 0); pigeonResult.aNullableInt = GetNullableObjectAtIndex(list, 1); pigeonResult.aNullableInt64 = GetNullableObjectAtIndex(list, 2); pigeonResult.aNullableDouble = GetNullableObjectAtIndex(list, 3); pigeonResult.aNullableByteArray = GetNullableObjectAtIndex(list, 4); pigeonResult.aNullable4ByteArray = GetNullableObjectAtIndex(list, 5); pigeonResult.aNullable8ByteArray = GetNullableObjectAtIndex(list, 6); pigeonResult.aNullableFloatArray = GetNullableObjectAtIndex(list, 7); pigeonResult.aNullableList = GetNullableObjectAtIndex(list, 8); pigeonResult.aNullableMap = GetNullableObjectAtIndex(list, 9); pigeonResult.nullableNestedList = GetNullableObjectAtIndex(list, 10); pigeonResult.nullableMapWithAnnotations = GetNullableObjectAtIndex(list, 11); pigeonResult.nullableMapWithObject = GetNullableObjectAtIndex(list, 12); NSNumber *aNullableEnumAsNumber = GetNullableObjectAtIndex(list, 13); AnEnumBox *aNullableEnum = aNullableEnumAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[aNullableEnumAsNumber integerValue]]; pigeonResult.aNullableEnum = aNullableEnum; pigeonResult.aNullableString = GetNullableObjectAtIndex(list, 14); pigeonResult.aNullableObject = GetNullableObjectAtIndex(list, 15); return pigeonResult; } + (nullable AllNullableTypes *)nullableFromList:(NSArray *)list { return (list) ? [AllNullableTypes fromList:list] : nil; } - (NSArray *)toList { return @[ self.aNullableBool ?: [NSNull null], self.aNullableInt ?: [NSNull null], self.aNullableInt64 ?: [NSNull null], self.aNullableDouble ?: [NSNull null], self.aNullableByteArray ?: [NSNull null], self.aNullable4ByteArray ?: [NSNull null], self.aNullable8ByteArray ?: [NSNull null], self.aNullableFloatArray ?: [NSNull null], self.aNullableList ?: [NSNull null], self.aNullableMap ?: [NSNull null], self.nullableNestedList ?: [NSNull null], self.nullableMapWithAnnotations ?: [NSNull null], self.nullableMapWithObject ?: [NSNull null], (self.aNullableEnum == nil ? [NSNull null] : [NSNumber numberWithInteger:self.aNullableEnum.value]), self.aNullableString ?: [NSNull null], self.aNullableObject ?: [NSNull null], ]; } @end @implementation AllClassesWrapper + (instancetype)makeWithAllNullableTypes:(AllNullableTypes *)allNullableTypes allTypes:(nullable AllTypes *)allTypes { AllClassesWrapper *pigeonResult = [[AllClassesWrapper alloc] init]; pigeonResult.allNullableTypes = allNullableTypes; pigeonResult.allTypes = allTypes; return pigeonResult; } + (AllClassesWrapper *)fromList:(NSArray *)list { AllClassesWrapper *pigeonResult = [[AllClassesWrapper alloc] init]; pigeonResult.allNullableTypes = [AllNullableTypes nullableFromList:(GetNullableObjectAtIndex(list, 0))]; pigeonResult.allTypes = [AllTypes nullableFromList:(GetNullableObjectAtIndex(list, 1))]; return pigeonResult; } + (nullable AllClassesWrapper *)nullableFromList:(NSArray *)list { return (list) ? [AllClassesWrapper fromList:list] : nil; } - (NSArray *)toList { return @[ (self.allNullableTypes ? [self.allNullableTypes toList] : [NSNull null]), (self.allTypes ? [self.allTypes toList] : [NSNull null]), ]; } @end @implementation TestMessage + (instancetype)makeWithTestList:(nullable NSArray *)testList { TestMessage *pigeonResult = [[TestMessage alloc] init]; pigeonResult.testList = testList; return pigeonResult; } + (TestMessage *)fromList:(NSArray *)list { TestMessage *pigeonResult = [[TestMessage alloc] init]; pigeonResult.testList = GetNullableObjectAtIndex(list, 0); return pigeonResult; } + (nullable TestMessage *)nullableFromList:(NSArray *)list { return (list) ? [TestMessage fromList:list] : nil; } - (NSArray *)toList { return @[ self.testList ?: [NSNull null], ]; } @end @interface HostIntegrationCoreApiCodecReader : FlutterStandardReader @end @implementation HostIntegrationCoreApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [AllClassesWrapper fromList:[self readValue]]; case 129: return [AllNullableTypes fromList:[self readValue]]; case 130: return [AllTypes fromList:[self readValue]]; case 131: return [TestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface HostIntegrationCoreApiCodecWriter : FlutterStandardWriter @end @implementation HostIntegrationCoreApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[AllClassesWrapper class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[AllNullableTypes class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[AllTypes class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[TestMessage class]]) { [self writeByte:131]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface HostIntegrationCoreApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation HostIntegrationCoreApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[HostIntegrationCoreApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[HostIntegrationCoreApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *HostIntegrationCoreApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ HostIntegrationCoreApiCodecReaderWriter *readerWriter = [[HostIntegrationCoreApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void SetUpHostIntegrationCoreApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<HostIntegrationCoreApi> *api) { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(noopWithError:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(noopWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api noopWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoAllTypes:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoAllTypes:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); FlutterError *error; AllTypes *output = [api echoAllTypes:arg_everything error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns an error, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(throwErrorWithError:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(throwErrorWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; id output = [api throwErrorWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns an error from a void function, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwErrorFromVoid" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwErrorFromVoidWithError:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwErrorFromVoidWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api throwErrorFromVoidWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns a Flutter error, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwFlutterError" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwFlutterErrorWithError:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwFlutterErrorWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; id output = [api throwFlutterErrorWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoInt:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; NSNumber *output = [api echoInt:arg_anInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoDouble:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; FlutterError *error; NSNumber *output = [api echoDouble:arg_aDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoBool:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoBool:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; FlutterError *error; NSNumber *output = [api echoBool:arg_aBool error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoString:arg_aString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoUint8List:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoUint8List:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); FlutterError *error; FlutterStandardTypedData *output = [api echoUint8List:arg_aUint8List error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoObject:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoObject:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); FlutterError *error; id output = [api echoObject:arg_anObject error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoList:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoList:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSArray<id> *output = [api echoList:arg_aList error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoMap:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoMap:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSDictionary<NSString *, id> *output = [api echoMap:arg_aMap error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map to test nested class serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoClassWrapper" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoClassWrapper:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoClassWrapper:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllClassesWrapper *arg_wrapper = GetNullableObjectAtIndex(args, 0); FlutterError *error; AllClassesWrapper *output = [api echoClassWrapper:arg_wrapper error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoEnum:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoEnum:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; AnEnumBox *enumBox = [api echoEnum:arg_anEnum error:&error]; NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the default string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNamedDefaultString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNamedDefaultString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNamedDefaultString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNamedDefaultString:arg_aString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoOptionalDefaultDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoOptionalDefaultDouble:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoOptionalDefaultDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; FlutterError *error; NSNumber *output = [api echoOptionalDefaultDouble:arg_aDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoRequiredInt:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoRequiredInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; NSNumber *output = [api echoRequiredInt:arg_anInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAllNullableTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAllNullableTypes:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAllNullableTypes:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); FlutterError *error; AllNullableTypes *output = [api echoAllNullableTypes:arg_everything error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"extractNestedNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(extractNestedNullableStringFrom:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(extractNestedNullableStringFrom:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllClassesWrapper *arg_wrapper = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api extractNestedNullableStringFrom:arg_wrapper error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"createNestedNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(createNestedObjectWithNullableString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(createNestedObjectWithNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_nullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; AllClassesWrapper *output = [api createNestedObjectWithNullableString:arg_nullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in arguments of multiple types. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"sendMultipleNullableTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(sendMultipleNullableTypesABool: anInt:aString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(sendMultipleNullableTypesABool:anInt:aString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 1); NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 2); FlutterError *error; AllNullableTypes *output = [api sendMultipleNullableTypesABool:arg_aNullableBool anInt:arg_aNullableInt aString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoNullableInt:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoNullableInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableInt:arg_aNullableInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableDouble:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableDouble = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableDouble:arg_aNullableDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoNullableBool:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoNullableBool:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableBool:arg_aNullableBool error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNullableString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableUint8List:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableUint8List:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aNullableUint8List = GetNullableObjectAtIndex(args, 0); FlutterError *error; FlutterStandardTypedData *output = [api echoNullableUint8List:arg_aNullableUint8List error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableObject" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableObject:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableObject:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_aNullableObject = GetNullableObjectAtIndex(args, 0); FlutterError *error; id output = [api echoNullableObject:arg_aNullableObject error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoNullableList:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoNullableList:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aNullableList = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSArray<id> *output = [api echoNullableList:arg_aNullableList error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoNullableMap:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoNullableMap:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aNullableMap = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSDictionary<NSString *, id> *output = [api echoNullableMap:arg_aNullableMap error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoNullableEnum:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoNullableEnum:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); AnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; FlutterError *error; AnEnumBox *enumBox = [api echoNullableEnum:arg_anEnum error:&error]; NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoOptionalNullableInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoOptionalNullableInt:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoOptionalNullableInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoOptionalNullableInt:arg_aNullableInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNamedNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNamedNullableString:error:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNamedNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNamedNullableString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(noopAsyncWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(noopAsyncWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api noopAsyncWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoAsyncInt:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoAsyncInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; [api echoAsyncInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncDouble:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; [api echoAsyncDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncBool:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; [api echoAsyncBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed string asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncString:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoAsyncString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncUint8List:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); [api echoAsyncUint8List:arg_aUint8List completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncObject:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncObject:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); [api echoAsyncObject:arg_anObject completion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncList:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api echoAsyncList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoAsyncMap:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to @selector(echoAsyncMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api echoAsyncMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncEnum:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; [api echoAsyncEnum:arg_anEnum completion:^(AnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with an error from an async function returning a value. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncErrorWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with an error from an async void function. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwAsyncErrorFromVoid" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncErrorFromVoidWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncErrorFromVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncErrorFromVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with a Flutter error from an async function returning a value. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwAsyncFlutterError" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncFlutterErrorWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncFlutterErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncFlutterErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test async serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncAllTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncAllTypes:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncAllTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api echoAsyncAllTypes:arg_everything completion:^(AllTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableAllNullableTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableAllNullableTypes:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableAllNullableTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableAllNullableTypes:arg_everything completion:^(AllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableInt:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anInt = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableDouble:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aDouble = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableBool:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aBool = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed string asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableString:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableUint8List:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableUint8List:arg_aUint8List completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableObject" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableObject:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableObject:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableObject:arg_anObject completion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableList:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableMap:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableEnum:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); AnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; [api echoAsyncNullableEnum:arg_anEnum completion:^(AnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterNoopWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterNoopWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterNoopWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterThrowError" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterThrowErrorWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterThrowErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterThrowErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterThrowErrorFromVoid" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterThrowErrorFromVoidWithCompletion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterThrowErrorFromVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterThrowErrorFromVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoAllTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoAllTypes:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoAllTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoAllTypes:arg_everything completion:^(AllTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoAllNullableTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoAllNullableTypes:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoAllNullableTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoAllNullableTypes:arg_everything completion:^(AllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterSendMultipleNullableTypes" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector (callFlutterSendMultipleNullableTypesABool:anInt:aString:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterSendMultipleNullableTypesABool:anInt:aString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 1); NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 2); [api callFlutterSendMultipleNullableTypesABool:arg_aNullableBool anInt:arg_aNullableInt aString:arg_aNullableString completion:^(AllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoBool:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; [api callFlutterEchoBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoInt:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; [api callFlutterEchoInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoDouble:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; [api callFlutterEchoDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoString:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoUint8List:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoUint8List:arg_aList completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoList:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoMap:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoEnum:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; AnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; [api callFlutterEchoEnum:arg_anEnum completion:^(AnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableBool" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableBool:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aBool = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableInt" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableInt:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anInt = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableDouble" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableDouble:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aDouble = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableString" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableString:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableUint8List" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableUint8List:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableUint8List:arg_aList completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableList" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableList:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableMap" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableMap:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableEnum" binaryMessenger:binaryMessenger codec:HostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableEnum:completion:)], @"HostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); AnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; [api callFlutterEchoNullableEnum:arg_anEnum completion:^(AnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } } @interface FlutterIntegrationCoreApiCodecReader : FlutterStandardReader @end @implementation FlutterIntegrationCoreApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [AllClassesWrapper fromList:[self readValue]]; case 129: return [AllNullableTypes fromList:[self readValue]]; case 130: return [AllTypes fromList:[self readValue]]; case 131: return [TestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FlutterIntegrationCoreApiCodecWriter : FlutterStandardWriter @end @implementation FlutterIntegrationCoreApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[AllClassesWrapper class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[AllNullableTypes class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[AllTypes class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[TestMessage class]]) { [self writeByte:131]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FlutterIntegrationCoreApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FlutterIntegrationCoreApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FlutterIntegrationCoreApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FlutterIntegrationCoreApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FlutterIntegrationCoreApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FlutterIntegrationCoreApiCodecReaderWriter *readerWriter = [[FlutterIntegrationCoreApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } @interface FlutterIntegrationCoreApi () @property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger; @end @implementation FlutterIntegrationCoreApi - (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger { self = [super init]; if (self) { _binaryMessenger = binaryMessenger; } return self; } - (void)noopWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)throwErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { id output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)throwErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)echoAllTypes:(AllTypes *)arg_everything completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_everything ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { AllTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoAllNullableTypes:(nullable AllNullableTypes *)arg_everything completion: (void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_everything ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { AllNullableTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)sendMultipleNullableTypesABool:(nullable NSNumber *)arg_aNullableBool anInt:(nullable NSNumber *)arg_aNullableInt aString:(nullable NSString *)arg_aNullableString completion:(void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." @"sendMultipleNullableTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aNullableBool ?: [NSNull null], arg_aNullableInt ?: [NSNull null], arg_aNullableString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { AllNullableTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoBool:(BOOL)arg_aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_aBool) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoInt:(NSInteger)arg_anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_anInt) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoDouble:(double)arg_aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_aDouble) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoUint8List:(FlutterStandardTypedData *)arg_aList completion: (void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FlutterStandardTypedData *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoList:(NSArray<id> *)arg_aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSArray<id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoMap:(NSDictionary<NSString *, id> *)arg_aMap completion: (void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aMap ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSDictionary<NSString *, id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoEnum:(AnEnum)arg_anEnum completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ [NSNumber numberWithInteger:arg_anEnum] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *outputAsNumber = reply[0] == [NSNull null] ? nil : reply[0]; AnEnumBox *output = outputAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[outputAsNumber integerValue]]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableBool:(nullable NSNumber *)arg_aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aBool ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableInt:(nullable NSNumber *)arg_anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_anInt ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableDouble:(nullable NSNumber *)arg_aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aDouble ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableString:(nullable NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableUint8List:(nullable FlutterStandardTypedData *)arg_aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." @"echoNullableUint8List"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FlutterStandardTypedData *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableList:(nullable NSArray<id> *)arg_aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSArray<id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableMap:(nullable NSDictionary<NSString *, id> *)arg_aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aMap ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSDictionary<NSString *, id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableEnum:(nullable AnEnumBox *)arg_anEnum completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_anEnum == nil ? [NSNull null] : [NSNumber numberWithInteger:arg_anEnum.value] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *outputAsNumber = reply[0] == [NSNull null] ? nil : reply[0]; AnEnumBox *output = outputAsNumber == nil ? nil : [[AnEnumBox alloc] initWithValue:[outputAsNumber integerValue]]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)echoAsyncString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } @end NSObject<FlutterMessageCodec> *HostTrivialApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } void SetUpHostTrivialApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<HostTrivialApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop" binaryMessenger:binaryMessenger codec:HostTrivialApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(noopWithError:)], @"HostTrivialApi api (%@) doesn't respond to @selector(noopWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api noopWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } } NSObject<FlutterMessageCodec> *HostSmallApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } void SetUpHostSmallApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<HostSmallApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" binaryMessenger:binaryMessenger codec:HostSmallApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoString:completion:)], @"HostSmallApi api (%@) doesn't respond to @selector(echoString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid" binaryMessenger:binaryMessenger codec:HostSmallApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(voidVoidWithCompletion:)], @"HostSmallApi api (%@) doesn't respond to @selector(voidVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api voidVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } } @interface FlutterSmallApiCodecReader : FlutterStandardReader @end @implementation FlutterSmallApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [TestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FlutterSmallApiCodecWriter : FlutterStandardWriter @end @implementation FlutterSmallApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[TestMessage class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FlutterSmallApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FlutterSmallApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FlutterSmallApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FlutterSmallApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FlutterSmallApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FlutterSmallApiCodecReaderWriter *readerWriter = [[FlutterSmallApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } @interface FlutterSmallApi () @property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger; @end @implementation FlutterSmallApi - (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger { self = [super init]; if (self) { _binaryMessenger = binaryMessenger; } return self; } - (void)echoWrappedList:(TestMessage *)arg_msg completion:(void (^)(TestMessage *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterSmallApiGetCodec()]; [channel sendMessage:@[ arg_msg ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { TestMessage *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FlutterSmallApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/CoreTests.gen.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/CoreTests.gen.m", "repo_id": "packages", "token_count": 66528 }
1,029
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // 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".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } enum NullFieldsSearchReplyType { success, failure, } class NullFieldsSearchRequest { NullFieldsSearchRequest({ this.query, required this.identifier, }); String? query; int identifier; Object encode() { return <Object?>[ query, identifier, ]; } static NullFieldsSearchRequest decode(Object result) { result as List<Object?>; return NullFieldsSearchRequest( query: result[0] as String?, identifier: result[1]! as int, ); } } class NullFieldsSearchReply { NullFieldsSearchReply({ this.result, this.error, this.indices, this.request, this.type, }); String? result; String? error; List<int?>? indices; NullFieldsSearchRequest? request; NullFieldsSearchReplyType? type; Object encode() { return <Object?>[ result, error, indices, request?.encode(), type?.index, ]; } static NullFieldsSearchReply decode(Object result) { result as List<Object?>; return NullFieldsSearchReply( result: result[0] as String?, error: result[1] as String?, indices: (result[2] as List<Object?>?)?.cast<int?>(), request: result[3] != null ? NullFieldsSearchRequest.decode(result[3]! as List<Object?>) : null, type: result[4] != null ? NullFieldsSearchReplyType.values[result[4]! as int] : null, ); } } class _NullFieldsHostApiCodec extends StandardMessageCodec { const _NullFieldsHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NullFieldsSearchReply) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NullFieldsSearchRequest) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NullFieldsSearchReply.decode(readValue(buffer)!); case 129: return NullFieldsSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class NullFieldsHostApi { /// Constructor for [NullFieldsHostApi]. 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. NullFieldsHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = _NullFieldsHostApiCodec(); Future<NullFieldsSearchReply> search(NullFieldsSearchRequest nested) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsHostApi.search'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[nested]) 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 NullFieldsSearchReply?)!; } } } class _NullFieldsFlutterApiCodec extends StandardMessageCodec { const _NullFieldsFlutterApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NullFieldsSearchReply) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NullFieldsSearchRequest) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NullFieldsSearchReply.decode(readValue(buffer)!); case 129: return NullFieldsSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class NullFieldsFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = _NullFieldsFlutterApiCodec(); NullFieldsSearchReply search(NullFieldsSearchRequest request); static void setup(NullFieldsFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null.'); final List<Object?> args = (message as List<Object?>?)!; final NullFieldsSearchRequest? arg_request = (args[0] as NullFieldsSearchRequest?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null, expected non-null NullFieldsSearchRequest.'); try { final NullFieldsSearchReply output = api.search(arg_request!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart", "repo_id": "packages", "token_count": 2905 }
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. // // 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, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_test_plugin_code/src/generated/message.gen.dart'; class _TestHostApiCodec extends StandardMessageCodec { const _TestHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageSearchReply) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MessageSearchRequest) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageSearchReply.decode(readValue(buffer)!); case 129: return MessageSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// This comment is to test api documentation comments. /// /// This comment also tests multiple line comments. abstract class TestHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestHostApiCodec(); /// This comment is to test documentation comments. /// /// This comment also tests multiple line comments. void initialize(); /// This comment is to test method documentation comments. MessageSearchReply search(MessageSearchRequest request); static void setup(TestHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { // ignore message api.initialize(); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null.'); final List<Object?> args = (message as List<Object?>?)!; final MessageSearchRequest? arg_request = (args[0] as MessageSearchRequest?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.'); final MessageSearchReply output = api.search(arg_request!); return <Object?>[output]; }); } } } } class _TestNestedApiCodec extends StandardMessageCodec { const _TestNestedApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageNested) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MessageSearchReply) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is MessageSearchRequest) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageNested.decode(readValue(buffer)!); case 129: return MessageSearchReply.decode(readValue(buffer)!); case 130: return MessageSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// This comment is to test api documentation comments. abstract class TestNestedApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestNestedApiCodec(); /// This comment is to test method documentation comments. /// /// This comment also tests multiple line comments. MessageSearchReply search(MessageNested nested); static void setup(TestNestedApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null.'); final List<Object?> args = (message as List<Object?>?)!; final MessageNested? arg_nested = (args[0] as MessageNested?); assert(arg_nested != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null, expected non-null MessageNested.'); final MessageSearchReply output = api.search(arg_nested!); return <Object?>[output]; }); } } } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart", "repo_id": "packages", "token_count": 2554 }
1,031
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package 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 class ListTest : TestCase() { @Test fun testListInList() { val binaryMessenger = mockk<BinaryMessenger>() val api = FlutterSmallApi(binaryMessenger) val inside = TestMessage(listOf(1, 2, 3)) val input = TestMessage(listOf(inside)) every { binaryMessenger.send(any(), any(), any()) } answers { val codec = FlutterSmallApi.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.echoWrappedList(input) { didCall = true assertEquals(input, it.getOrNull()) } assertTrue(didCall) } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/ListTest.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/ListTest.kt", "repo_id": "packages", "token_count": 489 }
1,032
// 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 <gtest/gtest.h> #include "pigeon/multiple_arity.gen.h" #include "test/utils/fake_host_messenger.h" namespace multiple_arity_pigeontest { namespace { using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; using testing::FakeHostMessenger; class TestHostApi : public MultipleArityHostApi { public: TestHostApi() {} virtual ~TestHostApi() {} protected: ErrorOr<int64_t> Subtract(int64_t x, int64_t y) override { return x - y; } }; const EncodableValue& GetResult(const EncodableValue& pigeon_response) { return std::get<EncodableList>(pigeon_response)[0]; } } // namespace TEST(MultipleArity, HostSimple) { FakeHostMessenger messenger(&MultipleArityHostApi::GetCodec()); TestHostApi api; MultipleArityHostApi::SetUp(&messenger, &api); int64_t result = 0; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi." "subtract", EncodableValue(EncodableList({ EncodableValue(30), EncodableValue(10), })), [&result](const EncodableValue& reply) { result = GetResult(reply).LongValue(); }); EXPECT_EQ(result, 20); } // TODO(stuartmorgan): Add a FlutterApi version of the test. } // namespace multiple_arity_pigeontest
packages/packages/pigeon/platform_tests/test_plugin/windows/test/multiple_arity_test.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/multiple_arity_test.cpp", "repo_id": "packages", "token_count": 540 }
1,033
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/ast.dart'; import 'package:pigeon/dart_generator.dart'; import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { group('ProxyApi', () { test('one api', () { final Root root = Root(apis: <Api>[ AstProxyApi(name: 'Api', constructors: <Constructor>[ Constructor(name: 'name', parameters: <Parameter>[ Parameter( type: const TypeDeclaration( baseName: 'Input', isNullable: false, ), name: 'input', ), ]), ], fields: <ApiField>[ ApiField( name: 'someField', type: const TypeDeclaration( baseName: 'int', isNullable: false, ), ) ], methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: const TypeDeclaration( baseName: 'Input', isNullable: false, ), name: 'input', ) ], returnType: const TypeDeclaration( baseName: 'String', isNullable: false, ), ), Method( name: 'doSomethingElse', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: const TypeDeclaration( baseName: 'Input', isNullable: false, ), name: 'input', ) ], returnType: const TypeDeclaration( baseName: 'String', isNullable: false, ), isRequired: false, ), ]) ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); // Instance Manager expect(code, contains(r'class PigeonInstanceManager')); expect(code, contains(r'class _PigeonInstanceManagerApi')); // Base Api class expect( code, contains(r'abstract class PigeonProxyApiBaseClass'), ); // Codec and class expect(code, contains('class _PigeonProxyApiBaseCodec')); expect(code, contains(r'class Api extends PigeonProxyApiBaseClass')); // Constructors expect( collapsedCode, contains( r'Api.name({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, required this.someField, this.doSomethingElse, required Input input, })', ), ); expect( code, contains( r'Api.pigeon_detached', ), ); // Field expect(code, contains('final int someField;')); // Dart -> Host method expect(code, contains('Future<String> doSomething(Input input)')); // Host -> Dart method expect(code, contains(r'static void pigeon_setUpMessageHandlers({')); expect( collapsedCode, contains( 'final String Function( Api pigeon_instance, Input input, )? doSomethingElse;', ), ); // Copy method expect(code, contains(r'Api pigeon_copy(')); }); group('inheritance', () { test('extends', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final Root root = Root(apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], superClass: TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ), ), api2, ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains(r'class Api extends Api2')); expect( collapsedCode, contains( r'Api.pigeon_detached({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) : super.pigeon_detached();', ), ); }); test('implements', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final Root root = Root(apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ) }, ), api2, ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( r'class Api extends PigeonProxyApiBaseClass implements Api2', ), ); }); test('implements 2 ProxyApis', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final AstProxyApi api3 = AstProxyApi( name: 'Api3', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final Root root = Root(apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ), TypeDeclaration( baseName: 'Api3', isNullable: false, associatedProxyApi: api2, ), }, ), api2, api3, ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( r'class Api extends PigeonProxyApiBaseClass implements Api2, Api3', ), ); }); test('implements inherits flutter methods', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[ Method( name: 'aFlutterMethod', returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[], location: ApiLocation.flutter, ), Method( name: 'aNullableFlutterMethod', returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[], location: ApiLocation.flutter, isRequired: false, ), ], ); final Root root = Root(apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ) }, ), api2, ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( code, contains( r'class Api extends PigeonProxyApiBaseClass implements Api2', ), ); expect( collapsedCode, contains( r'Api.pigeon_detached({ super.pigeon_binaryMessenger, ' r'super.pigeon_instanceManager, ' r'required this.aFlutterMethod, ' r'this.aNullableFlutterMethod, })', ), ); }); }); group('Constructors', () { test('empty name and no params constructor', () { final Root root = Root( apis: <Api>[ AstProxyApi(name: 'Api', constructors: <Constructor>[ Constructor( name: '', parameters: <Parameter>[], ) ], fields: <ApiField>[], methods: <Method>[]), ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'Api({ super.pigeon_binaryMessenger, ' r'super.pigeon_instanceManager, })', ), ); expect( collapsedCode, contains( r"const String __pigeon_channelName = 'dev.flutter.pigeon.test_package.Api.pigeon_defaultConstructor';", ), ); expect( collapsedCode, contains( r'__pigeon_channel .send(<Object?>[__pigeon_instanceIdentifier])', ), ); }); test('multiple params constructor', () { final Enum anEnum = Enum( name: 'AnEnum', members: <EnumMember>[EnumMember(name: 'one')], ); final Root root = Root( apis: <Api>[ AstProxyApi(name: 'Api', constructors: <Constructor>[ Constructor( name: 'name', parameters: <Parameter>[ Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'int', ), name: 'validType', ), Parameter( type: TypeDeclaration( isNullable: false, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'enumType', ), Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'Api2', ), name: 'proxyApiType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'int', ), name: 'nullableValidType', ), Parameter( type: TypeDeclaration( isNullable: true, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'nullableEnumType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'Api2', ), name: 'nullableProxyApiType', ), ], ) ], fields: <ApiField>[], methods: <Method>[]), AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ), ], classes: <Class>[], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'Api.name({ super.pigeon_binaryMessenger, ' r'super.pigeon_instanceManager, ' r'required int validType, ' r'required AnEnum enumType, ' r'required Api2 proxyApiType, ' r'int? nullableValidType, ' r'AnEnum? nullableEnumType, ' r'Api2? nullableProxyApiType, })', ), ); expect( collapsedCode, contains( r'__pigeon_channel.send(<Object?>[ ' r'__pigeon_instanceIdentifier, ' r'validType, enumType.index, proxyApiType, ' r'nullableValidType, nullableEnumType?.index, nullableProxyApiType ])', ), ); }); }); group('Fields', () { test('constructor with fields', () { final Enum anEnum = Enum( name: 'AnEnum', members: <EnumMember>[EnumMember(name: 'one')], ); final Root root = Root( apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[ Constructor( name: 'name', parameters: <Parameter>[], ) ], fields: <ApiField>[ ApiField( type: const TypeDeclaration( isNullable: false, baseName: 'int', ), name: 'validType', ), ApiField( type: TypeDeclaration( isNullable: false, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'enumType', ), ApiField( type: const TypeDeclaration( isNullable: false, baseName: 'Api2', ), name: 'proxyApiType', ), ApiField( type: const TypeDeclaration( isNullable: true, baseName: 'int', ), name: 'nullableValidType', ), ApiField( type: TypeDeclaration( isNullable: true, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'nullableEnumType', ), ApiField( type: const TypeDeclaration( isNullable: true, baseName: 'Api2', ), name: 'nullableProxyApiType', ), ], methods: <Method>[], ), AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ), ], classes: <Class>[], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'Api.name({ super.pigeon_binaryMessenger, ' r'super.pigeon_instanceManager, ' r'required this.validType, ' r'required this.enumType, ' r'required this.proxyApiType, ' r'this.nullableValidType, ' r'this.nullableEnumType, ' r'this.nullableProxyApiType, })', ), ); expect( collapsedCode, contains( r'__pigeon_channel.send(<Object?>[ ' r'__pigeon_instanceIdentifier, ' r'validType, enumType.index, proxyApiType, ' r'nullableValidType, nullableEnumType?.index, nullableProxyApiType ])', ), ); expect( code, contains(r'final int validType;'), ); expect( code, contains(r'final AnEnum enumType;'), ); expect( code, contains(r'final Api2 proxyApiType;'), ); expect( code, contains(r'final int? nullableValidType;'), ); expect( code, contains(r'final AnEnum? nullableEnumType;'), ); expect( code, contains(r'final Api2? nullableProxyApiType;'), ); }); test('attached field', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final Root root = Root( apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[ ApiField( name: 'aField', isAttached: true, type: TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ), ), ], methods: <Method>[], ), api2, ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, contains(r'late final Api2 aField = __pigeon_aField();')); expect(code, contains(r'Api2 __pigeon_aField()')); }); test('static attached field', () { final AstProxyApi api2 = AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ); final Root root = Root( apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[ ApiField( name: 'aField', isStatic: true, isAttached: true, type: TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: api2, ), ), ], methods: <Method>[], ), api2, ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect( code, contains(r'static final Api2 aField = __pigeon_aField();')); expect(code, contains(r'static Api2 __pigeon_aField()')); }); }); group('Host methods', () { test('multiple params method', () { final Enum anEnum = Enum( name: 'AnEnum', members: <EnumMember>[EnumMember(name: 'one')], ); final Root root = Root( apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'int', ), name: 'validType', ), Parameter( type: TypeDeclaration( isNullable: false, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'enumType', ), Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'Api2', ), name: 'proxyApiType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'int', ), name: 'nullableValidType', ), Parameter( type: TypeDeclaration( isNullable: true, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'nullableEnumType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'Api2', ), name: 'nullableProxyApiType', ), ], returnType: const TypeDeclaration.voidDeclaration(), ), ], ), AstProxyApi( name: 'Api2', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[], ), ], classes: <Class>[], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'Future<void> doSomething( int validType, AnEnum enumType, ' r'Api2 proxyApiType, int? nullableValidType, ' r'AnEnum? nullableEnumType, Api2? nullableProxyApiType, )', ), ); expect( collapsedCode, contains( r'await __pigeon_channel.send(<Object?>[ this, validType, ' r'enumType.index, proxyApiType, nullableValidType, ' r'nullableEnumType?.index, nullableProxyApiType ])', ), ); }); test('static method', () { final Root root = Root( apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, isStatic: true, parameters: <Parameter>[], returnType: const TypeDeclaration.voidDeclaration(), ), ], ), ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'static Future<void> doSomething({ BinaryMessenger? pigeon_binaryMessenger, ' r'PigeonInstanceManager? pigeon_instanceManager, })', ), ); expect( collapsedCode, contains(r'await __pigeon_channel.send(null)'), ); }); }); group('Flutter methods', () { test('multiple params flutter method', () { final Enum anEnum = Enum( name: 'AnEnum', members: <EnumMember>[EnumMember(name: 'one')], ); final Root root = Root(apis: <Api>[ AstProxyApi( name: 'Api', constructors: <Constructor>[], fields: <ApiField>[], methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, isRequired: false, parameters: <Parameter>[ Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'int', ), name: 'validType', ), Parameter( type: TypeDeclaration( isNullable: false, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'enumType', ), Parameter( type: const TypeDeclaration( isNullable: false, baseName: 'Api2', ), name: 'proxyApiType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'int', ), name: 'nullableValidType', ), Parameter( type: TypeDeclaration( isNullable: true, baseName: 'AnEnum', associatedEnum: anEnum, ), name: 'nullableEnumType', ), Parameter( type: const TypeDeclaration( isNullable: true, baseName: 'Api2', ), name: 'nullableProxyApiType', ), ], returnType: const TypeDeclaration.voidDeclaration(), ), ]) ], classes: <Class>[], enums: <Enum>[ anEnum ]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( collapsedCode, contains( r'final void Function( Api pigeon_instance, int validType, ' r'AnEnum enumType, Api2 proxyApiType, int? nullableValidType, ' r'AnEnum? nullableEnumType, Api2? nullableProxyApiType, )? ' r'doSomething;', ), ); expect( collapsedCode, contains( r'void Function( Api pigeon_instance, int validType, AnEnum enumType, ' r'Api2 proxyApiType, int? nullableValidType, ' r'AnEnum? nullableEnumType, Api2? nullableProxyApiType, )? ' r'doSomething'), ); expect( code, contains(r'final Api? arg_pigeon_instance = (args[0] as Api?);'), ); expect( code, contains(r'final int? arg_validType = (args[1] as int?);'), ); expect( collapsedCode, contains( r'final AnEnum? arg_enumType = args[2] == null ? ' r'null : AnEnum.values[args[2]! as int];', ), ); expect( code, contains(r'final Api2? arg_proxyApiType = (args[3] as Api2?);'), ); expect( code, contains(r'final int? arg_nullableValidType = (args[4] as int?);'), ); expect( collapsedCode, contains( r'final AnEnum? arg_nullableEnumType = args[5] == null ? ' r'null : AnEnum.values[args[5]! as int];', ), ); expect( collapsedCode, contains( r'(doSomething ?? arg_pigeon_instance!.doSomething)?.call( arg_pigeon_instance!, ' r'arg_validType!, arg_enumType!, arg_proxyApiType!, ' r'arg_nullableValidType, arg_nullableEnumType, ' r'arg_nullableProxyApiType);', ), ); }); }); }); } /// Replaces a new line and the indentation with a single white space /// /// This /// /// ```dart /// void method( /// int param1, /// int param2, /// ) /// ``` /// /// converts to /// /// ```dart /// void method( int param1, int param2, ) /// ``` String _collapseNewlineAndIndentation(String string) { final StringBuffer result = StringBuffer(); for (final String line in string.split('\n')) { result.write('${line.trimLeft()} '); } return result.toString().trim(); }
packages/packages/pigeon/test/dart/proxy_api_test.dart/0
{ "file_path": "packages/packages/pigeon/test/dart/proxy_api_test.dart", "repo_id": "packages", "token_count": 18117 }
1,034
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' show Process, ProcessStartMode, stderr, stdout; Future<int> runProcess(String command, List<String> arguments, {String? workingDirectory, bool streamOutput = true, bool logFailure = false}) async { final Process process = await Process.start( command, arguments, workingDirectory: workingDirectory, mode: streamOutput ? ProcessStartMode.inheritStdio : ProcessStartMode.normal, ); if (streamOutput) { return process.exitCode; } final List<int> stdoutBuffer = <int>[]; final List<int> stderrBuffer = <int>[]; final Future<void> stdoutFuture = process.stdout.forEach(stdoutBuffer.addAll); final Future<void> stderrFuture = process.stderr.forEach(stderrBuffer.addAll); final int exitCode = await process.exitCode; await Future.wait(<Future<void>>[ stdoutFuture, stderrFuture, ]); if (exitCode != 0 && logFailure) { // ignore: avoid_print print('$command $arguments failed:'); stdout.add(stdoutBuffer); stderr.add(stderrBuffer); await Future.wait(<Future<void>>[ stdout.flush(), stderr.flush(), ]); } return exitCode; }
packages/packages/pigeon/tool/shared/process_utils.dart/0
{ "file_path": "packages/packages/pigeon/tool/shared/process_utils.dart", "repo_id": "packages", "token_count": 467 }
1,035
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/platform/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/platform/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,036
name: pointer_interceptor_example description: An example app for the pointer_interceptor package. publish_to: 'none' version: 1.0.0 environment: sdk: ">=3.1.0 <4.0.0" flutter: ">=3.13.0" dependencies: flutter: sdk: flutter pointer_interceptor: path: ../ dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true
packages/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml", "repo_id": "packages", "token_count": 214 }
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 'dart:convert'; import 'dart:io' show Process, ProcessException, ProcessResult, ProcessSignal, ProcessStartMode, systemEncoding; import 'common.dart'; import 'exceptions.dart'; import 'process_manager.dart'; /// Local implementation of the `ProcessManager` interface. /// /// This implementation delegates directly to the corresponding static methods /// in `dart:io`. /// /// All methods that take a `command` will run `toString()` on the command /// elements to derive the executable and arguments that should be passed to /// the underlying `dart:io` methods. Thus, the degenerate case of /// `List<String>` will trivially work as expected. class LocalProcessManager implements ProcessManager { /// Creates a new `LocalProcessManager`. const LocalProcessManager(); @override Future<Process> start( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, ProcessStartMode mode = ProcessStartMode.normal, }) { try { return Process.start( sanitizeExecutablePath(_getExecutable( command, workingDirectory, runInShell, )), _getArguments(command), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, mode: mode, ); } on ProcessException catch (exception) { throw ProcessPackageException.fromProcessException(exception, workingDirectory: workingDirectory); } } @override Future<ProcessResult> run( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }) { try { return Process.run( sanitizeExecutablePath(_getExecutable( command, workingDirectory, runInShell, )), _getArguments(command), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, stdoutEncoding: stdoutEncoding, stderrEncoding: stderrEncoding, ); } on ProcessException catch (exception) { throw ProcessPackageException.fromProcessException(exception, workingDirectory: workingDirectory); } } @override ProcessResult runSync( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }) { try { return Process.runSync( sanitizeExecutablePath(_getExecutable( command, workingDirectory, runInShell, )), _getArguments(command), workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, stdoutEncoding: stdoutEncoding, stderrEncoding: stderrEncoding, ); } on ProcessException catch (exception) { throw ProcessPackageException.fromProcessException(exception, workingDirectory: workingDirectory); } } @override bool canRun(covariant String executable, {String? workingDirectory}) => getExecutablePath(executable, workingDirectory) != null; @override bool killPid(int pid, [ProcessSignal signal = ProcessSignal.sigterm]) { return Process.killPid(pid, signal); } } String _getExecutable( List<dynamic> command, String? workingDirectory, bool runInShell) { final String commandName = command.first.toString(); if (runInShell) { return commandName; } return getExecutablePath( commandName, workingDirectory, throwOnFailure: true, )!; } List<String> _getArguments(List<Object> command) => // Adding a specific type to map in order to workaround dart issue // https://github.com/dart-lang/sdk/issues/32414 command .skip(1) .map<String>((dynamic element) => element.toString()) .toList();
packages/packages/process/lib/src/interface/local_process_manager.dart/0
{ "file_path": "packages/packages/process/lib/src/interface/local_process_manager.dart", "repo_id": "packages", "token_count": 1652 }
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. package io.flutter.plugins.quickactions; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutInfo; import android.content.pm.ShortcutManager; import android.content.res.Resources; import android.graphics.drawable.Icon; import android.os.Build; import android.os.Handler; import android.os.Looper; import androidx.annotation.ChecksSdkIntAtLeast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugins.quickactions.Messages.AndroidQuickActionsApi; import io.flutter.plugins.quickactions.Messages.FlutterError; import io.flutter.plugins.quickactions.Messages.Result; import io.flutter.plugins.quickactions.Messages.ShortcutItemMessage; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; final class QuickActions implements AndroidQuickActionsApi { protected static final String EXTRA_ACTION = "some unique action key"; private final Context context; private Activity activity; QuickActions(Context context) { this.context = context; } void setActivity(Activity activity) { this.activity = activity; } public Activity getActivity() { return this.activity; } // Returns true when running on a version of Android that supports quick actions. // When this returns false, methods should silently no-op, per the documented behavior (see README.md). @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.N_MR1) boolean isVersionAllowed() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1; } @Override public void setShortcutItems( @NonNull List<ShortcutItemMessage> itemsList, @NonNull Result<Void> result) { if (!isVersionAllowed()) { result.success(null); return; } ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE); List<ShortcutInfo> shortcuts = shortcutItemMessageToShortcutInfo(itemsList); Executor uiThreadExecutor = new UiThreadExecutor(); ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); executor.execute( () -> { boolean dynamicShortcutsSet = false; try { shortcutManager.setDynamicShortcuts(shortcuts); dynamicShortcutsSet = true; } catch (Exception e) { // Leave dynamicShortcutsSet as false } final boolean didSucceed = dynamicShortcutsSet; // TODO(camsim99): Investigate removing all of the executor logic in favor of background channels. uiThreadExecutor.execute( () -> { if (didSucceed) { result.success(null); } else { result.error( new FlutterError( "quick_action_setshortcutitems_failure", "Exception thrown when setting dynamic shortcuts", null)); } }); }); } @Override public void clearShortcutItems() { if (!isVersionAllowed()) { return; } ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE); shortcutManager.removeAllDynamicShortcuts(); } @Override public @Nullable String getLaunchAction() { if (!isVersionAllowed()) { return null; } ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE); if (activity == null) { throw new FlutterError( "quick_action_getlaunchaction_no_activity", "There is no activity available when launching action", null); } final Intent intent = activity.getIntent(); final String launchAction = intent.getStringExtra(EXTRA_ACTION); if (launchAction != null && !launchAction.isEmpty()) { shortcutManager.reportShortcutUsed(launchAction); intent.removeExtra(EXTRA_ACTION); } return launchAction; } @TargetApi(Build.VERSION_CODES.N_MR1) private List<ShortcutInfo> shortcutItemMessageToShortcutInfo( @NonNull List<ShortcutItemMessage> shortcuts) { final List<ShortcutInfo> shortcutInfos = new ArrayList<>(); for (ShortcutItemMessage shortcut : shortcuts) { final String icon = shortcut.getIcon(); final String type = shortcut.getType(); final String title = shortcut.getLocalizedTitle(); final ShortcutInfo.Builder shortcutBuilder = new ShortcutInfo.Builder(context, type); final int resourceId = loadResourceId(context, icon); final Intent intent = getIntentToOpenMainActivity(type); if (resourceId > 0) { shortcutBuilder.setIcon(Icon.createWithResource(context, resourceId)); } final ShortcutInfo shortcutInfo = shortcutBuilder.setLongLabel(title).setShortLabel(title).setIntent(intent).build(); shortcutInfos.add(shortcutInfo); } return shortcutInfos; } // This method requires doing dynamic resource lookup, which is a discouraged API. @SuppressWarnings("DiscouragedApi") private int loadResourceId(Context context, String icon) { if (icon == null) { return 0; } final String packageName = context.getPackageName(); final Resources res = context.getResources(); final int resourceId = res.getIdentifier(icon, "drawable", packageName); if (resourceId == 0) { return res.getIdentifier(icon, "mipmap", packageName); } else { return resourceId; } } private Intent getIntentToOpenMainActivity(String type) { final String packageName = context.getPackageName(); return context .getPackageManager() .getLaunchIntentForPackage(packageName) .setAction(Intent.ACTION_RUN) .putExtra(EXTRA_ACTION, type) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); } static class UiThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable command) { handler.post(command); } } }
packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActions.java/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActions.java", "repo_id": "packages", "token_count": 2383 }
1,039
name: quick_actions_android description: An implementation for the Android platform of the Flutter `quick_actions` plugin. repository: https://github.com/flutter/packages/tree/main/packages/quick_actions/quick_actions_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22 version: 1.0.10 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: quick_actions platforms: android: package: io.flutter.plugins.quickactions pluginClass: QuickActionsPlugin dartPluginClass: QuickActionsAndroid dependencies: flutter: sdk: flutter quick_actions_platform_interface: ^1.0.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter pigeon: ^11.0.1 plugin_platform_interface: ^2.1.7 topics: - quick-actions - os-integration
packages/packages/quick_actions/quick_actions_android/pubspec.yaml/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/pubspec.yaml", "repo_id": "packages", "token_count": 346 }
1,040
// 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 UIKit /// Provides the capability to get and set the app's home screen shortcut items. protocol ShortcutItemProviding: AnyObject { /// An array of shortcut items for home screen. var shortcutItems: [UIApplicationShortcutItem]? { get set } } /// A default implementation of the `ShortcutItemProviding` protocol. extension UIApplication: ShortcutItemProviding {}
packages/packages/quick_actions/quick_actions_ios/ios/Classes/ShortcutItemProviding.swift/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/ios/Classes/ShortcutItemProviding.swift", "repo_id": "packages", "token_count": 141 }
1,041
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/rfw/example/remote/android/gradle.properties/0
{ "file_path": "packages/packages/rfw/example/remote/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
1,042
// 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. // There's a lot of <Object>[] lists in this file so to avoid making this // file even less readable we relax our usual stance on verbose typing. // ignore_for_file: always_specify_types // This file is hand-formatted. import 'dart:math' as math show pi; // ignore: unnecessary_import, see https://github.com/flutter/flutter/pull/138881 import 'dart:ui' show FontFeature; // TODO(ianh): https://github.com/flutter/flutter/issues/87235 import 'package:flutter/material.dart'; import 'runtime.dart'; /// Default duration and curve for animations in remote flutter widgets. /// /// This inherited widget allows a duration and a curve (defaulting to 200ms and /// [Curves.fastOutSlowIn]) to be set as the default to use when local widgets /// use the [ArgumentsDecoder.curve] and [ArgumentsDecoder.duration] methods and /// find that the [DataSource] has no explicit curve or duration. class AnimationDefaults extends InheritedWidget { /// Configures an [AnimanionDefaults] widget. /// /// The [duration] and [curve] are optional, and default to 200ms and /// [Curves.fastOutSlowIn] respectively. const AnimationDefaults({ super.key, this.duration, this.curve, required super.child, }); /// The default duration that [ArgumentsDecoder.duration] should use. /// /// Defaults to 200ms when this is null. final Duration? duration; /// The default curve that [ArgumentsDecoder.curve] should use. /// /// Defaults to [Curves.fastOutSlowIn] when this is null. final Curve? curve; /// Return the ambient [AnimationDefaults.duration], or 200ms if there is no /// ambient [AnimationDefaults] or if the nearest [AnimationDefaults] has a /// null [duration]. static Duration durationOf(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<AnimationDefaults>()?.duration ?? const Duration(milliseconds: 200); } /// Return the ambient [AnimationDefaults.curve], or [Curves.fastOutSlowIn] if /// there is no ambient [AnimationDefaults] or if the nearest /// [AnimationDefaults] has a null [curve]. static Curve curveOf(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<AnimationDefaults>()?.curve ?? Curves.fastOutSlowIn; } @override bool updateShouldNotify(AnimationDefaults oldWidget) => duration != oldWidget.duration || curve != oldWidget.curve; } /// Signature for methods that decode structured values from a [DataSource], /// such as the static methods of [ArgumentDecoders]. /// /// Used to make some of the methods of that class extensible. typedef ArgumentDecoder<T> = T Function(DataSource source, List<Object> key); /// A set of methods for decoding structured values from a [DataSource]. /// /// Specifically, these methods decode types that are used by local widgets /// (q.v. [createCoreWidgets]). /// /// These methods take a [DataSource] and a `key`. The `key` is a path to the /// part of the [DataSource] that the value should be read from. This may /// identify a map, a list, or a leaf value, depending on the needs of the /// method. class ArgumentDecoders { const ArgumentDecoders._(); /// This is a workaround for https://github.com/dart-lang/sdk/issues/47021 static const ArgumentDecoders __ = ArgumentDecoders._(); // ignore: unused_field // (in alphabetical order) /// Decodes an [AlignmentDirectional] or [Alignment] object out of the /// specified map. /// /// If the map has `start` and `y` keys, then it is interpreted as an /// [AlignmentDirectional] with those values. Otherwise if it has `x` and `y` /// it's an [Alignment] with those values. Otherwise it returns null. static AlignmentGeometry? alignment(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } final double? x = source.v<double>([...key, 'x']); final double? start = source.v<double>([...key, 'start']); final double? y = source.v<double>([...key, 'y']); if (x == null && start == null) { return null; } if (y == null) { return null; } if (start != null) { return AlignmentDirectional(start, y); } x!; return Alignment(x, y); } /// Decodes the specified map into a [BoxConstraints]. /// /// The keys used are `minWidth`, `maxWidth`, `minHeight`, and `maxHeight`. /// Omitted keys are defaulted to 0.0 for minimums and infinity for maximums. static BoxConstraints? boxConstraints(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return BoxConstraints( minWidth: source.v<double>([...key, 'minWidth']) ?? 0.0, maxWidth: source.v<double>([...key, 'maxWidth']) ?? double.infinity, minHeight: source.v<double>([...key, 'minHeight']) ?? 0.0, maxHeight: source.v<double>([...key, 'maxHeight']) ?? double.infinity, ); } /// Returns a [BorderDirectional] from the specified list. /// /// The list is a list of values as interpreted by [borderSide]. An empty or /// missing list results in a null return value. The list should have one /// through four items. Extra items are ignored. /// /// The values are interpreted as follows: /// /// * start: first value. /// * top: second value, defaulting to same as start. /// * end: third value, defaulting to same as start. /// * bottom: fourth value, defaulting to same as top. static BoxBorder? border(DataSource source, List<Object> key) { final BorderSide? a = borderSide(source, [...key, 0]); if (a == null) { return null; } final BorderSide? b = borderSide(source, [...key, 1]); final BorderSide? c = borderSide(source, [...key, 2]); final BorderSide? d = borderSide(source, [...key, 3]); return BorderDirectional( start: a, top: b ?? a, end: c ?? a, bottom: d ?? b ?? a, ); } /// Returns a [BorderRadiusDirectional] from the specified list. /// /// The list is a list of values as interpreted by [radius]. An empty or /// missing list results in a null return value. The list should have one /// through four items. Extra items are ignored. /// /// The values are interpreted as follows: /// /// * topStart: first value. /// * topEnd: second value, defaulting to same as topStart. /// * bottomStart: third value, defaulting to same as topStart. /// * bottomEnd: fourth value, defaulting to same as topEnd. static BorderRadiusGeometry? borderRadius(DataSource source, List<Object> key) { final Radius? a = radius(source, [...key, 0]); if (a == null) { return null; } final Radius? b = radius(source, [...key, 1]); final Radius? c = radius(source, [...key, 2]); final Radius? d = radius(source, [...key, 3]); return BorderRadiusDirectional.only( topStart: a, topEnd: b ?? a, bottomStart: c ?? a, bottomEnd: d ?? b ?? a, ); } /// Returns a [BorderSide] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [BorderSide] is created from the /// keys `color` (see [color], defaults to black), `width` (a double, defaults /// to 1.0), and `style` (see [enumValue] for [BorderStyle], defaults to /// [BorderStyle.solid]). static BorderSide? borderSide(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return BorderSide( color: color(source, [...key, 'color']) ?? const Color(0xFF000000), width: source.v<double>([...key, 'width']) ?? 1.0, style: enumValue<BorderStyle>(BorderStyle.values, source, [...key, 'style']) ?? BorderStyle.solid, ); } /// Returns a [BoxShadow] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [BoxShadow] is created from the /// keys `color` (see [color], defaults to black), `offset` (see [offset], /// defaults to [Offset.zero]), `blurRadius` (double, defaults to zero), and /// `spreadRadius` (double, defaults to zero). static BoxShadow boxShadow(DataSource source, List<Object> key) { if (!source.isMap(key)) { return const BoxShadow(); } return BoxShadow( color: color(source, [...key, 'color']) ?? const Color(0xFF000000), offset: offset(source, [...key, 'offset']) ?? Offset.zero, blurRadius: source.v<double>([...key, 'blurRadius']) ?? 0.0, spreadRadius: source.v<double>([...key, 'spreadRadius']) ?? 0.0, ); } /// Returns a [Color] from the specified integer. /// /// Returns null if it's not an integer; otherwise, passes it to the [ /// Color] constructor. static Color? color(DataSource source, List<Object> key) { final int? value = source.v<int>(key); if (value == null) { return null; } return Color(value); } /// Returns a [ColorFilter] from the specified map. /// /// The `type` key specifies the kind of filter. /// /// A type of `linearToSrgbGamma` creates a [ColorFilter.linearToSrgbGamma]. /// /// A type of `matrix` creates a [ColorFilter.matrix], parsing the `matrix` /// key as per [colorMatrix]). If there is no `matrix` key, returns null. /// /// A type of `mode` creates a [ColorFilter.mode], using the `color` key /// (see[color], defaults to black) and the `blendMode` key (see [enumValue] for /// [BlendMdoe], defaults to [BlendMode.srcOver]) /// /// A type of `srgbToLinearGamma` creates a [ColorFilter.srgbToLinearGamma]. /// /// If the type is none of these, but is not null, then the type is looked up /// in [colorFilterDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static ColorFilter? colorFilter(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'linearToSrgbGamma': return const ColorFilter.linearToSrgbGamma(); case 'matrix': final List<double>? matrix = colorMatrix(source, [...key, 'matrix']); if (matrix == null) { return null; } return ColorFilter.matrix(matrix); case 'mode': return ColorFilter.mode( color(source, [...key, 'color']) ?? const Color(0xFF000000), enumValue<BlendMode>(BlendMode.values, source, [...key, 'blendMode']) ?? BlendMode.srcOver, ); case 'srgbToLinearGamma': return const ColorFilter.srgbToLinearGamma(); default: final ArgumentDecoder<ColorFilter?>? decoder = colorFilterDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [colorFilter]. static final Map<String, ArgumentDecoder<ColorFilter?>> colorFilterDecoders = <String, ArgumentDecoder<ColorFilter?>>{}; /// Returns a list of 20 doubles from the specified list. /// /// If the specified key does not identify a list, returns null instead. /// /// If the list has fewer than 20 entries or if any of the entries are not /// doubles, any entries that could not be obtained are replaced by zero. /// /// Used by [colorFilter] in the `matrix` mode. static List<double>? colorMatrix(DataSource source, List<Object> key) { if (!source.isList(key)) { return null; } return <double>[ source.v<double>([...key, 0]) ?? 0.0, source.v<double>([...key, 1]) ?? 0.0, source.v<double>([...key, 2]) ?? 0.0, source.v<double>([...key, 3]) ?? 0.0, source.v<double>([...key, 4]) ?? 0.0, source.v<double>([...key, 5]) ?? 0.0, source.v<double>([...key, 6]) ?? 0.0, source.v<double>([...key, 7]) ?? 0.0, source.v<double>([...key, 8]) ?? 0.0, source.v<double>([...key, 9]) ?? 0.0, source.v<double>([...key, 10]) ?? 0.0, source.v<double>([...key, 11]) ?? 0.0, source.v<double>([...key, 12]) ?? 0.0, source.v<double>([...key, 13]) ?? 0.0, source.v<double>([...key, 14]) ?? 0.0, source.v<double>([...key, 15]) ?? 0.0, source.v<double>([...key, 16]) ?? 0.0, source.v<double>([...key, 17]) ?? 0.0, source.v<double>([...key, 18]) ?? 0.0, source.v<double>([...key, 19]) ?? 0.0, ]; } /// Returns a [Color] from the specified integer. /// /// Returns black if it's not an integer; otherwise, passes it to the [ /// Color] constructor. /// /// This is useful in situations where null is not acceptable, for example, /// when providing a decoder to [list]. Otherwise, prefer using [DataSource.v] /// directly. static Color colorOrBlack(DataSource source, List<Object> key) { return color(source, key) ?? const Color(0xFF000000); } /// Returns a [Curve] from the specified string. /// /// The given key should specify a string. If that string matches one of the /// names of static curves defined in the [Curves] class, then that curve is /// returned. Otherwise, if the string was not null, and is present as a key /// in the [curveDecoders] map, then the matching decoder from that map is /// invoked. Otherwise, the default obtained from [AnimationDefaults.curveOf] /// is used (which is why a [BuildContext] is required). static Curve curve(DataSource source, List<Object> key, BuildContext context) { final String? type = source.v<String>(key); switch (type) { case 'linear': return Curves.linear; case 'decelerate': return Curves.decelerate; case 'fastLinearToSlowEaseIn': return Curves.fastLinearToSlowEaseIn; case 'ease': return Curves.ease; case 'easeIn': return Curves.easeIn; case 'easeInToLinear': return Curves.easeInToLinear; case 'easeInSine': return Curves.easeInSine; case 'easeInQuad': return Curves.easeInQuad; case 'easeInCubic': return Curves.easeInCubic; case 'easeInQuart': return Curves.easeInQuart; case 'easeInQuint': return Curves.easeInQuint; case 'easeInExpo': return Curves.easeInExpo; case 'easeInCirc': return Curves.easeInCirc; case 'easeInBack': return Curves.easeInBack; case 'easeOut': return Curves.easeOut; case 'linearToEaseOut': return Curves.linearToEaseOut; case 'easeOutSine': return Curves.easeOutSine; case 'easeOutQuad': return Curves.easeOutQuad; case 'easeOutCubic': return Curves.easeOutCubic; case 'easeOutQuart': return Curves.easeOutQuart; case 'easeOutQuint': return Curves.easeOutQuint; case 'easeOutExpo': return Curves.easeOutExpo; case 'easeOutCirc': return Curves.easeOutCirc; case 'easeOutBack': return Curves.easeOutBack; case 'easeInOut': return Curves.easeInOut; case 'easeInOutSine': return Curves.easeInOutSine; case 'easeInOutQuad': return Curves.easeInOutQuad; case 'easeInOutCubic': return Curves.easeInOutCubic; case 'easeInOutCubicEmphasized': return Curves.easeInOutCubicEmphasized; case 'easeInOutQuart': return Curves.easeInOutQuart; case 'easeInOutQuint': return Curves.easeInOutQuint; case 'easeInOutExpo': return Curves.easeInOutExpo; case 'easeInOutCirc': return Curves.easeInOutCirc; case 'easeInOutBack': return Curves.easeInOutBack; case 'fastOutSlowIn': return Curves.fastOutSlowIn; case 'slowMiddle': return Curves.slowMiddle; case 'bounceIn': return Curves.bounceIn; case 'bounceOut': return Curves.bounceOut; case 'bounceInOut': return Curves.bounceInOut; case 'elasticIn': return Curves.elasticIn; case 'elasticOut': return Curves.elasticOut; case 'elasticInOut': return Curves.elasticInOut; default: if (type != null) { final ArgumentDecoder<Curve>? decoder = curveDecoders[type]; if (decoder != null) { return decoder(source, key); } } return AnimationDefaults.curveOf(context); } } /// Extension mechanism for [curve]. /// /// The decoders must not return null. /// /// The given key will specify a string, which is known to not match any of /// the values in [Curves]. static final Map<String, ArgumentDecoder<Curve>> curveDecoders = <String, ArgumentDecoder<Curve>>{}; /// Returns a [Decoration] from the specified map. /// /// The `type` key specifies the kind of decoration. /// /// A type of `box` creates a [BoxDecoration] using the keys `color` /// ([color]), `image` ([decorationImage]), `border` ([border]), /// `borderRadius` ([borderRadius]), `boxShadow` (a [list] of [boxShadow]), /// `gradient` ([gradient]), `backgroundBlendMode` (an [enumValue] of [BlendMode]), /// and `shape` (an [enumValue] of [BoxShape]), these keys each corresponding to /// the properties of [BoxDecoration] with the same name. /// /// A type of `flutterLogo` creates a [FlutterLogoDecoration] using the keys /// `color` ([color], corresponds to [FlutterLogoDecoration.textColor]), /// `style` ([enumValue] of [FlutterLogoStyle], defaults to /// [FlutterLogoStyle.markOnly]), and `margin` ([edgeInsets], always with a /// left-to-right direction), the latter two keys corresponding to /// the properties of [FlutterLogoDecoration] with the same name. /// /// A type of `shape` creates a [ShapeDecoration] using the keys `color` /// ([color]), `image` ([decorationImage]), `gradient` ([gradient]), `shadows` /// (a [list] of [boxShadow]), and `shape` ([shapeBorder]), these keys each /// corresponding to the properties of [ShapeDecoration] with the same name. /// /// If the type is none of these, but is not null, then the type is looked up /// in [decorationDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static Decoration? decoration(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'box': return BoxDecoration( color: color(source, [...key, 'color']), image: decorationImage(source, [...key, 'image']), border: border(source, [...key, 'border']), borderRadius: borderRadius(source, [...key, 'borderRadius']), boxShadow: list<BoxShadow>(source, [...key, 'boxShadow'], boxShadow), gradient: gradient(source, [...key, 'gradient']), backgroundBlendMode: enumValue<BlendMode>(BlendMode.values, source, [...key, 'backgroundBlendMode']), shape: enumValue<BoxShape>(BoxShape.values, source, [...key, 'shape']) ?? BoxShape.rectangle, ); case 'flutterLogo': return FlutterLogoDecoration( textColor: color(source, [...key, 'color']) ?? const Color(0xFF757575), style: enumValue<FlutterLogoStyle>(FlutterLogoStyle.values, source, [...key, 'style']) ?? FlutterLogoStyle.markOnly, margin: (edgeInsets(source, [...key, 'margin']) ?? EdgeInsets.zero).resolve(TextDirection.ltr), ); case 'shape': return ShapeDecoration( color: color(source, [...key, 'color']), image: decorationImage(source, [...key, 'image']), gradient: gradient(source, [...key, 'gradient']), shadows: list<BoxShadow>(source, [...key, 'shadows'], boxShadow), shape: shapeBorder(source, [...key, 'shape']) ?? const Border(), ); default: final ArgumentDecoder<Decoration?>? decoder = decorationDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [decoration]. static final Map<String, ArgumentDecoder<Decoration?>> decorationDecoders = <String, ArgumentDecoder<Decoration?>>{}; /// Returns a [DecorationImage] from the specified map. /// /// The [DecorationImage.image] is determined by interpreting the same key as /// per [imageProvider]. If that method returns null, then this returns null /// also. Otherwise, the return value is used as the provider and additional /// keys map to the identically-named properties of [DecorationImage]: /// `onError` (must be an event handler; the payload map is augmented by an /// `exception` key that contains the text serialization of the exception and /// a `stackTrace` key that contains the stack trace, also as a string), /// `colorFilter` ([colorFilter]), `fit` ([enumValue] of [BoxFit]), `alignment` /// ([alignment], defaults to [Alignment.center]), `centerSlice` ([rect]), /// `repeat` ([enumValue] of [ImageRepeat], defaults to [ImageRepeat.noRepeat]), /// `matchTextDirection` (boolean, defaults to false). static DecorationImage? decorationImage(DataSource source, List<Object> key) { final ImageProvider? provider = imageProvider(source, key); if (provider == null) { return null; } return DecorationImage( image: provider, onError: (Object exception, StackTrace? stackTrace) { final VoidCallback? handler = source.voidHandler([...key, 'onError'], { 'exception': exception.toString(), 'stackTrack': stackTrace.toString() }); if (handler != null) { handler(); } }, colorFilter: colorFilter(source, [...key, 'colorFilter']), fit: enumValue<BoxFit>(BoxFit.values, source, [...key, 'fit']), alignment: alignment(source, [...key, 'alignment']) ?? Alignment.center, centerSlice: rect(source, [...key, 'centerSlice']), repeat: enumValue<ImageRepeat>(ImageRepeat.values, source, [...key, 'repeat']) ?? ImageRepeat.noRepeat, matchTextDirection: source.v<bool>([...key, 'matchTextDirection']) ?? false, ); } /// Returns a double from the specified double. /// /// Returns 0.0 if it's not a double. /// /// This is useful in situations where null is not acceptable, for example, /// when providing a decoder to [list]. Otherwise, prefer using [DataSource.v] /// directly. static double doubleOrZero(DataSource source, List<Object> key) { return source.v<double>(key) ?? 0.0; } /// Returns a [Duration] from the specified integer. /// /// If it's not an integer, the default obtained from /// [AnimationDefaults.durationOf] is used (which is why a [BuildContext] is /// required). static Duration duration(DataSource source, List<Object> key, BuildContext context) { final int? value = source.v<int>(key); if (value == null) { return AnimationDefaults.durationOf(context); } return Duration(milliseconds: value); } /// Returns an [EdgeInsetsDirectional] from the specified list. /// /// The list is a list of doubles. An empty or missing list results in a null /// return value. The list should have one through four items. Extra items are /// ignored. /// /// The values are interpreted as follows: /// /// * start: first value. /// * top: second value, defaulting to same as start. /// * end: third value, defaulting to same as start. /// * bottom: fourth value, defaulting to same as top. static EdgeInsetsGeometry? edgeInsets(DataSource source, List<Object> key) { final double? a = source.v<double>([...key, 0]); if (a == null) { return null; } final double? b = source.v<double>([...key, 1]); final double? c = source.v<double>([...key, 2]); final double? d = source.v<double>([...key, 3]); return EdgeInsetsDirectional.fromSTEB( a, b ?? a, c ?? a, d ?? b ?? a, ); } /// Returns one of the values of the specified enum `T`, from the specified string. /// /// The string must match the name of the enum value, excluding the enum type /// name (the part of its [toString] after the dot). /// /// The first argument must be the `values` list for that enum; this is the /// list of values that is searched. /// /// For example, `enumValue<TileMode>(TileMode.values, source, ['tileMode']) ?? /// TileMode.clamp` reads the `tileMode` key of `source`, and looks for the /// first match in [TileMode.values], defaulting to [TileMode.clamp] if /// nothing matches; thus, the string `mirror` would return [TileMode.mirror]. static T? enumValue<T>(List<T> values, DataSource source, List<Object> key) { final String? value = source.v<String>(key); if (value == null) { return null; } for (int index = 0; index < values.length; index += 1) { if (value == values[index].toString().split('.').last) { return values[index]; } } return null; } /// Returns a [FontFeature] from the specified map. /// /// The `feature` key is used as the font feature name (defaulting to the /// probably-useless private value "NONE"), and the `value` key is used as the /// value (defaulting to 1, which typically means "enabled"). /// /// As this never returns null, it is possible to use it with [list]. static FontFeature fontFeature(DataSource source, List<Object> key) { return FontFeature(source.v<String>([...key, 'feature']) ?? 'NONE', source.v<int>([...key, 'value']) ?? 1); } /// Returns a [Gradient] from the specified map. /// /// The `type` key specifies the kind of gradient. /// /// A type of `linear` creates a [LinearGradient] using the keys `begin` /// ([alignment], defaults to [Alignment.centerLeft]), `end` ([alignment], /// defaults to [Alignment.centerRight]), `colors` ([list] of [colorOrBlack], /// defaults to a two-element list with black and white), `stops` ([list] of /// [doubleOrZero]), and `tileMode` ([enumValue] of [TileMode], defaults to /// [TileMode.clamp]), these keys each corresponding to the properties of /// [BoxDecoration] with the same name. /// /// A type of `radial` creates a [RadialGradient] using the keys `center` /// ([alignment], defaults to [Alignment.center]), `radius' (double, defaults /// to 0.5), `colors` ([list] of [colorOrBlack], defaults to a two-element /// list with black and white), `stops` ([list] of [doubleOrZero]), `tileMode` /// ([enumValue] of [TileMode], defaults to [TileMode.clamp]), `focal` /// (([alignment]), and `focalRadius` (double, defaults to zero), these keys /// each corresponding to the properties of [BoxDecoration] with the same /// name. /// /// A type of `linear` creates a [LinearGradient] using the keys `center` /// ([alignment], defaults to [Alignment.center]), `startAngle` (double, /// defaults to 0.0), `endAngle` (double, defaults to 2π), `colors` ([list] of /// [colorOrBlack], defaults to a two-element list with black and white), /// `stops` ([list] of [doubleOrZero]), and `tileMode` ([enumValue] of [TileMode], /// defaults to [TileMode.clamp]), these keys each corresponding to the /// properties of [BoxDecoration] with the same name. /// /// The `transform` property of these gradient classes is not supported. // TODO(ianh): https://github.com/flutter/flutter/issues/87208 /// /// If the type is none of these, but is not null, then the type is looked up /// in [gradientDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static Gradient? gradient(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'linear': return LinearGradient( begin: alignment(source, [...key, 'begin']) ?? Alignment.centerLeft, end: alignment(source, [...key, 'end']) ?? Alignment.centerRight, colors: list<Color>(source, [...key, 'colors'], colorOrBlack) ?? const <Color>[Color(0xFF000000), Color(0xFFFFFFFF)], stops: list<double>(source, [...key, 'stops'], doubleOrZero), tileMode: enumValue<TileMode>(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 ); case 'radial': return RadialGradient( center: alignment(source, [...key, 'center']) ?? Alignment.center, radius: source.v<double>([...key, 'radius']) ?? 0.5, colors: list<Color>(source, [...key, 'colors'], colorOrBlack) ?? const <Color>[Color(0xFF000000), Color(0xFFFFFFFF)], stops: list<double>(source, [...key, 'stops'], doubleOrZero), tileMode: enumValue<TileMode>(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, focal: alignment(source, [...key, 'focal']), focalRadius: source.v<double>([...key, 'focalRadius']) ?? 0.0, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 ); case 'sweep': return SweepGradient( center: alignment(source, [...key, 'center']) ?? Alignment.center, startAngle: source.v<double>([...key, 'startAngle']) ?? 0.0, endAngle: source.v<double>([...key, 'endAngle']) ?? math.pi * 2, colors: list<Color>(source, [...key, 'colors'], colorOrBlack) ?? const <Color>[Color(0xFF000000), Color(0xFFFFFFFF)], stops: list<double>(source, [...key, 'stops'], doubleOrZero), tileMode: enumValue<TileMode>(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 ); default: final ArgumentDecoder<Gradient?>? decoder = gradientDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [gradient]. static final Map<String, ArgumentDecoder<Gradient?>> gradientDecoders = <String, ArgumentDecoder<Gradient?>>{}; /// Returns a [SliverGridDelegate] from the specified map. /// /// The `type` key specifies the kind of grid delegate. /// /// A type of `fixedCrossAxisCount` creates a /// [SliverGridDelegateWithFixedCrossAxisCount] using the keys /// `crossAxisCount`, `mainAxisSpacing`, `crossAxisSpacing`, /// `childAspectRatio`, and `mainAxisExtent`. /// /// A type of `maxCrossAxisExtent` creates a /// [SliverGridDelegateWithMaxCrossAxisExtent] using the keys /// maxCrossAxisExtent:`, `mainAxisSpacing`, `crossAxisSpacing`, /// `childAspectRatio`, and `mainAxisExtent`. /// /// The types (int or double) and defaults for these keys match the /// identically named arguments to the default constructors of those classes. /// /// If the type is none of these, but is not null, then the type is looked up /// in [gridDelegateDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static SliverGridDelegate? gridDelegate(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'fixedCrossAxisCount': return SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: source.v<int>([...key, 'crossAxisCount']) ?? 2, mainAxisSpacing: source.v<double>([...key, 'mainAxisSpacing']) ?? 0.0, crossAxisSpacing: source.v<double>([...key, 'crossAxisSpacing']) ?? 0.0, childAspectRatio: source.v<double>([...key, 'childAspectRatio']) ?? 1.0, mainAxisExtent: source.v<double>([...key, 'mainAxisExtent']), ); case 'maxCrossAxisExtent': return SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: source.v<double>([...key, 'maxCrossAxisExtent']) ?? 100.0, mainAxisSpacing: source.v<double>([...key, 'mainAxisSpacing']) ?? 0.0, crossAxisSpacing: source.v<double>([...key, 'crossAxisSpacing']) ?? 0.0, childAspectRatio: source.v<double>([...key, 'childAspectRatio']) ?? 1.0, mainAxisExtent: source.v<double>([...key, 'mainAxisExtent']), ); default: final ArgumentDecoder<SliverGridDelegate?>? decoder = gridDelegateDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [gridDelegate]. static final Map<String, ArgumentDecoder<SliverGridDelegate?>> gridDelegateDecoders = <String, ArgumentDecoder<SliverGridDelegate?>>{}; /// Returns an [IconData] from the specified map. /// /// If the map does not have an `icon` key that is an integer, returns null. /// /// Otherwise, returns an [IconData] with the [IconData.codePoint] set to the /// integer from the `icon` key, the [IconData.fontFamily] set to the string /// from the `fontFamily` key, and the [IconData.matchTextDirection] set to /// the boolean from the `matchTextDirection` key (defaulting to false). /// /// For Material Design icons (those from the [Icons] class), the code point /// can be obtained from the documentation for the icon, and the font family /// is `MaterialIcons`. For example, [Icons.chalet] would correspond to /// `{ icon: 0xe14f, fontFamily: 'MaterialIcons' }`. /// /// When building the release build of an application that uses the RFW /// package, because this method creates non-const [IconData] objects /// dynamically, the `--no-tree-shake-icons` option must be used. static IconData? iconData(DataSource source, List<Object> key) { final int? icon = source.v<int>([...key, 'icon']); if (icon == null) { return null; } return IconData( icon, fontFamily: source.v<String>([...key, 'fontFamily']), matchTextDirection: source.v<bool>([...key, 'matchTextDirection']) ?? false, ); } /// Returns an [IconThemeData] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [IconThemeData] is created from /// the following keys: 'color` ([color]), `opacity` (double), `size` /// (double). static IconThemeData? iconThemeData(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return IconThemeData( color: color(source, [...key, 'color']), opacity: source.v<double>([...key, 'opacity']), size: source.v<double>([...key, 'size']), ); } /// Returns an [ImageProvider] from the specifed map. /// /// The `source` key of the specified map is controlling. It must be a string. /// If its value is one of the keys in [imageProviderDecoders], then the /// relevant decoder is invoked and its return value is used (even if it is /// null). /// /// Otherwise, if the `source` key gives an absolute URL (one with a scheme), /// then a [NetworkImage] with that URL is returned. Its scale is given by the /// `scale` key (double, defaults to 1.0). /// /// Otherwise, if the `source` key gives a relative URL (i.e. it can be parsed /// as a URL and has no scheme), an [AssetImage] with the name given by the /// `source` key is returned. /// /// Otherwise, if there is no `source` key in the map, or if that cannot be /// parsed as a URL (absolute or relative), null is returned. static ImageProvider? imageProvider(DataSource source, List<Object> key) { final String? image = source.v<String>([...key, 'source']); if (image == null) { return null; } if (imageProviderDecoders.containsKey(image)) { return imageProviderDecoders[image]!(source, key); } final Uri? imageUrl = Uri.tryParse(image); if (imageUrl == null) { return null; } if (!imageUrl.hasScheme) { return AssetImage(image); } return NetworkImage(image, scale: source.v<double>([...key, 'scale']) ?? 1.0); } /// Extension mechanism for [imageProvider]. static final Map<String, ArgumentDecoder<ImageProvider?>> imageProviderDecoders = <String, ArgumentDecoder<ImageProvider?>>{}; /// Returns a [List] of `T` values from the specified list, using the given /// `decoder` to parse each value. /// /// If the list is absent _or empty_, returns null (not an empty list). /// /// Otherwise, returns a list with as many items as the specified list, with /// each entry in the list decoded using `decoder`. /// /// If `T` is non-nullable, the decoder must also be non-nullable. static List<T>? list<T>(DataSource source, List<Object> key, ArgumentDecoder<T> decoder) { final int count = source.length(key); if (count == 0) { return null; } return List<T>.generate(count, (int index) { return decoder(source, [...key, index]); }); } /// Returns a [Locale] from the specified string. /// /// The string is split on hyphens ("-"). /// /// If the string is null, returns null. /// /// If there is no hyphen in the list, uses the one-argument form of [ /// Locale], passing the whole string. /// /// If there is one hyphen in the list, uses the two-argument form of [ /// Locale], passing the parts before and after the hyphen respectively. /// /// If there are two or more hyphens, uses the [Locale.fromSubtags] /// constructor. static Locale? locale(DataSource source, List<Object> key) { final String? value = source.v<String>(key); if (value == null) { return null; } final List<String> subtags = value.split('-'); if (subtags.isEmpty) { return null; } if (subtags.length == 1) { return Locale(value); } if (subtags.length == 2) { return Locale(subtags[0], subtags[1]); } // TODO(ianh): verify this is correct (I tried looking up the Unicode spec but it was... confusing) return Locale.fromSubtags(languageCode: subtags[0], scriptCode: subtags[1], countryCode: subtags[2]); } /// Returns a list of 16 doubles from the specified list. /// /// If the list is missing or has fewer than 16 entries, returns null. /// /// Otherwise, returns a list of 16 entries, corresponding to the first 16 /// entries of the specified list, with any non-double values replaced by 0.0. static Matrix4? matrix(DataSource source, List<Object> key) { final double? arg15 = source.v<double>([...key, 15]); if (arg15 == null) { return null; } return Matrix4( source.v<double>([...key, 0]) ?? 0.0, source.v<double>([...key, 1]) ?? 0.0, source.v<double>([...key, 2]) ?? 0.0, source.v<double>([...key, 3]) ?? 0.0, source.v<double>([...key, 4]) ?? 0.0, source.v<double>([...key, 5]) ?? 0.0, source.v<double>([...key, 6]) ?? 0.0, source.v<double>([...key, 7]) ?? 0.0, source.v<double>([...key, 8]) ?? 0.0, source.v<double>([...key, 9]) ?? 0.0, source.v<double>([...key, 10]) ?? 0.0, source.v<double>([...key, 11]) ?? 0.0, source.v<double>([...key, 12]) ?? 0.0, source.v<double>([...key, 13]) ?? 0.0, source.v<double>([...key, 14]) ?? 0.0, arg15, ); } /// Returns a [MaskFilter] from the specified map. /// /// The `type` key specifies the kind of mask filter. /// /// A type of `blur` creates a [MaskFilter.blur]. The `style` key ([enumValue] of /// [BlurStyle], defaults to [BlurStyle.normal]) is used as the blur style, /// and the `sigma` key (double, defaults to 1.0) is used as the blur sigma. /// /// If the type is none of these, but is not null, then the type is looked up /// in [maskFilterDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static MaskFilter? maskFilter(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'blur': return MaskFilter.blur( enumValue<BlurStyle>(BlurStyle.values, source, [...key, 'style']) ?? BlurStyle.normal, source.v<double>([...key, 'sigma']) ?? 1.0, ); default: final ArgumentDecoder<MaskFilter?>? decoder = maskFilterDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [maskFilter]. static final Map<String, ArgumentDecoder<MaskFilter?>> maskFilterDecoders = <String, ArgumentDecoder<MaskFilter?>>{}; /// Returns an [Offset] from the specified map. /// /// The map must have an `x` key and a `y` key, doubles. static Offset? offset(DataSource source, List<Object> key) { final double? x = source.v<double>([...key, 'x']); if (x == null) { return null; } final double? y = source.v<double>([...key, 'y']); if (y == null) { return null; } return Offset(x, y); } /// Returns a [Paint] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), a new [Paint] is created and its /// properties are set according to the identically-named properties of the /// map, as follows: /// /// * `blendMode`: [enumValue] of [BlendMode]. /// * `color`: [color]. /// * `colorFilter`: [colorFilter]. /// * `filterQuality`: [enumValue] of [FilterQuality]. // * `imageFilter`: [imageFilter]. // * `invertColors`: boolean. /// * `isAntiAlias`: boolean. /// * `maskFilter`: [maskFilter]. /// * `shader`: [shader]. // * `strokeCap`: [enumValue] of [StrokeCap]. // * `strokeJoin`: [enumValue] of [StrokeJoin]. // * `strokeMiterLimit`: double. // * `strokeWidth`: double. // * `style`: [enumValue] of [PaintingStyle]. /// /// (Some values are not supported, because there is no way for them to be /// used currently in RFW contexts.) static Paint? paint(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } final Paint result = Paint(); final BlendMode? paintBlendMode = enumValue<BlendMode>(BlendMode.values, source, [...key, 'blendMode']); if (paintBlendMode != null) { result.blendMode = paintBlendMode; } final Color? paintColor = color(source, [...key, 'color']); if (paintColor != null) { result.color = paintColor; } final ColorFilter? paintColorFilter = colorFilter(source, [...key, 'colorFilter']); if (paintColorFilter != null) { result.colorFilter = paintColorFilter; } final FilterQuality? paintFilterQuality = enumValue<FilterQuality>(FilterQuality.values, source, [...key, 'filterQuality']); if (paintFilterQuality != null) { result.filterQuality = paintFilterQuality; } // final ImageFilter? paintImageFilter = imageFilter(source, [...key, 'imageFilter']); // if (paintImageFilter != null) { // result.imageFilter = paintImageFilter; // } // final bool? paintInvertColors = source.v<bool>([...key, 'invertColors']); // if (paintInvertColors != null) { // result.invertColors = paintInvertColors; // } final bool? paintIsAntiAlias = source.v<bool>([...key, 'isAntiAlias']); if (paintIsAntiAlias != null) { result.isAntiAlias = paintIsAntiAlias; } final MaskFilter? paintMaskFilter = maskFilter(source, [...key, 'maskFilter']); if (paintMaskFilter != null) { result.maskFilter = paintMaskFilter; } final Shader? paintShader = shader(source, [...key, 'shader']); if (paintShader != null) { result.shader = paintShader; } // final StrokeCap? paintStrokeCap = enumValue<StrokeCap>(StrokeCap.values, source, [...key, 'strokeCap']), // if (paintStrokeCap != null) { // result.strokeCap = paintStrokeCap; // } // final StrokeJoin? paintStrokeJoin = enumValue<StrokeJoin>(StrokeJoin.values, source, [...key, 'strokeJoin']), // if (paintStrokeJoin != null) { // result.strokeJoin = paintStrokeJoin; // } // final double paintStrokeMiterLimit? = source.v<double>([...key, 'strokeMiterLimit']), // if (paintStrokeMiterLimit != null) { // result.strokeMiterLimit = paintStrokeMiterLimit; // } // final double paintStrokeWidth? = source.v<double>([...key, 'strokeWidth']), // if (paintStrokeWidth != null) { // result.strokeWidth = paintStrokeWidth; // } // final PaintingStyle? paintStyle = enumValue<PaintingStyle>(PaintingStyle.values, source, [...key, 'style']), // if (paintStyle != null) { // result.style = paintStyle; // } return result; } /// Returns a [Radius] from the specified map. /// /// The map must have an `x` value corresponding to [Radius.x], and may have a /// `y` value corresponding to [Radius.y]. /// /// If the map only has an `x` key, the `y` value is assumed to be the same /// (as in [Radius.circular]). /// /// If the `x` key is absent, the returned value is null. static Radius? radius(DataSource source, List<Object> key) { final double? x = source.v<double>([...key, 'x']); if (x == null) { return null; } final double y = source.v<double>([...key, 'y']) ?? x; return Radius.elliptical(x, y); } /// Returns a [Rect] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise, returns a [Rect.fromLTWH] whose x, y, width, and height /// components are determined from the `x`, `y`, `w`, and `h` properties of /// the map, with missing (or non-double) values replaced by zeros. static Rect? rect(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } final double x = source.v<double>([...key, 'x']) ?? 0.0; final double y = source.v<double>([...key, 'y']) ?? 0.0; final double w = source.v<double>([...key, 'w']) ?? 0.0; final double h = source.v<double>([...key, 'h']) ?? 0.0; return Rect.fromLTWH(x, y, w, h); } /// Returns a [ShapeBorder] from the specified map or list. /// /// If the key identifies a list, then each entry in the list is decoded by /// recursively invoking [shapeBorder], and the result is the combination of /// those [ShapeBorder] values as obtained using the [ShapeBorder.+] operator. /// /// Otherwise, if the key identifies a map with a `type` value, the map is /// interpreted according to the `type` as follows: /// /// * `box`: the map's `sides` key is interpreted as a list by [border] and /// the resulting [BoxBorder] (actually, [BorderDirectional]) is returned. /// /// * `beveled`: a [BeveledRectangleBorder] is returned; the `side` key is /// interpreted by [borderSide] to set the [BeveledRectangleBorder.side] /// (default of [BorderSide.none)), and the `borderRadius` key is /// interpreted by [borderRadius] to set the /// [BeveledRectangleBorder.borderRadius] (default [BorderRadius.zero]). /// /// * `circle`: a [CircleBorder] is returned; the `side` key is interpreted /// by [borderSide] to set the [BeveledRectangleBorder.side] (default of /// [BorderSide.none)). /// /// * `continuous`: a [ContinuousRectangleBorder] is returned; the `side` key /// is interpreted by [borderSide] to set the [BeveledRectangleBorder.side] /// (default of [BorderSide.none)), and the `borderRadius` key is /// interpreted by [borderRadius] to set the /// [BeveledRectangleBorder.borderRadius] (default [BorderRadius.zero]). /// /// * `rounded`: a [RoundedRectangleBorder] is returned; the `side` key is /// interpreted by [borderSide] to set the [BeveledRectangleBorder.side] /// (default of [BorderSide.none)), and the `borderRadius` key is /// interpreted by [borderRadius] to set the /// [BeveledRectangleBorder.borderRadius] (default [BorderRadius.zero]). /// /// * `stadium`: a [StadiumBorder] is returned; the `side` key is interpreted /// by [borderSide] to set the [BeveledRectangleBorder.side] (default of /// [BorderSide.none)). /// /// If the type is none of these, then the type is looked up in /// [shapeBorderDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, if type is null or is not found in [shapeBorderDecoders], returns null. static ShapeBorder? shapeBorder(DataSource source, List<Object> key) { final List<ShapeBorder?>? shapes = list<ShapeBorder?>(source, key, shapeBorder); if (shapes != null) { return shapes.where((ShapeBorder? a) => a != null).reduce((ShapeBorder? a, ShapeBorder? b) => a! + b!); } final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'box': return border(source, [...key, 'sides']) ?? const Border(); case 'beveled': return BeveledRectangleBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, borderRadius: borderRadius(source, [...key, 'borderRadius']) ?? BorderRadius.zero, ); case 'circle': return CircleBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, ); case 'continuous': return ContinuousRectangleBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, borderRadius: borderRadius(source, [...key, 'borderRadius']) ?? BorderRadius.zero, ); case 'rounded': return RoundedRectangleBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, borderRadius: borderRadius(source, [...key, 'borderRadius']) ?? BorderRadius.zero, ); case 'stadium': return StadiumBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, ); default: final ArgumentDecoder<ShapeBorder>? decoder = shapeBorderDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [shapeBorder]. static final Map<String, ArgumentDecoder<ShapeBorder>> shapeBorderDecoders = <String, ArgumentDecoder<ShapeBorder>>{}; /// Returns a [Shader] based on the specified map. /// /// The `type` key specifies the kind of shader. /// /// A type of `linear`, `radial`, or `sweep` is interpreted as described by /// [gradient]; then, the gradient is compiled to a shader by applying the /// `rect` (interpreted by [rect]) and `textDirection` (interpreted as an /// [enumValue] of [TextDirection]) using the [Gradient.createShader] method. /// /// If the type is none of these, but is not null, then the type is looked up /// in [shaderDecoders], and if an entry is found, this method defers to /// that callback. /// /// Otherwise, returns null. static Shader? shader(DataSource source, List<Object> key) { final String? type = source.v<String>([...key, 'type']); switch (type) { case null: return null; case 'linear': case 'radial': case 'sweep': return gradient(source, key)!.createShader( rect(source, [...key, 'rect']) ?? Rect.zero, textDirection: enumValue<TextDirection>(TextDirection.values, source, ['textDirection']) ?? TextDirection.ltr, ); default: final ArgumentDecoder<Shader?>? decoder = shaderDecoders[type]; if (decoder == null) { return null; } return decoder(source, key); } } /// Extension mechanism for [shader]. static final Map<String, ArgumentDecoder<Shader?>> shaderDecoders = <String, ArgumentDecoder<Shader?>>{}; /// Returns a string from the specified string. /// /// Returns the empty string if it's not a string. /// /// This is useful in situations where null is not acceptable, for example, /// when providing a decoder to [list]. Otherwise, prefer using [DataSource.v] /// directly. static String string(DataSource source, List<Object> key) { return source.v<String>(key) ?? ''; } /// Returns a [StrutStyle] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [StrutStyle] is created from the /// following keys: 'fontFamily` (string), `fontFamilyFallback` ([list] of /// [string]), `fontSize` (double), `height` (double), `leadingDistribution` /// ([enumValue] of [TextLeadingDistribution]), `leading` (double), /// `fontWeight` ([enumValue] of [FontWeight]), `fontStyle` ([enumValue] of /// [FontStyle]), `forceStrutHeight` (boolean). static StrutStyle? strutStyle(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return StrutStyle( fontFamily: source.v<String>([...key, 'fontFamily']), fontFamilyFallback: list<String>(source, [...key, 'fontFamilyFallback'], string), fontSize: source.v<double>([...key, 'fontSize']), height: source.v<double>([...key, 'height']), leadingDistribution: enumValue<TextLeadingDistribution>(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']), leading: source.v<double>([...key, 'leading']), fontWeight: enumValue<FontWeight>(FontWeight.values, source, [...key, 'fontWeight']), fontStyle: enumValue<FontStyle>(FontStyle.values, source, [...key, 'fontStyle']), forceStrutHeight: source.v<bool>([...key, 'forceStrutHeight']), ); } /// Returns a [TextHeightBehavior] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [TextHeightBehavior] is created /// from the following keys: 'applyHeightToFirstAscent` (boolean; defaults to /// true), `applyHeightToLastDescent` (boolean, defaults to true), and /// `leadingDistribution` ([enumValue] of [TextLeadingDistribution], deafults /// to [TextLeadingDistribution.proportional]). static TextHeightBehavior? textHeightBehavior(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return TextHeightBehavior( applyHeightToFirstAscent: source.v<bool>([...key, 'applyHeightToFirstAscent']) ?? true, applyHeightToLastDescent: source.v<bool>([...key, 'applyHeightToLastDescent']) ?? true, leadingDistribution: enumValue<TextLeadingDistribution>(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']) ?? TextLeadingDistribution.proportional, ); } /// Returns a [TextDecoration] from the specified list or string. /// /// If the key identifies a list, then each entry in the list is decoded by /// recursively invoking [textDecoration], and the result is the combination /// of those [TextDecoration] values as obtained using /// [TextDecoration.combine]. /// /// Otherwise, if the key identifies a string, then the value `lineThrough` is /// mapped to [TextDecoration.lineThrough], `overline` to /// [TextDecoration.overline], and `underline` to [TextDecoration.underline]. /// Other values (and the abscence of a value) are interpreted as /// [TextDecoration.none]. static TextDecoration textDecoration(DataSource source, List<Object> key) { final List<TextDecoration>? decorations = list<TextDecoration>(source, key, textDecoration); if (decorations != null) { return TextDecoration.combine(decorations); } switch (source.v<String>([...key])) { case 'lineThrough': return TextDecoration.lineThrough; case 'overline': return TextDecoration.overline; case 'underline': return TextDecoration.underline; default: return TextDecoration.none; } } /// Returns a [TextStyle] from the specified map. /// /// If the map is absent, returns null. /// /// Otherwise (even if it has no keys), the [TextStyle] is created from the /// following keys: `color` ([color]), `backgroundColor` ([color]), `fontSize` /// (double), `fontWeight` ([enumValue] of [FontWeight]), `fontStyle` /// ([enumValue] of [FontStyle]), `letterSpacing` (double), `wordSpacing` /// (double), `textBaseline` ([enumValue] of [TextBaseline]), `height` /// (double), `leadingDistribution` ([enumValue] of /// [TextLeadingDistribution]), `locale` ([locale]), `foreground` ([paint]), /// `background` ([paint]), `shadows` ([list] of [boxShadow]s), `fontFeatures` /// ([list] of [fontFeature]s), `decoration` ([textDecoration]), /// `decorationColor` ([color]), `decorationStyle` ([enumValue] of /// [TextDecorationStyle]), `decorationThickness` (double), 'fontFamily` /// (string), `fontFamilyFallback` ([list] of [string]), and `overflow` /// ([enumValue] of [TextOverflow]). static TextStyle? textStyle(DataSource source, List<Object> key) { if (!source.isMap(key)) { return null; } return TextStyle( color: color(source, [...key, 'color']), backgroundColor: color(source, [...key, 'backgroundColor']), fontSize: source.v<double>([...key, 'fontSize']), fontWeight: enumValue<FontWeight>(FontWeight.values, source, [...key, 'fontWeight']), fontStyle: enumValue<FontStyle>(FontStyle.values, source, [...key, 'fontStyle']), letterSpacing: source.v<double>([...key, 'letterSpacing']), wordSpacing: source.v<double>([...key, 'wordSpacing']), textBaseline: enumValue<TextBaseline>(TextBaseline.values, source, ['textBaseline']), height: source.v<double>([...key, 'height']), leadingDistribution: enumValue<TextLeadingDistribution>(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']), locale: locale(source, [...key, 'locale']), foreground: paint(source, [...key, 'foreground']), background: paint(source, [...key, 'background']), shadows: list<BoxShadow>(source, [...key, 'shadows'], boxShadow), fontFeatures: list<FontFeature>(source, [...key, 'fontFeatures'], fontFeature), decoration: textDecoration(source, [...key, 'decoration']), decorationColor: color(source, [...key, 'decorationColor']), decorationStyle: enumValue<TextDecorationStyle>(TextDecorationStyle.values, source, [...key, 'decorationStyle']), decorationThickness: source.v<double>([...key, 'decorationThickness']), fontFamily: source.v<String>([...key, 'fontFamily']), fontFamilyFallback: list<String>(source, [...key, 'fontFamilyFallback'], string), overflow: enumValue<TextOverflow>(TextOverflow.values, source, ['overflow']), ); } /// Returns a [VisualDensity] from the specified string or map. /// /// If the specified value is a string, then it is interpreted as follows: /// /// * `adaptivePlatformDensity`: returns /// [VisualDensity.adaptivePlatformDensity] (which varies by platform). /// * `comfortable`: returns [VisualDensity.comfortable]. /// * `compact`: returns [VisualDensity.compact]. /// * `standard`: returns [VisualDensity.standard]. /// /// Otherwise, if the specified value is a map, then the keys `horizontal` and /// `vertical` (doubles) are used to create a custom [VisualDensity]. The /// specified values must be in the range given by /// [VisualDensity.minimumDensity] to [VisualDensity.maximumDensity]. Missing /// values are interpreted as zero. static VisualDensity? visualDensity(DataSource source, List<Object> key) { final String? type = source.v<String>(key); switch (type) { case 'adaptivePlatformDensity': return VisualDensity.adaptivePlatformDensity; case 'comfortable': return VisualDensity.comfortable; case 'compact': return VisualDensity.compact; case 'standard': return VisualDensity.standard; default: if (!source.isMap(key)) { return null; } return VisualDensity( horizontal: source.v<double>([...key, 'horizontal']) ?? 0.0, vertical: source.v<double>([...key, 'vertical']) ?? 0.0, ); } } }
packages/packages/rfw/lib/src/flutter/argument_decoders.dart/0
{ "file_path": "packages/packages/rfw/lib/src/flutter/argument_decoders.dart", "repo_id": "packages", "token_count": 21603 }
1,043
// 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. // ignore_for_file: use_raw_strings, avoid_escaping_inner_quotes import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart'; import 'package:rfw/rfw.dart'; const String sourceFile = ''' import core; widget verify { state: true } = switch args.value.c.0 { 0xDD: ColoredBox(color: 0xFF0D0D0D), default: ColoredBox(color: args.value), }; widget remote = SizedBox(child: args.corn.0); widget root = remote( corn: [ ...for v in data.list: verify(value: v), ], );'''; void main() { testWidgets('parseLibraryFile: source location tracking', (WidgetTester tester) async { final RemoteWidgetLibrary test = parseLibraryFile(sourceFile); expect(test.widgets.first.source, isNull); }); testWidgets('parseLibraryFile: source location tracking', (WidgetTester tester) async { String extract(BlobNode node) => (node.source!.start.source as String).substring(node.source!.start.offset, node.source!.end.offset); // We use the actual source text as the sourceIdentifier to make it trivial to find the source contents. // In normal operation, the sourceIdentifier would be the file name or some similar object. final RemoteWidgetLibrary test = parseLibraryFile(sourceFile, sourceIdentifier: sourceFile); expect(extract(test.widgets.first), ''' widget verify { state: true } = switch args.value.c.0 { 0xDD: ColoredBox(color: 0xFF0D0D0D), default: ColoredBox(color: args.value), };'''); expect(extract((test.widgets.first.root as Switch).input as ArgsReference), 'args.value.c.0'); }); testWidgets('Runtime: source location tracking', (WidgetTester tester) async { String extract(BlobNode node) { if (node.source == null) { printOnFailure('This node had no source information: ${node.runtimeType} $node'); } return (node.source!.start.source as String).substring(node.source!.start.offset, node.source!.end.offset); } final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) // We use the actual source text as the sourceIdentifier to make it trivial to find the source contents. // In normal operation, the sourceIdentifier would be the file name or some similar object. ..update(const LibraryName(<String>['test']), parseLibraryFile(sourceFile, sourceIdentifier: sourceFile)); final DynamicContent data = DynamicContent(<String, Object?>{ 'list': <Object?>[ <String, Object?>{ 'a': <String, Object?>{ 'b': 0xEE }, 'c': <Object?>[ 0xDD ], }, ], }); await tester.pumpWidget( RemoteWidget( runtime: runtime, data: data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { fail('unexpected event $eventName'); }, ), ); expect(extract(Runtime.blobNodeFor(tester.firstElement(find.byType(ColoredBox)))!), 'ColoredBox(color: 0xFF0D0D0D)'); }); }
packages/packages/rfw/test/source_locations_test.dart/0
{ "file_path": "packages/packages/rfw/test/source_locations_test.dart", "repo_id": "packages", "token_count": 1167 }
1,044
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/shared_preferences/shared_preferences/example/android/gradle.properties/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,045
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk version to 34. ## 2.2.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Deletes deprecated splash screen meta-data element. ## 2.2.0 * Adds `clearWithParameters` and `getAllWithParameters` methods. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.1.4 * Fixes compatibility with AGP versions older than 4.2. ## 2.1.3 * Adds a namespace for compatibility with AGP 8.0. ## 2.1.2 * Sets the required Java compile version to 1.8 for new features used in 2.1.1. ## 2.1.1 * Updates minimum Flutter version to 3.0. * Converts implementation to Pigeon. ## 2.1.0 * Adds `getAllWithPrefix` and `clearWithPrefix` methods. ## 2.0.17 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. * Updates compileSdkVersion to 33. ## 2.0.16 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.0.15 * Updates code for stricter lint checks. ## 2.0.14 * Fixes typo in `SharedPreferencesAndroid` docs. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.0.13 * Updates gradle to 7.2.2. * Updates minimum Flutter version to 2.10. ## 2.0.12 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.0.11 * Switches to an in-package method channel implementation. ## 2.0.10 * Removes dependency on `meta`. ## 2.0.9 * Updates compileSdkVersion to 31. ## 2.0.8 * Split from `shared_preferences` as a federated implementation.
packages/packages/shared_preferences/shared_preferences_android/CHANGELOG.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/CHANGELOG.md", "repo_id": "packages", "token_count": 580 }
1,046
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #endif public class SharedPreferencesPlugin: NSObject, FlutterPlugin, UserDefaultsApi { public static func register(with registrar: FlutterPluginRegistrar) { let instance = SharedPreferencesPlugin() // Workaround for https://github.com/flutter/flutter/issues/118103. #if os(iOS) let messenger = registrar.messenger() #else let messenger = registrar.messenger #endif UserDefaultsApiSetup.setUp(binaryMessenger: messenger, api: instance) } func getAll(prefix: String, allowList: [String]?) -> [String?: Any?] { return getAllPrefs(prefix: prefix, allowList: allowList) } func setBool(key: String, value: Bool) { UserDefaults.standard.set(value, forKey: key) } func setDouble(key: String, value: Double) { UserDefaults.standard.set(value, forKey: key) } func setValue(key: String, value: Any) { UserDefaults.standard.set(value, forKey: key) } func remove(key: String) { UserDefaults.standard.removeObject(forKey: key) } func clear(prefix: String, allowList: [String]?) -> Bool { let defaults = UserDefaults.standard for (key, _) in getAllPrefs(prefix: prefix, allowList: allowList) { defaults.removeObject(forKey: key) } return true } /// Returns all preferences stored with specified prefix. /// If [allowList] is included, only items included will be returned. func getAllPrefs(prefix: String, allowList: [String]?) -> [String: Any] { var filteredPrefs: [String: Any] = [:] var allowSet: Set<String>? if let allowList = allowList { allowSet = Set(allowList) } if let appDomain = Bundle.main.bundleIdentifier, let prefs = UserDefaults.standard.persistentDomain(forName: appDomain) { for (key, value) in prefs where (key.hasPrefix(prefix) && (allowSet == nil || allowSet!.contains(key))) { filteredPrefs[key] = value } } return filteredPrefs } }
packages/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/SharedPreferencesPlugin.swift/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/SharedPreferencesPlugin.swift", "repo_id": "packages", "token_count": 766 }
1,047
name: shared_preferences_foundation description: iOS and macOS implementation of the shared_preferences plugin. repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_foundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.3.5 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: shared_preferences platforms: ios: pluginClass: SharedPreferencesPlugin dartPluginClass: SharedPreferencesFoundation sharedDarwinSource: true macos: pluginClass: SharedPreferencesPlugin dartPluginClass: SharedPreferencesFoundation sharedDarwinSource: true dependencies: flutter: sdk: flutter shared_preferences_platform_interface: ^2.3.0 dev_dependencies: flutter_test: sdk: flutter pigeon: ^10.1.6 topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences_foundation/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/pubspec.yaml", "repo_id": "packages", "token_count": 377 }
1,048
// 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. /// Filter options used to get and clear preferences. class PreferencesFilter { /// Constructor. PreferencesFilter({ required this.prefix, this.allowList, }); /// A prefix to limit getting and clearing to only items that begin with /// this string. String prefix; /// A list of preference keys that will limit getting and clearing to only /// items included in this list. Set<String>? allowList; } /// Parameters for use in [getAll] methods. class GetAllParameters { /// Constructor. GetAllParameters({required this.filter}); /// Filter to limit which preferences are returned. PreferencesFilter filter; } /// Parameters for use in [clear] methods. class ClearParameters { /// Constructor. ClearParameters({required this.filter}); /// Filter to limit which preferences are cleared. PreferencesFilter filter; }
packages/packages/shared_preferences/shared_preferences_platform_interface/lib/types.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_platform_interface/lib/types.dart", "repo_id": "packages", "token_count": 261 }
1,049
name: shared_preferences_web description: Web platform implementation of shared_preferences repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.3.0 environment: sdk: ^3.3.0 flutter: ">=3.19.0" flutter: plugin: implements: shared_preferences platforms: web: pluginClass: SharedPreferencesPlugin fileName: shared_preferences_web.dart dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter shared_preferences_platform_interface: ^2.3.0 web: ^0.5.0 dev_dependencies: flutter_test: sdk: flutter topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences_web/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_web/pubspec.yaml", "repo_id": "packages", "token_count": 325 }
1,050
name: standard_message_codec description: An efficient and schemaless binary encoding format for Flutter and Dart. version: 0.0.1+4 repository: https://github.com/flutter/packages/tree/main/packages/standard_message_codec issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Astandard_message_codec environment: sdk: ^3.1.0 dev_dependencies: test: ^1.16.0 topics: - decode - encode - interop
packages/packages/standard_message_codec/pubspec.yaml/0
{ "file_path": "packages/packages/standard_message_codec/pubspec.yaml", "repo_id": "packages", "token_count": 160 }
1,051
#include "Generated.xcconfig"
packages/packages/two_dimensional_scrollables/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
1,052
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/two_dimensional_scrollables/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,053
// 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:url_launcher_android/src/messages.g.dart'; import 'package:url_launcher_android/url_launcher_android.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { late _FakeUrlLauncherApi api; setUp(() { api = _FakeUrlLauncherApi(); }); test('registers instance', () { UrlLauncherAndroid.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherAndroid>()); }); group('canLaunch', () { test('returns true', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool canLaunch = await launcher.canLaunch('http://example.com/'); expect(canLaunch, true); }); test('returns false', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool canLaunch = await launcher.canLaunch('unknown://scheme'); expect(canLaunch, false); }); test('checks a generic URL if an http URL returns false', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool canLaunch = await launcher .canLaunch('http://${_FakeUrlLauncherApi.specialHandlerDomain}'); expect(canLaunch, true); }); test('checks a generic URL if an https URL returns false', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool canLaunch = await launcher .canLaunch('https://${_FakeUrlLauncherApi.specialHandlerDomain}'); expect(canLaunch, true); }); }); group('legacy launch without webview', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(launched, true); expect(api.usedWebView, false); expect(api.passedWebViewOptions?.headers, isEmpty); }); test('passes headers', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{'key': 'value'}, ); expect(api.passedWebViewOptions?.headers.length, 1); expect(api.passedWebViewOptions?.headers['key'], 'value'); }); test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launch( 'https://noactivity', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>())); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launch( 'unknown://scheme', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); }); }); group('legacy launch with webview', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, false); expect(api.passedWebViewOptions?.enableDomStorage, false); expect(api.passedWebViewOptions?.enableJavaScript, false); expect(api.passedWebViewOptions?.headers, isEmpty); }); test('passes enableJavaScript to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: true, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(api.passedWebViewOptions?.enableJavaScript, true); }); test('passes enableDomStorage to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: true, universalLinksOnly: false, headers: const <String, String>{}, ); expect(api.passedWebViewOptions?.enableDomStorage, true); }); test('passes showTitle to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( 'http://example.com/', const LaunchOptions( browserConfiguration: InAppBrowserConfiguration( showTitle: true, ), ), ); expect(api.passedBrowserOptions?.showTitle, true); }); test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launch( 'https://noactivity', useSafariVC: false, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>())); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launch( 'unknown://scheme', useSafariVC: false, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); }); }); group('launch without webview', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( 'http://example.com/', const LaunchOptions(mode: PreferredLaunchMode.externalApplication), ); expect(launched, true); expect(api.usedWebView, false); expect(api.passedWebViewOptions?.headers, isEmpty); }); test('passes headers', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( 'http://example.com/', const LaunchOptions( mode: PreferredLaunchMode.externalApplication, webViewConfiguration: InAppWebViewConfiguration( headers: <String, String>{'key': 'value'})), ); expect(api.passedWebViewOptions?.headers.length, 1); expect(api.passedWebViewOptions?.headers['key'], 'value'); }); test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launchUrl('https://noactivity', const LaunchOptions()), throwsA(isA<PlatformException>())); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launchUrl('unknown://scheme', const LaunchOptions()), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); }); }); group('launch with webview', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl('http://example.com/', const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, false); expect(api.passedWebViewOptions?.enableDomStorage, true); expect(api.passedWebViewOptions?.enableJavaScript, true); expect(api.passedWebViewOptions?.headers, isEmpty); }); test('passes enableJavaScript to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( 'http://example.com/', const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, webViewConfiguration: InAppWebViewConfiguration(enableJavaScript: false))); expect(api.passedWebViewOptions?.enableJavaScript, false); }); test('passes enableDomStorage to webview', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( 'http://example.com/', const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, webViewConfiguration: InAppWebViewConfiguration(enableDomStorage: false))); expect(api.passedWebViewOptions?.enableDomStorage, false); }); test('passes through no-activity exception', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launchUrl('https://noactivity', const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA(isA<PlatformException>())); }); test('throws if there is no handling activity', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); await expectLater( launcher.launchUrl('unknown://scheme', const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'ACTIVITY_NOT_FOUND'))); }); }); group('launch with custom tab', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl('http://example.com/', const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView)); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); }); }); group('launch with platform default', () { test('uses custom tabs for http', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( 'http://example.com/', const LaunchOptions()); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); }); test('uses custom tabs for https', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( 'https://example.com/', const LaunchOptions()); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); }); test('uses external for other schemes', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( 'supportedcustomscheme://example.com/', const LaunchOptions()); expect(launched, true); expect(api.usedWebView, false); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns true for in app web view', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view when available', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = true; expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), true); }); test('returns false for in app browser view when not available', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = false; expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); }); }); group('supportsCloseForMode', () { test('returns true for in app web view', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), true); }); test('returns false for other modes', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(api: api); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.externalApplication), false); expect( await launcher.supportsCloseForMode( PreferredLaunchMode.externalNonBrowserApplication), false); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), false); }); }); } /// A fake implementation of the host API that reacts to specific schemes. /// /// See _launch for the behaviors. class _FakeUrlLauncherApi implements UrlLauncherApi { bool hasCustomTabSupport = true; WebViewOptions? passedWebViewOptions; BrowserOptions? passedBrowserOptions; bool? usedWebView; bool? allowedCustomTab; bool? closed; /// A domain that will be treated as having no handler, even for http(s). static String specialHandlerDomain = 'special.handler.domain'; @override Future<bool> canLaunchUrl(String url) async { return _launch(url); } @override Future<bool> launchUrl(String url, Map<String?, String?> headers) async { passedWebViewOptions = WebViewOptions( enableJavaScript: false, enableDomStorage: false, headers: headers, ); usedWebView = false; return _launch(url); } @override Future<void> closeWebView() async { closed = true; } @override Future<bool> openUrlInApp( String url, bool allowCustomTab, WebViewOptions webViewOptions, BrowserOptions browserOptions, ) async { passedWebViewOptions = webViewOptions; passedBrowserOptions = browserOptions; usedWebView = true; allowedCustomTab = allowCustomTab; return _launch(url); } @override Future<bool> supportsCustomTabs() async { return hasCustomTabSupport; } bool _launch(String url) { final String scheme = url.split(':')[0]; switch (scheme) { case 'http': case 'https': case 'supportedcustomscheme': if (url.endsWith('noactivity')) { throw PlatformException(code: 'NO_ACTIVITY'); } return !url.contains(specialHandlerDomain); default: return false; } } }
packages/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart", "repo_id": "packages", "token_count": 6412 }
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. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func isNullish(_ value: Any?) -> Bool { return value is NSNull || value == nil } private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } /// Possible outcomes of launching a URL. enum LaunchResult: Int { /// The URL was successfully launched (or could be, for `canLaunchUrl`). case success = 0 /// There was no handler available for the URL. case failure = 1 /// The URL could not be launched because it is invalid. case invalidUrl = 2 } /// Possible outcomes of handling a URL within the application. enum InAppLoadResult: Int { /// The URL was successfully loaded. case success = 0 /// The URL did not load successfully. case failedToLoad = 1 /// The URL could not be launched because it is invalid. case invalidUrl = 2 } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UrlLauncherApi { /// Checks whether a URL can be loaded. func canLaunchUrl(url: String) throws -> LaunchResult /// Opens the URL externally, returning the status of launching it. func launchUrl( url: String, universalLinksOnly: Bool, completion: @escaping (Result<LaunchResult, Error>) -> Void) /// Opens the URL in an in-app SFSafariViewController, returning the results /// of loading it. func openUrlInSafariViewController( url: String, completion: @escaping (Result<InAppLoadResult, Error>) -> Void) /// Closes the view controller opened by [openUrlInSafariViewController]. func closeSafariViewController() throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class UrlLauncherApiSetup { /// The codec used by UrlLauncherApi. /// Sets up an instance of `UrlLauncherApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UrlLauncherApi?) { /// Checks whether a URL can be loaded. let canLaunchUrlChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.canLaunchUrl", binaryMessenger: binaryMessenger) if let api = api { canLaunchUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] let urlArg = args[0] as! String do { let result = try api.canLaunchUrl(url: urlArg) reply(wrapResult(result.rawValue)) } catch { reply(wrapError(error)) } } } else { canLaunchUrlChannel.setMessageHandler(nil) } /// Opens the URL externally, returning the status of launching it. let launchUrlChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.launchUrl", binaryMessenger: binaryMessenger) if let api = api { launchUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] let urlArg = args[0] as! String let universalLinksOnlyArg = args[1] as! Bool api.launchUrl(url: urlArg, universalLinksOnly: universalLinksOnlyArg) { result in switch result { case .success(let res): reply(wrapResult(res.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { launchUrlChannel.setMessageHandler(nil) } /// Opens the URL in an in-app SFSafariViewController, returning the results /// of loading it. let openUrlInSafariViewControllerChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.openUrlInSafariViewController", binaryMessenger: binaryMessenger) if let api = api { openUrlInSafariViewControllerChannel.setMessageHandler { message, reply in let args = message as! [Any?] let urlArg = args[0] as! String api.openUrlInSafariViewController(url: urlArg) { result in switch result { case .success(let res): reply(wrapResult(res.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { openUrlInSafariViewControllerChannel.setMessageHandler(nil) } /// Closes the view controller opened by [openUrlInSafariViewController]. let closeSafariViewControllerChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.closeSafariViewController", binaryMessenger: binaryMessenger) if let api = api { closeSafariViewControllerChannel.setMessageHandler { _, reply in do { try api.closeSafariViewController() reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { closeSafariViewControllerChannel.setMessageHandler(nil) } } }
packages/packages/url_launcher/url_launcher_ios/ios/Classes/messages.g.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/ios/Classes/messages.g.swift", "repo_id": "packages", "token_count": 2042 }
1,055
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,056
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', swiftOut: 'macos/Classes/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', )) /// Possible error conditions for [UrlLauncherApi] calls. enum UrlLauncherError { /// The URL could not be parsed as an NSURL. invalidUrl, } /// Possible results for a [UrlLauncherApi] call with a boolean outcome. class UrlLauncherBoolResult { UrlLauncherBoolResult(this.value, {this.error}); final bool value; final UrlLauncherError? error; } @HostApi() abstract class UrlLauncherApi { /// Returns a true result if the URL can definitely be launched. @SwiftFunction('canLaunch(url:)') UrlLauncherBoolResult canLaunchUrl(String url); /// Opens the URL externally, returning a true result if successful. @SwiftFunction('launch(url:)') UrlLauncherBoolResult launchUrl(String url); }
packages/packages/url_launcher/url_launcher_macos/pigeons/messages.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/pigeons/messages.dart", "repo_id": "packages", "token_count": 349 }
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. #include <flutter/method_channel.h> #include <flutter/plugin_registrar_windows.h> #include <windows.h> #include <memory> #include <optional> #include <sstream> #include <string> #include "messages.g.h" #include "system_apis.h" namespace url_launcher_windows { class UrlLauncherPlugin : public flutter::Plugin, public UrlLauncherApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrar* registrar); UrlLauncherPlugin(); // Creates a plugin instance with the given SystemApi instance. // // Exists for unit testing with mock implementations. UrlLauncherPlugin(std::unique_ptr<SystemApis> system_apis); virtual ~UrlLauncherPlugin(); // Disallow copy and move. UrlLauncherPlugin(const UrlLauncherPlugin&) = delete; UrlLauncherPlugin& operator=(const UrlLauncherPlugin&) = delete; // UrlLauncherApi: ErrorOr<bool> CanLaunchUrl(const std::string& url) override; ErrorOr<bool> LaunchUrl(const std::string& url) override; private: std::unique_ptr<SystemApis> system_apis_; }; } // namespace url_launcher_windows
packages/packages/url_launcher/url_launcher_windows/windows/url_launcher_plugin.h/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/windows/url_launcher_plugin.h", "repo_id": "packages", "token_count": 390 }
1,058
WEBVTT 00:00:00.200 --> 00:00:01.750 [ Birds chirping ] 00:00:02.300 --> 00:00:05.000 [ Buzzing ]
packages/packages/video_player/video_player/example/assets/bumble_bee_captions.vtt/0
{ "file_path": "packages/packages/video_player/video_player/example/assets/bumble_bee_captions.vtt", "repo_id": "packages", "token_count": 51 }
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. package io.flutter.plugins.videoplayer; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.upstream.DefaultHttpDataSource; import io.flutter.plugin.common.EventChannel; import io.flutter.view.TextureRegistry; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class VideoPlayerTest { private ExoPlayer fakeExoPlayer; private EventChannel fakeEventChannel; private TextureRegistry.SurfaceTextureEntry fakeSurfaceTextureEntry; private VideoPlayerOptions fakeVideoPlayerOptions; private QueuingEventSink fakeEventSink; private DefaultHttpDataSource.Factory httpDataSourceFactorySpy; @Captor private ArgumentCaptor<HashMap<String, Object>> eventCaptor; @Before public void before() { MockitoAnnotations.openMocks(this); fakeExoPlayer = mock(ExoPlayer.class); fakeEventChannel = mock(EventChannel.class); fakeSurfaceTextureEntry = mock(TextureRegistry.SurfaceTextureEntry.class); fakeVideoPlayerOptions = mock(VideoPlayerOptions.class); fakeEventSink = mock(QueuingEventSink.class); httpDataSourceFactorySpy = spy(new DefaultHttpDataSource.Factory()); } @Test public void videoPlayer_buildsHttpDataSourceFactoryProperlyWhenHttpHeadersNull() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); videoPlayer.buildHttpDataSourceFactory(new HashMap<>()); verify(httpDataSourceFactorySpy).setUserAgent("ExoPlayer"); verify(httpDataSourceFactorySpy).setAllowCrossProtocolRedirects(true); verify(httpDataSourceFactorySpy, never()).setDefaultRequestProperties(any()); } @Test public void videoPlayer_buildsHttpDataSourceFactoryProperlyWhenHttpHeadersNonNullAndUserAgentSpecified() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Map<String, String> httpHeaders = new HashMap<String, String>() { { put("header", "value"); put("User-Agent", "userAgent"); } }; videoPlayer.buildHttpDataSourceFactory(httpHeaders); verify(httpDataSourceFactorySpy).setUserAgent("userAgent"); verify(httpDataSourceFactorySpy).setAllowCrossProtocolRedirects(true); verify(httpDataSourceFactorySpy).setDefaultRequestProperties(httpHeaders); } @Test public void videoPlayer_buildsHttpDataSourceFactoryProperlyWhenHttpHeadersNonNullAndUserAgentNotSpecified() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Map<String, String> httpHeaders = new HashMap<String, String>() { { put("header", "value"); } }; videoPlayer.buildHttpDataSourceFactory(httpHeaders); verify(httpDataSourceFactorySpy).setUserAgent("ExoPlayer"); verify(httpDataSourceFactorySpy).setAllowCrossProtocolRedirects(true); verify(httpDataSourceFactorySpy).setDefaultRequestProperties(httpHeaders); } @Test public void sendInitializedSendsExpectedEvent_90RotationDegrees() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Format testFormat = new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(90).build(); when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat); when(fakeExoPlayer.getDuration()).thenReturn(10L); videoPlayer.isInitialized = true; videoPlayer.sendInitialized(); verify(fakeEventSink).success(eventCaptor.capture()); HashMap<String, Object> event = eventCaptor.getValue(); assertEquals(event.get("event"), "initialized"); assertEquals(event.get("duration"), 10L); assertEquals(event.get("width"), 200); assertEquals(event.get("height"), 100); assertEquals(event.get("rotationCorrection"), null); } @Test public void sendInitializedSendsExpectedEvent_270RotationDegrees() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Format testFormat = new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(270).build(); when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat); when(fakeExoPlayer.getDuration()).thenReturn(10L); videoPlayer.isInitialized = true; videoPlayer.sendInitialized(); verify(fakeEventSink).success(eventCaptor.capture()); HashMap<String, Object> event = eventCaptor.getValue(); assertEquals(event.get("event"), "initialized"); assertEquals(event.get("duration"), 10L); assertEquals(event.get("width"), 200); assertEquals(event.get("height"), 100); assertEquals(event.get("rotationCorrection"), null); } @Test public void sendInitializedSendsExpectedEvent_0RotationDegrees() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Format testFormat = new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(0).build(); when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat); when(fakeExoPlayer.getDuration()).thenReturn(10L); videoPlayer.isInitialized = true; videoPlayer.sendInitialized(); verify(fakeEventSink).success(eventCaptor.capture()); HashMap<String, Object> event = eventCaptor.getValue(); assertEquals(event.get("event"), "initialized"); assertEquals(event.get("duration"), 10L); assertEquals(event.get("width"), 100); assertEquals(event.get("height"), 200); assertEquals(event.get("rotationCorrection"), null); } @Test public void sendInitializedSendsExpectedEvent_180RotationDegrees() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); Format testFormat = new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(180).build(); when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat); when(fakeExoPlayer.getDuration()).thenReturn(10L); videoPlayer.isInitialized = true; videoPlayer.sendInitialized(); verify(fakeEventSink).success(eventCaptor.capture()); HashMap<String, Object> event = eventCaptor.getValue(); assertEquals(event.get("event"), "initialized"); assertEquals(event.get("duration"), 10L); assertEquals(event.get("width"), 100); assertEquals(event.get("height"), 200); assertEquals(event.get("rotationCorrection"), 180); } @Test public void onIsPlayingChangedSendsExpectedEvent() { VideoPlayer videoPlayer = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); doAnswer( (Answer<Void>) invocation -> { Map<String, Object> event = new HashMap<>(); event.put("event", "isPlayingStateUpdate"); event.put("isPlaying", (Boolean) invocation.getArguments()[0]); fakeEventSink.success(event); return null; }) .when(fakeExoPlayer) .setPlayWhenReady(anyBoolean()); videoPlayer.play(); verify(fakeEventSink).success(eventCaptor.capture()); HashMap<String, Object> event1 = eventCaptor.getValue(); assertEquals(event1.get("event"), "isPlayingStateUpdate"); assertEquals(event1.get("isPlaying"), true); videoPlayer.pause(); verify(fakeEventSink, times(2)).success(eventCaptor.capture()); HashMap<String, Object> event2 = eventCaptor.getValue(); assertEquals(event2.get("event"), "isPlayingStateUpdate"); assertEquals(event2.get("isPlaying"), false); } @Test public void behindLiveWindowErrorResetsPlayerToDefaultPosition() { List<Player.Listener> listeners = new LinkedList<>(); doAnswer(invocation -> listeners.add(invocation.getArgument(0))) .when(fakeExoPlayer) .addListener(any()); VideoPlayer unused = new VideoPlayer( fakeExoPlayer, fakeEventChannel, fakeSurfaceTextureEntry, fakeVideoPlayerOptions, fakeEventSink, httpDataSourceFactorySpy); PlaybackException exception = new PlaybackException(null, null, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW); listeners.forEach(listener -> listener.onPlayerError(exception)); verify(fakeExoPlayer).seekToDefaultPosition(); verify(fakeExoPlayer).prepare(); } }
packages/packages/video_player/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java/0
{ "file_path": "packages/packages/video_player/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java", "repo_id": "packages", "token_count": 4058 }
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 "FVPVideoPlayerPlugin.h" #import <AVFoundation/AVFoundation.h> #import "FVPDisplayLink.h" #import "messages.g.h" // Protocol for AVFoundation object instance factory. Used for injecting framework objects in tests. @protocol FVPAVFactory @required - (AVPlayer *)playerWithPlayerItem:(AVPlayerItem *)playerItem; - (AVPlayerItemVideoOutput *)videoOutputWithPixelBufferAttributes: (NSDictionary<NSString *, id> *)attributes; @end // Protocol for an AVPlayer instance factory. Used for injecting display links in tests. @protocol FVPDisplayLinkFactory - (FVPDisplayLink *)displayLinkWithRegistrar:(id<FlutterPluginRegistrar>)registrar callback:(void (^)(void))callback; @end #pragma mark - // TODO(stuartmorgan): Move this whole class to its own files. @interface FVPVideoPlayer : NSObject <FlutterStreamHandler, FlutterTexture> @property(readonly, nonatomic) AVPlayer *player; // This is to fix 2 bugs: 1. blank video for encrypted video streams on iOS 16 // (https://github.com/flutter/flutter/issues/111457) and 2. swapped width and height for some video // streams (not just iOS 16). (https://github.com/flutter/flutter/issues/109116). // An invisible AVPlayerLayer is used to overwrite the protection of pixel buffers in those streams // for issue #1, and restore the correct width and height for issue #2. @property(readonly, nonatomic) AVPlayerLayer *playerLayer; @property(readonly, nonatomic) int64_t position; - (void)onTextureUnregistered:(NSObject<FlutterTexture> *)texture; @end #pragma mark - @interface FVPVideoPlayerPlugin () <FVPAVFoundationVideoPlayerApi> @property(readonly, strong, nonatomic) NSMutableDictionary<NSNumber *, FVPVideoPlayer *> *playersByTextureId; - (instancetype)initWithAVFactory:(id<FVPAVFactory>)avFactory displayLinkFactory:(id<FVPDisplayLinkFactory>)displayLinkFactory registrar:(NSObject<FlutterPluginRegistrar> *)registrar; @end
packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPVideoPlayerPlugin_Test.h/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPVideoPlayerPlugin_Test.h", "repo_id": "packages", "token_count": 698 }
1,061
// 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' as io; import 'package:logging/logging.dart'; import 'src/benchmark_result.dart'; import 'src/common.dart'; import 'src/compilation_options.dart'; import 'src/runner.dart'; export 'src/benchmark_result.dart'; export 'src/compilation_options.dart'; /// The default port number used by the local benchmark server. const int defaultBenchmarkServerPort = 9999; /// The default port number used for Chrome DevTool Protocol. const int defaultChromeDebugPort = 10000; /// Builds and serves a Flutter Web app, collects raw benchmark data and /// summarizes the result as a [BenchmarkResult]. /// /// [benchmarkAppDirectory] is the directory containing the app that's being /// benchmarked. The app is expected to use `package:web_benchmarks/client.dart` /// and call the `runBenchmarks` function to run the benchmarks. /// /// [entryPoint] is the path to the main app file that runs the benchmark. It /// can be different (and typically is) from the production entry point of the /// app. /// /// If [useCanvasKit] is true, builds the app in CanvasKit mode. /// /// [benchmarkServerPort] is the port this benchmark server serves the app on. /// By default uses [defaultBenchmarkServerPort]. /// /// [chromeDebugPort] is the port Chrome uses for DevTool Protocol used to /// extract tracing data. By default uses [defaultChromeDebugPort]. /// /// If [headless] is true, runs Chrome without UI. In particular, this is /// useful in environments (e.g. CI) that doesn't have a display. Future<BenchmarkResults> serveWebBenchmark({ required io.Directory benchmarkAppDirectory, required String entryPoint, int benchmarkServerPort = defaultBenchmarkServerPort, int chromeDebugPort = defaultChromeDebugPort, bool headless = true, bool treeShakeIcons = true, String initialPage = defaultInitialPage, CompilationOptions compilationOptions = const CompilationOptions(), }) async { // Reduce logging level. Otherwise, package:webkit_inspection_protocol is way too spammy. Logger.root.level = Level.INFO; return BenchmarkServer( benchmarkAppDirectory: benchmarkAppDirectory, entryPoint: entryPoint, benchmarkServerPort: benchmarkServerPort, chromeDebugPort: chromeDebugPort, headless: headless, compilationOptions: compilationOptions, treeShakeIcons: treeShakeIcons, initialPage: initialPage, ).run(); }
packages/packages/web_benchmarks/lib/server.dart/0
{ "file_path": "packages/packages/web_benchmarks/lib/server.dart", "repo_id": "packages", "token_count": 711 }
1,062
# test_app An example app for web benchmarks testing.
packages/packages/web_benchmarks/testing/test_app/README.md/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/README.md", "repo_id": "packages", "token_count": 15 }
1,063
name: webview_flutter description: A Flutter plugin that provides a WebView widget on Android and iOS. repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 version: 4.7.0 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: platforms: android: default_package: webview_flutter_android ios: default_package: webview_flutter_wkwebview dependencies: flutter: sdk: flutter webview_flutter_android: ^3.15.0 webview_flutter_platform_interface: ^2.10.0 webview_flutter_wkwebview: ^3.12.0 dev_dependencies: build_runner: ^2.1.5 flutter_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 topics: - html - webview - webview-flutter
packages/packages/webview_flutter/webview_flutter/pubspec.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/pubspec.yaml", "repo_id": "packages", "token_count": 369 }
1,064
group 'io.flutter.plugins.webviewflutter' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:8.0.0' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'io.flutter.plugins.webviewflutter' } compileSdk 34 defaultConfig { minSdkVersion 19 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } dependencies { implementation 'androidx.annotation:annotation:1.7.1' implementation 'androidx.webkit:webkit:1.7.0' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.1.0' testImplementation 'androidx.test:core:1.3.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/webview_flutter/webview_flutter_android/android/build.gradle/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/build.gradle", "repo_id": "packages", "token_count": 720 }
1,065
// 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.webviewflutter; import android.webkit.HttpAuthHandler; import androidx.annotation.NonNull; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.HttpAuthHandlerFlutterApi; /** * Flutter API implementation for {@link HttpAuthHandler}. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class HttpAuthHandlerFlutterApiImpl { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private final HttpAuthHandlerFlutterApi api; /** * Constructs a {@link HttpAuthHandlerFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public HttpAuthHandlerFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new HttpAuthHandlerFlutterApi(binaryMessenger); } /** * Stores the `HttpAuthHandler` instance and notifies Dart to create and store a new * `HttpAuthHandler` instance that is attached to this one. If `instance` has already been added, * this method does nothing. */ public void create( @NonNull HttpAuthHandler instance, @NonNull HttpAuthHandlerFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create(instanceManager.addHostCreatedInstance(instance), callback); } } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerFlutterApiImpl.java", "repo_id": "packages", "token_count": 566 }
1,066
// 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.webviewflutter; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.FlutterEngine; /** * App and package facing native API provided by the `webview_flutter_android` plugin. * * <p>This class follows the convention of breaking changes of the Dart API, which means that any * changes to the class that are not backwards compatible will only be made with a major version * change of the plugin. * * <p>Native code other than this external API does not follow breaking change conventions, so app * or plugin clients should not use any other native APIs. */ @SuppressWarnings("unused") public interface WebViewFlutterAndroidExternalApi { /** * Retrieves the {@link WebView} that is associated with `identifier`. * * <p>See the Dart method `AndroidWebViewController.webViewIdentifier` to get the identifier of an * underlying `WebView`. * * @param engine the execution environment the {@link WebViewFlutterPlugin} should belong to. If * the engine doesn't contain an attached instance of {@link WebViewFlutterPlugin}, this * method returns null. * @param identifier the associated identifier of the `WebView`. * @return the `WebView` associated with `identifier` or null if a `WebView` instance associated * with `identifier` could not be found. */ @Nullable static WebView getWebView(@NonNull FlutterEngine engine, long identifier) { final WebViewFlutterPlugin webViewPlugin = (WebViewFlutterPlugin) engine.getPlugins().get(WebViewFlutterPlugin.class); if (webViewPlugin != null && webViewPlugin.getInstanceManager() != null) { final Object instance = webViewPlugin.getInstanceManager().getInstance(identifier); if (instance instanceof WebView) { return (WebView) instance; } } return null; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterAndroidExternalApi.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterAndroidExternalApi.java", "repo_id": "packages", "token_count": 612 }
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. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Mode of how to select files for a file chooser. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. enum FileChooserMode { /// Open single file and requires that the file exists before allowing the /// user to pick it. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN. open, /// Similar to [open] but allows multiple files to be selected. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN_MULTIPLE. openMultiple, /// Allows picking a nonexistent file and saving it. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_SAVE. save, } /// Indicates the type of message logged to the console. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel. enum ConsoleMessageLevel { /// Indicates a message is logged for debugging. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#DEBUG. debug, /// Indicates a message is provided as an error. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#ERROR. error, /// Indicates a message is provided as a basic log message. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#LOG. log, /// Indicates a message is provided as a tip. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#TIP. tip, /// Indicates a message is provided as a warning. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#WARNING. warning, /// Indicates a message with an unknown level. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. unknown, } class WebResourceRequestData { WebResourceRequestData({ required this.url, required this.isForMainFrame, this.isRedirect, required this.hasGesture, required this.method, required this.requestHeaders, }); String url; bool isForMainFrame; bool? isRedirect; bool hasGesture; String method; Map<String?, String?> requestHeaders; Object encode() { return <Object?>[ url, isForMainFrame, isRedirect, hasGesture, method, requestHeaders, ]; } static WebResourceRequestData decode(Object result) { result as List<Object?>; return WebResourceRequestData( url: result[0]! as String, isForMainFrame: result[1]! as bool, isRedirect: result[2] as bool?, hasGesture: result[3]! as bool, method: result[4]! as String, requestHeaders: (result[5] as Map<Object?, Object?>?)!.cast<String?, String?>(), ); } } class WebResourceResponseData { WebResourceResponseData({ required this.statusCode, }); int statusCode; Object encode() { return <Object?>[ statusCode, ]; } static WebResourceResponseData decode(Object result) { result as List<Object?>; return WebResourceResponseData( statusCode: result[0]! as int, ); } } class WebResourceErrorData { WebResourceErrorData({ required this.errorCode, required this.description, }); int errorCode; String description; Object encode() { return <Object?>[ errorCode, description, ]; } static WebResourceErrorData decode(Object result) { result as List<Object?>; return WebResourceErrorData( errorCode: result[0]! as int, description: result[1]! as String, ); } } class WebViewPoint { WebViewPoint({ required this.x, required this.y, }); int x; int y; Object encode() { return <Object?>[ x, y, ]; } static WebViewPoint decode(Object result) { result as List<Object?>; return WebViewPoint( x: result[0]! as int, y: result[1]! as int, ); } } /// Represents a JavaScript console message from WebCore. /// /// See https://developer.android.com/reference/android/webkit/ConsoleMessage class ConsoleMessage { ConsoleMessage({ required this.lineNumber, required this.message, required this.level, required this.sourceId, }); int lineNumber; String message; ConsoleMessageLevel level; String sourceId; Object encode() { return <Object?>[ lineNumber, message, level.index, sourceId, ]; } static ConsoleMessage decode(Object result) { result as List<Object?>; return ConsoleMessage( lineNumber: result[0]! as int, message: result[1]! as String, level: ConsoleMessageLevel.values[result[2]! as int], sourceId: result[3]! as String, ); } } /// Host API for managing the native `InstanceManager`. class InstanceManagerHostApi { /// Constructor for [InstanceManagerHostApi]. 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. InstanceManagerHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Clear the native `InstanceManager`. /// /// This is typically only used after a hot restart. Future<void> clear() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.InstanceManagerHostApi.clear', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) 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; } } } /// Handles methods calls to the native Java Object class. /// /// Also handles calls to remove the reference to an instance with `dispose`. /// /// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html. class JavaObjectHostApi { /// Constructor for [JavaObjectHostApi]. 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. JavaObjectHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> dispose(int arg_identifier) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.JavaObjectHostApi.dispose', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_identifier]) 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; } } } /// Handles callbacks methods for the native Java Object class. /// /// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html. abstract class JavaObjectFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void dispose(int identifier); static void setup(JavaObjectFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.JavaObjectFlutterApi.dispose', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaObjectFlutterApi.dispose was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaObjectFlutterApi.dispose was null, expected non-null int.'); api.dispose(arg_identifier!); return; }); } } } } /// Host API for `CookieManager`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. class CookieManagerHostApi { /// Constructor for [CookieManagerHostApi]. 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. CookieManagerHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Handles attaching `CookieManager.instance` to a native instance. Future<void> attachInstance(int arg_instanceIdentifier) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.attachInstance', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceIdentifier]) 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; } } /// Handles Dart method `CookieManager.setCookie`. Future<void> setCookie( int arg_identifier, String arg_url, String arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_identifier, arg_url, arg_value]) 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; } } /// Handles Dart method `CookieManager.removeAllCookies`. Future<bool> removeAllCookies(int arg_identifier) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.removeAllCookies', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_identifier]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Handles Dart method `CookieManager.setAcceptThirdPartyCookies`. Future<void> setAcceptThirdPartyCookies( int arg_identifier, int arg_webViewIdentifier, bool arg_accept) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_identifier, arg_webViewIdentifier, arg_accept]) 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; } } } class _WebViewHostApiCodec extends StandardMessageCodec { const _WebViewHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WebViewPoint) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WebViewPoint.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class WebViewHostApi { /// Constructor for [WebViewHostApi]. 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. WebViewHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _WebViewHostApiCodec(); Future<void> create(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> loadData(int arg_instanceId, String arg_data, String? arg_mimeType, String? arg_encoding) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send( <Object?>[arg_instanceId, arg_data, arg_mimeType, arg_encoding]) 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; } } Future<void> loadDataWithBaseUrl( int arg_instanceId, String? arg_baseUrl, String arg_data, String? arg_mimeType, String? arg_encoding, String? arg_historyUrl) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[ arg_instanceId, arg_baseUrl, arg_data, arg_mimeType, arg_encoding, arg_historyUrl ]) 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; } } Future<void> loadUrl(int arg_instanceId, String arg_url, Map<String?, String?> arg_headers) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_url, arg_headers]) 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; } } Future<void> postUrl( int arg_instanceId, String arg_url, Uint8List arg_data) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_url, arg_data]) 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; } } Future<String?> getUrl(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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<bool> canGoBack(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoBack', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } Future<bool> canGoForward(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoForward', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } Future<void> goBack(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goBack', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> goForward(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goForward', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> reload(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.reload', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> clearCache(int arg_instanceId, bool arg_includeDiskFiles) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_includeDiskFiles]) 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; } } Future<String?> evaluateJavascript( int arg_instanceId, String arg_javascriptString) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_javascriptString]) 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?> getTitle(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getTitle', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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<void> scrollTo(int arg_instanceId, int arg_x, int arg_y) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_x, arg_y]) 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; } } Future<void> scrollBy(int arg_instanceId, int arg_x, int arg_y) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_x, arg_y]) 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; } } Future<int> getScrollX(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollX', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as int?)!; } } Future<int> getScrollY(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollY', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as int?)!; } } Future<WebViewPoint> getScrollPosition(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollPosition', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as WebViewPoint?)!; } } Future<void> setWebContentsDebuggingEnabled(bool arg_enabled) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebContentsDebuggingEnabled', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_enabled]) 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; } } Future<void> setWebViewClient( int arg_instanceId, int arg_webViewClientInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_webViewClientInstanceId]) 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; } } Future<void> addJavaScriptChannel( int arg_instanceId, int arg_javaScriptChannelInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_javaScriptChannelInstanceId]) 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; } } Future<void> removeJavaScriptChannel( int arg_instanceId, int arg_javaScriptChannelInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_javaScriptChannelInstanceId]) 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; } } Future<void> setDownloadListener( int arg_instanceId, int? arg_listenerInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setDownloadListener', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_listenerInstanceId]) 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; } } Future<void> setWebChromeClient( int arg_instanceId, int? arg_clientInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebChromeClient', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_clientInstanceId]) 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; } } Future<void> setBackgroundColor(int arg_instanceId, int arg_color) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_color]) 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; } } } /// Flutter API for `WebView`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/webkit/WebView. abstract class WebViewFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int identifier); void onScrollChanged( int webViewInstanceId, int left, int top, int oldLeft, int oldTop); static void setup(WebViewFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.create was null, expected non-null int.'); api.create(arg_identifier!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_webViewInstanceId = (args[0] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null, expected non-null int.'); final int? arg_left = (args[1] as int?); assert(arg_left != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null, expected non-null int.'); final int? arg_top = (args[2] as int?); assert(arg_top != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null, expected non-null int.'); final int? arg_oldLeft = (args[3] as int?); assert(arg_oldLeft != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null, expected non-null int.'); final int? arg_oldTop = (args[4] as int?); assert(arg_oldTop != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged was null, expected non-null int.'); api.onScrollChanged(arg_webViewInstanceId!, arg_left!, arg_top!, arg_oldLeft!, arg_oldTop!); return; }); } } } } class WebSettingsHostApi { /// Constructor for [WebSettingsHostApi]. 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. WebSettingsHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId, int arg_webViewInstanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId, arg_webViewInstanceId]) 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; } } Future<void> setDomStorageEnabled(int arg_instanceId, bool arg_flag) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_flag]) 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; } } Future<void> setJavaScriptCanOpenWindowsAutomatically( int arg_instanceId, bool arg_flag) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_flag]) 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; } } Future<void> setSupportMultipleWindows( int arg_instanceId, bool arg_support) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_support]) 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; } } Future<void> setJavaScriptEnabled(int arg_instanceId, bool arg_flag) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_flag]) 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; } } Future<void> setUserAgentString( int arg_instanceId, String? arg_userAgentString) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUserAgentString', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_userAgentString]) 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; } } Future<void> setMediaPlaybackRequiresUserGesture( int arg_instanceId, bool arg_require) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_require]) 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; } } Future<void> setSupportZoom(int arg_instanceId, bool arg_support) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_support]) 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; } } Future<void> setLoadWithOverviewMode( int arg_instanceId, bool arg_overview) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_overview]) 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; } } Future<void> setUseWideViewPort(int arg_instanceId, bool arg_use) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_use]) 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; } } Future<void> setDisplayZoomControls( int arg_instanceId, bool arg_enabled) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_enabled]) 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; } } Future<void> setBuiltInZoomControls( int arg_instanceId, bool arg_enabled) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_enabled]) 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; } } Future<void> setAllowFileAccess(int arg_instanceId, bool arg_enabled) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_enabled]) 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; } } Future<void> setTextZoom(int arg_instanceId, int arg_textZoom) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_textZoom]) 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; } } Future<String> getUserAgentString(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.getUserAgentString', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as String?)!; } } } class JavaScriptChannelHostApi { /// Constructor for [JavaScriptChannelHostApi]. 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. JavaScriptChannelHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId, String arg_channelName) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_channelName]) 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; } } } abstract class JavaScriptChannelFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void postMessage(int instanceId, String message); static void setup(JavaScriptChannelFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelFlutterApi.postMessage', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelFlutterApi.postMessage was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelFlutterApi.postMessage was null, expected non-null int.'); final String? arg_message = (args[1] as String?); assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelFlutterApi.postMessage was null, expected non-null String.'); api.postMessage(arg_instanceId!, arg_message!); return; }); } } } } class WebViewClientHostApi { /// Constructor for [WebViewClientHostApi]. 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. WebViewClientHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } } class _WebViewClientFlutterApiCodec extends StandardMessageCodec { const _WebViewClientFlutterApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WebResourceErrorData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is WebResourceRequestData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is WebResourceResponseData) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WebResourceErrorData.decode(readValue(buffer)!); case 129: return WebResourceRequestData.decode(readValue(buffer)!); case 130: return WebResourceResponseData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class WebViewClientFlutterApi { static const MessageCodec<Object?> codec = _WebViewClientFlutterApiCodec(); void onPageStarted(int instanceId, int webViewInstanceId, String url); void onPageFinished(int instanceId, int webViewInstanceId, String url); void onReceivedHttpError(int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceResponseData response); void onReceivedRequestError(int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceErrorData error); void onReceivedError(int instanceId, int webViewInstanceId, int errorCode, String description, String failingUrl); void requestLoading( int instanceId, int webViewInstanceId, WebResourceRequestData request); void urlLoading(int instanceId, int webViewInstanceId, String url); void doUpdateVisitedHistory( int instanceId, int webViewInstanceId, String url, bool isReload); void onReceivedHttpAuthRequest(int instanceId, int webViewInstanceId, int httpAuthHandlerInstanceId, String host, String realm); static void setup(WebViewClientFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted was null, expected non-null int.'); final String? arg_url = (args[2] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted was null, expected non-null String.'); api.onPageStarted(arg_instanceId!, arg_webViewInstanceId!, arg_url!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished was null, expected non-null int.'); final String? arg_url = (args[2] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished was null, expected non-null String.'); api.onPageFinished(arg_instanceId!, arg_webViewInstanceId!, arg_url!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError was null, expected non-null int.'); final WebResourceRequestData? arg_request = (args[2] as WebResourceRequestData?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError was null, expected non-null WebResourceRequestData.'); final WebResourceResponseData? arg_response = (args[3] as WebResourceResponseData?); assert(arg_response != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError was null, expected non-null WebResourceResponseData.'); api.onReceivedHttpError(arg_instanceId!, arg_webViewInstanceId!, arg_request!, arg_response!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null int.'); final WebResourceRequestData? arg_request = (args[2] as WebResourceRequestData?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null WebResourceRequestData.'); final WebResourceErrorData? arg_error = (args[3] as WebResourceErrorData?); assert(arg_error != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null WebResourceErrorData.'); api.onReceivedRequestError(arg_instanceId!, arg_webViewInstanceId!, arg_request!, arg_error!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.'); final int? arg_errorCode = (args[2] as int?); assert(arg_errorCode != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.'); final String? arg_description = (args[3] as String?); assert(arg_description != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null, expected non-null String.'); final String? arg_failingUrl = (args[4] as String?); assert(arg_failingUrl != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError was null, expected non-null String.'); api.onReceivedError(arg_instanceId!, arg_webViewInstanceId!, arg_errorCode!, arg_description!, arg_failingUrl!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading was null, expected non-null int.'); final WebResourceRequestData? arg_request = (args[2] as WebResourceRequestData?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading was null, expected non-null WebResourceRequestData.'); api.requestLoading( arg_instanceId!, arg_webViewInstanceId!, arg_request!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading was null, expected non-null int.'); final String? arg_url = (args[2] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading was null, expected non-null String.'); api.urlLoading(arg_instanceId!, arg_webViewInstanceId!, arg_url!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory was null, expected non-null int.'); final String? arg_url = (args[2] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory was null, expected non-null String.'); final bool? arg_isReload = (args[3] as bool?); assert(arg_isReload != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory was null, expected non-null bool.'); api.doUpdateVisitedHistory( arg_instanceId!, arg_webViewInstanceId!, arg_url!, arg_isReload!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null, expected non-null int.'); final int? arg_httpAuthHandlerInstanceId = (args[2] as int?); assert(arg_httpAuthHandlerInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null, expected non-null int.'); final String? arg_host = (args[3] as String?); assert(arg_host != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null, expected non-null String.'); final String? arg_realm = (args[4] as String?); assert(arg_realm != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest was null, expected non-null String.'); api.onReceivedHttpAuthRequest(arg_instanceId!, arg_webViewInstanceId!, arg_httpAuthHandlerInstanceId!, arg_host!, arg_realm!); return; }); } } } } class DownloadListenerHostApi { /// Constructor for [DownloadListenerHostApi]. 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. DownloadListenerHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.DownloadListenerHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } } abstract class DownloadListenerFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void onDownloadStart(int instanceId, String url, String userAgent, String contentDisposition, String mimetype, int contentLength); static void setup(DownloadListenerFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.'); final String? arg_userAgent = (args[2] as String?); assert(arg_userAgent != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.'); final String? arg_contentDisposition = (args[3] as String?); assert(arg_contentDisposition != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.'); final String? arg_mimetype = (args[4] as String?); assert(arg_mimetype != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.'); final int? arg_contentLength = (args[5] as int?); assert(arg_contentLength != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null int.'); api.onDownloadStart(arg_instanceId!, arg_url!, arg_userAgent!, arg_contentDisposition!, arg_mimetype!, arg_contentLength!); return; }); } } } } class WebChromeClientHostApi { /// Constructor for [WebChromeClientHostApi]. 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. WebChromeClientHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> setSynchronousReturnValueForOnShowFileChooser( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } Future<void> setSynchronousReturnValueForOnConsoleMessage( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } Future<void> setSynchronousReturnValueForOnJsAlert( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } Future<void> setSynchronousReturnValueForOnJsConfirm( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } Future<void> setSynchronousReturnValueForOnJsPrompt( int arg_instanceId, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_value]) 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; } } } class FlutterAssetManagerHostApi { /// Constructor for [FlutterAssetManagerHostApi]. 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. FlutterAssetManagerHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<List<String?>> list(String arg_path) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.list', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_path]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<String?>(); } } Future<String> getAssetFilePathByName(String arg_name) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.getAssetFilePathByName', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_name]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as String?)!; } } } class _WebChromeClientFlutterApiCodec extends StandardMessageCodec { const _WebChromeClientFlutterApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is ConsoleMessage) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return ConsoleMessage.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class WebChromeClientFlutterApi { static const MessageCodec<Object?> codec = _WebChromeClientFlutterApiCodec(); void onProgressChanged(int instanceId, int webViewInstanceId, int progress); Future<List<String?>> onShowFileChooser( int instanceId, int webViewInstanceId, int paramsInstanceId); /// Callback to Dart function `WebChromeClient.onPermissionRequest`. void onPermissionRequest(int instanceId, int requestInstanceId); /// Callback to Dart function `WebChromeClient.onShowCustomView`. void onShowCustomView( int instanceId, int viewIdentifier, int callbackIdentifier); /// Callback to Dart function `WebChromeClient.onHideCustomView`. void onHideCustomView(int instanceId); /// Callback to Dart function `WebChromeClient.onGeolocationPermissionsShowPrompt`. void onGeolocationPermissionsShowPrompt( int instanceId, int paramsInstanceId, String origin); /// Callback to Dart function `WebChromeClient.onGeolocationPermissionsHidePrompt`. void onGeolocationPermissionsHidePrompt(int identifier); /// Callback to Dart function `WebChromeClient.onConsoleMessage`. void onConsoleMessage(int instanceId, ConsoleMessage message); Future<void> onJsAlert(int instanceId, String url, String message); Future<bool> onJsConfirm(int instanceId, String url, String message); Future<String> onJsPrompt( int instanceId, String url, String message, String defaultValue); static void setup(WebChromeClientFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.'); final int? arg_progress = (args[2] as int?); assert(arg_progress != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.'); api.onProgressChanged( arg_instanceId!, arg_webViewInstanceId!, arg_progress!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.'); final int? arg_webViewInstanceId = (args[1] as int?); assert(arg_webViewInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.'); final int? arg_paramsInstanceId = (args[2] as int?); assert(arg_paramsInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.'); final List<String?> output = await api.onShowFileChooser( arg_instanceId!, arg_webViewInstanceId!, arg_paramsInstanceId!); return output; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onPermissionRequest', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onPermissionRequest was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onPermissionRequest was null, expected non-null int.'); final int? arg_requestInstanceId = (args[1] as int?); assert(arg_requestInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onPermissionRequest was null, expected non-null int.'); api.onPermissionRequest(arg_instanceId!, arg_requestInstanceId!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView was null, expected non-null int.'); final int? arg_viewIdentifier = (args[1] as int?); assert(arg_viewIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView was null, expected non-null int.'); final int? arg_callbackIdentifier = (args[2] as int?); assert(arg_callbackIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView was null, expected non-null int.'); api.onShowCustomView( arg_instanceId!, arg_viewIdentifier!, arg_callbackIdentifier!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onHideCustomView', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onHideCustomView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onHideCustomView was null, expected non-null int.'); api.onHideCustomView(arg_instanceId!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt was null, expected non-null int.'); final int? arg_paramsInstanceId = (args[1] as int?); assert(arg_paramsInstanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt was null, expected non-null int.'); final String? arg_origin = (args[2] as String?); assert(arg_origin != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt was null, expected non-null String.'); api.onGeolocationPermissionsShowPrompt( arg_instanceId!, arg_paramsInstanceId!, arg_origin!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsHidePrompt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsHidePrompt was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsHidePrompt was null, expected non-null int.'); api.onGeolocationPermissionsHidePrompt(arg_identifier!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onConsoleMessage', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onConsoleMessage was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onConsoleMessage was null, expected non-null int.'); final ConsoleMessage? arg_message = (args[1] as ConsoleMessage?); assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onConsoleMessage was null, expected non-null ConsoleMessage.'); api.onConsoleMessage(arg_instanceId!, arg_message!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert was null, expected non-null String.'); final String? arg_message = (args[2] as String?); assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert was null, expected non-null String.'); await api.onJsAlert(arg_instanceId!, arg_url!, arg_message!); return; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm was null, expected non-null String.'); final String? arg_message = (args[2] as String?); assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm was null, expected non-null String.'); final bool output = await api.onJsConfirm(arg_instanceId!, arg_url!, arg_message!); return output; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt was null, expected non-null String.'); final String? arg_message = (args[2] as String?); assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt was null, expected non-null String.'); final String? arg_defaultValue = (args[3] as String?); assert(arg_defaultValue != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt was null, expected non-null String.'); final String output = await api.onJsPrompt( arg_instanceId!, arg_url!, arg_message!, arg_defaultValue!); return output; }); } } } } class WebStorageHostApi { /// Constructor for [WebStorageHostApi]. 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. WebStorageHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> create(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.create', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } Future<void> deleteAllData(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.deleteAllData', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } } /// Handles callbacks methods for the native Java FileChooserParams class. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. abstract class FileChooserParamsFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int instanceId, bool isCaptureEnabled, List<String?> acceptTypes, FileChooserMode mode, String? filenameHint); static void setup(FileChooserParamsFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create was null, expected non-null int.'); final bool? arg_isCaptureEnabled = (args[1] as bool?); assert(arg_isCaptureEnabled != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create was null, expected non-null bool.'); final List<String?>? arg_acceptTypes = (args[2] as List<Object?>?)?.cast<String?>(); assert(arg_acceptTypes != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create was null, expected non-null List<String?>.'); final FileChooserMode? arg_mode = args[3] == null ? null : FileChooserMode.values[args[3]! as int]; assert(arg_mode != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create was null, expected non-null FileChooserMode.'); final String? arg_filenameHint = (args[4] as String?); api.create(arg_instanceId!, arg_isCaptureEnabled!, arg_acceptTypes!, arg_mode!, arg_filenameHint); return; }); } } } } /// Host API for `PermissionRequest`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. /// /// See https://developer.android.com/reference/android/webkit/PermissionRequest. class PermissionRequestHostApi { /// Constructor for [PermissionRequestHostApi]. 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. PermissionRequestHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Handles Dart method `PermissionRequest.grant`. Future<void> grant(int arg_instanceId, List<String?> arg_resources) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_resources]) 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; } } /// Handles Dart method `PermissionRequest.deny`. Future<void> deny(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.deny', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } } /// Flutter API for `PermissionRequest`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/webkit/PermissionRequest. abstract class PermissionRequestFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int instanceId, List<String?> resources); static void setup(PermissionRequestFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.PermissionRequestFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestFlutterApi.create was null, expected non-null int.'); final List<String?>? arg_resources = (args[1] as List<Object?>?)?.cast<String?>(); assert(arg_resources != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestFlutterApi.create was null, expected non-null List<String?>.'); api.create(arg_instanceId!, arg_resources!); return; }); } } } } /// Host API for `CustomViewCallback`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.CustomViewCallback. class CustomViewCallbackHostApi { /// Constructor for [CustomViewCallbackHostApi]. 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. CustomViewCallbackHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Handles Dart method `CustomViewCallback.onCustomViewHidden`. Future<void> onCustomViewHidden(int arg_identifier) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackHostApi.onCustomViewHidden', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_identifier]) 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; } } } /// Flutter API for `CustomViewCallback`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.CustomViewCallback. abstract class CustomViewCallbackFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int identifier); static void setup(CustomViewCallbackFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackFlutterApi.create was null, expected non-null int.'); api.create(arg_identifier!); return; }); } } } } /// Flutter API for `View`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/view/View. abstract class ViewFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int identifier); static void setup(ViewFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.ViewFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.ViewFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.ViewFlutterApi.create was null, expected non-null int.'); api.create(arg_identifier!); return; }); } } } } /// Host API for `GeolocationPermissionsCallback`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. /// /// See https://developer.android.com/reference/android/webkit/GeolocationPermissions.Callback. class GeolocationPermissionsCallbackHostApi { /// Constructor for [GeolocationPermissionsCallbackHostApi]. 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. GeolocationPermissionsCallbackHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Handles Dart method `GeolocationPermissionsCallback.invoke`. Future<void> invoke(int arg_instanceId, String arg_origin, bool arg_allow, bool arg_retain) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_origin, arg_allow, arg_retain]) 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; } } } /// Flutter API for `GeolocationPermissionsCallback`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/webkit/GeolocationPermissions.Callback. abstract class GeolocationPermissionsCallbackFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int instanceId); static void setup(GeolocationPermissionsCallbackFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackFlutterApi.create was null, expected non-null int.'); api.create(arg_instanceId!); return; }); } } } } /// Host API for `HttpAuthHandler`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. /// /// See https://developer.android.com/reference/android/webkit/HttpAuthHandler. class HttpAuthHandlerHostApi { /// Constructor for [HttpAuthHandlerHostApi]. 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. HttpAuthHandlerHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Handles Dart method `HttpAuthHandler.useHttpAuthUsernamePassword`. Future<bool> useHttpAuthUsernamePassword(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.useHttpAuthUsernamePassword', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Handles Dart method `HttpAuthHandler.cancel`. Future<void> cancel(int arg_instanceId) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.cancel', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_instanceId]) 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; } } /// Handles Dart method `HttpAuthHandler.proceed`. Future<void> proceed( int arg_instanceId, String arg_username, String arg_password) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_instanceId, arg_username, arg_password]) 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; } } } /// Flutter API for `HttpAuthHandler`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.android.com/reference/android/webkit/HttpAuthHandler. abstract class HttpAuthHandlerFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new Dart instance and add it to the `InstanceManager`. void create(int instanceId); static void setup(HttpAuthHandlerFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerFlutterApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerFlutterApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_instanceId = (args[0] as int?); assert(arg_instanceId != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerFlutterApi.create was null, expected non-null int.'); api.create(arg_instanceId!); return; }); } } } }
packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.g.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.g.dart", "repo_id": "packages", "token_count": 50587 }
1,068