text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'billing_client_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
const _$BillingResponseEnumMap = {
BillingResponse.serviceTimeout: -3,
BillingResponse.featureNotSupported: -2,
BillingResponse.serviceDisconnected: -1,
BillingResponse.ok: 0,
BillingResponse.userCanceled: 1,
BillingResponse.serviceUnavailable: 2,
BillingResponse.billingUnavailable: 3,
BillingResponse.itemUnavailable: 4,
BillingResponse.developerError: 5,
BillingResponse.error: 6,
BillingResponse.itemAlreadyOwned: 7,
BillingResponse.itemNotOwned: 8,
};
const _$SkuTypeEnumMap = {
SkuType.inapp: 'inapp',
SkuType.subs: 'subs',
};
const _$ProrationModeEnumMap = {
ProrationMode.unknownSubscriptionUpgradeDowngradePolicy: 0,
ProrationMode.immediateWithTimeProration: 1,
ProrationMode.immediateAndChargeProratedPrice: 2,
ProrationMode.immediateWithoutProration: 3,
ProrationMode.deferred: 4,
ProrationMode.immediateAndChargeFullPrice: 5,
};
const _$BillingClientFeatureEnumMap = {
BillingClientFeature.inAppItemsOnVR: 'inAppItemsOnVr',
BillingClientFeature.priceChangeConfirmation: 'priceChangeConfirmation',
BillingClientFeature.subscriptions: 'subscriptions',
BillingClientFeature.subscriptionsOnVR: 'subscriptionsOnVr',
BillingClientFeature.subscriptionsUpdate: 'subscriptionsUpdate',
};
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.g.dart",
"repo_id": "plugins",
"token_count": 475
} | 1,169 |
// 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_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:test/test.dart';
const PurchaseWrapper dummyPurchase = PurchaseWrapper(
orderId: 'orderId',
packageName: 'packageName',
purchaseTime: 0,
signature: 'signature',
skus: <String>['sku'],
purchaseToken: 'purchaseToken',
isAutoRenewing: false,
originalJson: '',
developerPayload: 'dummy payload',
isAcknowledged: true,
purchaseState: PurchaseStateWrapper.purchased,
obfuscatedAccountId: 'Account101',
obfuscatedProfileId: 'Profile103',
);
const PurchaseWrapper dummyUnacknowledgedPurchase = PurchaseWrapper(
orderId: 'orderId',
packageName: 'packageName',
purchaseTime: 0,
signature: 'signature',
skus: <String>['sku'],
purchaseToken: 'purchaseToken',
isAutoRenewing: false,
originalJson: '',
developerPayload: 'dummy payload',
isAcknowledged: false,
purchaseState: PurchaseStateWrapper.purchased,
);
const PurchaseHistoryRecordWrapper dummyPurchaseHistoryRecord =
PurchaseHistoryRecordWrapper(
purchaseTime: 0,
signature: 'signature',
skus: <String>['sku'],
purchaseToken: 'purchaseToken',
originalJson: '',
developerPayload: 'dummy payload',
);
const PurchaseWrapper dummyOldPurchase = PurchaseWrapper(
orderId: 'oldOrderId',
packageName: 'oldPackageName',
purchaseTime: 0,
signature: 'oldSignature',
skus: <String>['oldSku'],
purchaseToken: 'oldPurchaseToken',
isAutoRenewing: false,
originalJson: '',
developerPayload: 'old dummy payload',
isAcknowledged: true,
purchaseState: PurchaseStateWrapper.purchased,
);
void main() {
group('PurchaseWrapper', () {
test('converts from map', () {
const PurchaseWrapper expected = dummyPurchase;
final PurchaseWrapper parsed =
PurchaseWrapper.fromJson(buildPurchaseMap(expected));
expect(parsed, equals(expected));
});
test('fromPurchase() should return correct PurchaseDetail object', () {
final GooglePlayPurchaseDetails details =
GooglePlayPurchaseDetails.fromPurchase(dummyPurchase);
expect(details.purchaseID, dummyPurchase.orderId);
expect(details.productID, dummyPurchase.sku);
expect(details.transactionDate, dummyPurchase.purchaseTime.toString());
expect(details.verificationData, isNotNull);
expect(details.verificationData.source, kIAPSource);
expect(details.verificationData.localVerificationData,
dummyPurchase.originalJson);
expect(details.verificationData.serverVerificationData,
dummyPurchase.purchaseToken);
expect(details.billingClientPurchase, dummyPurchase);
expect(details.pendingCompletePurchase, false);
});
test(
'fromPurchase() should return set pendingCompletePurchase to true for unacknowledged purchase',
() {
final GooglePlayPurchaseDetails details =
GooglePlayPurchaseDetails.fromPurchase(dummyUnacknowledgedPurchase);
expect(details.purchaseID, dummyPurchase.orderId);
expect(details.productID, dummyPurchase.sku);
expect(details.transactionDate, dummyPurchase.purchaseTime.toString());
expect(details.verificationData, isNotNull);
expect(details.verificationData.source, kIAPSource);
expect(details.verificationData.localVerificationData,
dummyPurchase.originalJson);
expect(details.verificationData.serverVerificationData,
dummyPurchase.purchaseToken);
expect(details.billingClientPurchase, dummyUnacknowledgedPurchase);
expect(details.pendingCompletePurchase, true);
});
});
group('PurchaseHistoryRecordWrapper', () {
test('converts from map', () {
const PurchaseHistoryRecordWrapper expected = dummyPurchaseHistoryRecord;
final PurchaseHistoryRecordWrapper parsed =
PurchaseHistoryRecordWrapper.fromJson(
buildPurchaseHistoryRecordMap(expected));
expect(parsed, equals(expected));
});
});
group('PurchasesResultWrapper', () {
test('parsed from map', () {
const BillingResponse responseCode = BillingResponse.ok;
final List<PurchaseWrapper> purchases = <PurchaseWrapper>[
dummyPurchase,
dummyPurchase
];
const String debugMessage = 'dummy Message';
const BillingResultWrapper billingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
final PurchasesResultWrapper expected = PurchasesResultWrapper(
billingResult: billingResult,
responseCode: responseCode,
purchasesList: purchases);
final PurchasesResultWrapper parsed =
PurchasesResultWrapper.fromJson(<String, dynamic>{
'billingResult': buildBillingResultMap(billingResult),
'responseCode': const BillingResponseConverter().toJson(responseCode),
'purchasesList': <Map<String, dynamic>>[
buildPurchaseMap(dummyPurchase),
buildPurchaseMap(dummyPurchase)
]
});
expect(parsed.billingResult, equals(expected.billingResult));
expect(parsed.responseCode, equals(expected.responseCode));
expect(parsed.purchasesList, containsAll(expected.purchasesList));
});
test('parsed from empty map', () {
final PurchasesResultWrapper parsed =
PurchasesResultWrapper.fromJson(const <String, dynamic>{});
expect(
parsed.billingResult,
equals(const BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidBillingResultErrorMessage)));
expect(parsed.responseCode, BillingResponse.error);
expect(parsed.purchasesList, isEmpty);
});
});
group('PurchasesHistoryResult', () {
test('parsed from map', () {
const BillingResponse responseCode = BillingResponse.ok;
final List<PurchaseHistoryRecordWrapper> purchaseHistoryRecordList =
<PurchaseHistoryRecordWrapper>[
dummyPurchaseHistoryRecord,
dummyPurchaseHistoryRecord
];
const String debugMessage = 'dummy Message';
const BillingResultWrapper billingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
final PurchasesHistoryResult expected = PurchasesHistoryResult(
billingResult: billingResult,
purchaseHistoryRecordList: purchaseHistoryRecordList);
final PurchasesHistoryResult parsed =
PurchasesHistoryResult.fromJson(<String, dynamic>{
'billingResult': buildBillingResultMap(billingResult),
'purchaseHistoryRecordList': <Map<String, dynamic>>[
buildPurchaseHistoryRecordMap(dummyPurchaseHistoryRecord),
buildPurchaseHistoryRecordMap(dummyPurchaseHistoryRecord)
]
});
expect(parsed.billingResult, equals(billingResult));
expect(parsed.purchaseHistoryRecordList,
containsAll(expected.purchaseHistoryRecordList));
});
test('parsed from empty map', () {
final PurchasesHistoryResult parsed =
PurchasesHistoryResult.fromJson(const <String, dynamic>{});
expect(
parsed.billingResult,
equals(const BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidBillingResultErrorMessage)));
expect(parsed.purchaseHistoryRecordList, isEmpty);
});
});
}
Map<String, dynamic> buildPurchaseMap(PurchaseWrapper original) {
return <String, dynamic>{
'orderId': original.orderId,
'packageName': original.packageName,
'purchaseTime': original.purchaseTime,
'signature': original.signature,
'skus': original.skus,
'purchaseToken': original.purchaseToken,
'isAutoRenewing': original.isAutoRenewing,
'originalJson': original.originalJson,
'developerPayload': original.developerPayload,
'purchaseState':
const PurchaseStateConverter().toJson(original.purchaseState),
'isAcknowledged': original.isAcknowledged,
'obfuscatedAccountId': original.obfuscatedAccountId,
'obfuscatedProfileId': original.obfuscatedProfileId,
};
}
Map<String, dynamic> buildPurchaseHistoryRecordMap(
PurchaseHistoryRecordWrapper original) {
return <String, dynamic>{
'purchaseTime': original.purchaseTime,
'signature': original.signature,
'skus': original.skus,
'purchaseToken': original.purchaseToken,
'originalJson': original.originalJson,
'developerPayload': original.developerPayload,
};
}
Map<String, dynamic> buildBillingResultMap(BillingResultWrapper original) {
return <String, dynamic>{
'responseCode':
const BillingResponseConverter().toJson(original.responseCode),
'debugMessage': original.debugMessage,
};
}
| plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart",
"repo_id": "plugins",
"token_count": 3115
} | 1,170 |
// 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 'in_app_purchase_platform_addition.dart';
/// The [InAppPurchasePlatformAdditionProvider] is responsible for providing
/// a platform-specific [InAppPurchasePlatformAddition].
///
/// [InAppPurchasePlatformAddition] implementation contain platform-specific
/// features that are not available from the platform idiomatic
/// [InAppPurchasePlatform] API.
abstract class InAppPurchasePlatformAdditionProvider {
/// Provides a platform-specific implementation of the [InAppPurchasePlatformAddition]
/// class.
T getPlatformAddition<T extends InAppPurchasePlatformAddition?>();
}
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform_addition_provider.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform_addition_provider.dart",
"repo_id": "plugins",
"token_count": 187
} | 1,171 |
# in\_app\_purchase\_storekit
The iOS and macOS implementation of [`in_app_purchase`][1].
## Usage
This package has been [endorsed][2], meaning that you only need to add `in_app_purchase`
as a dependency in your `pubspec.yaml`. This package will be automatically included in your app
when you do.
If you wish to use this package only, you can [add `in_app_purchase_storekit` directly][3].
## 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/plugins/blob/main/CONTRIBUTING.md).
[1]: ../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_storekit/install
| plugins/packages/in_app_purchase/in_app_purchase_storekit/README.md/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/README.md",
"repo_id": "plugins",
"token_count": 355
} | 1,172 |
#include "../../Flutter/Flutter-Release.xcconfig"
| plugins/packages/in_app_purchase/in_app_purchase_storekit/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 19
} | 1,173 |
// 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:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'fakes/fake_storekit_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform, fakeStoreKitPlatform.onMethodCall);
});
group('present code redemption sheet', () {
test('null', () async {
expect(
InAppPurchaseStoreKitPlatformAddition().presentCodeRedemptionSheet(),
completes);
});
});
group('refresh receipt data', () {
test('should refresh receipt data', () async {
final PurchaseVerificationData? receiptData =
await InAppPurchaseStoreKitPlatformAddition()
.refreshPurchaseVerificationData();
expect(receiptData, isNotNull);
expect(receiptData!.source, kIAPSource);
expect(receiptData.localVerificationData, 'refreshed receipt data');
expect(receiptData.serverVerificationData, 'refreshed receipt data');
});
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart",
"repo_id": "plugins",
"token_count": 606
} | 1,174 |
{
"images" : [
{
"idiom" : "universal",
"filename" : "flutter.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | plugins/packages/ios_platform_images/example/ios/Runner/Assets.xcassets/flutter.imageset/Contents.json/0 | {
"file_path": "plugins/packages/ios_platform_images/example/ios/Runner/Assets.xcassets/flutter.imageset/Contents.json",
"repo_id": "plugins",
"token_count": 194
} | 1,175 |
// 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 "IosPlatformImagesPlugin.h"
#if !__has_feature(objc_arc)
#error ARC must be enabled!
#endif
@interface IosPlatformImagesPlugin ()
@end
@implementation IosPlatformImagesPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/ios_platform_images"
binaryMessenger:[registrar messenger]];
[channel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
if ([@"loadImage" isEqualToString:call.method]) {
NSString *name = call.arguments;
UIImage *image = [UIImage imageNamed:name];
NSData *data = UIImagePNGRepresentation(image);
if (data) {
result(@{
@"scale" : @(image.scale),
@"data" : [FlutterStandardTypedData typedDataWithBytes:data],
});
} else {
result(nil);
}
return;
} else if ([@"resolveURL" isEqualToString:call.method]) {
NSArray *args = call.arguments;
NSString *name = args[0];
NSString *extension = (args[1] == (id)NSNull.null) ? nil : args[1];
NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:extension];
result(url.absoluteString);
return;
}
result(FlutterMethodNotImplemented);
}];
}
@end
| plugins/packages/ios_platform_images/ios/Classes/IosPlatformImagesPlugin.m/0 | {
"file_path": "plugins/packages/ios_platform_images/ios/Classes/IosPlatformImagesPlugin.m",
"repo_id": "plugins",
"token_count": 604
} | 1,176 |
// 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 is a temporary ignore to allow us to land a new set of linter rules in a
// series of manageable patches instead of one gigantic PR. It disables some of
// the new lints that are already failing on this plugin, for this plugin. It
// should be deleted and the failing lints addressed as soon as possible.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';
import 'package:local_auth_windows/local_auth_windows.dart';
/// A Flutter plugin for authenticating the user identity locally.
class LocalAuthentication {
/// Authenticates the user with biometrics available on the device while also
/// allowing the user to use device authentication - pin, pattern, passcode.
///
/// Returns true if the user successfully authenticated, false otherwise.
///
/// [localizedReason] is the message to show to user while prompting them
/// for authentication. This is typically along the lines of: 'Authenticate
/// to access MyApp.'. This must not be empty.
///
/// Provide [authMessages] if you want to
/// customize messages in the dialogs.
///
/// Provide [options] for configuring further authentication related options.
///
/// Throws a [PlatformException] if there were technical problems with local
/// authentication (e.g. lack of relevant hardware). This might throw
/// [PlatformException] with error code [otherOperatingSystem] on the iOS
/// simulator.
Future<bool> authenticate(
{required String localizedReason,
Iterable<AuthMessages> authMessages = const <AuthMessages>[
IOSAuthMessages(),
AndroidAuthMessages(),
WindowsAuthMessages()
],
AuthenticationOptions options = const AuthenticationOptions()}) {
return LocalAuthPlatform.instance.authenticate(
localizedReason: localizedReason,
authMessages: authMessages,
options: options,
);
}
/// Cancels any in-progress authentication, returning true if auth was
/// cancelled successfully.
///
/// This API is not supported by all platforms.
/// Returns false if there was some error, no authentication in progress,
/// or the current platform lacks support.
Future<bool> stopAuthentication() async {
return LocalAuthPlatform.instance.stopAuthentication();
}
/// Returns true if device is capable of checking biometrics.
Future<bool> get canCheckBiometrics =>
LocalAuthPlatform.instance.deviceSupportsBiometrics();
/// Returns true if device is capable of checking biometrics or is able to
/// fail over to device credentials.
Future<bool> isDeviceSupported() async =>
LocalAuthPlatform.instance.isDeviceSupported();
/// Returns a list of enrolled biometrics.
Future<List<BiometricType>> getAvailableBiometrics() =>
LocalAuthPlatform.instance.getEnrolledBiometrics();
}
| plugins/packages/local_auth/local_auth/lib/src/local_auth.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth/lib/src/local_auth.dart",
"repo_id": "plugins",
"token_count": 879
} | 1,177 |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M9,16.2L4.8,12l-1.4,1.4L9,19 21,7l-1.4,-1.4L9,16.2z"/>
</vector>
| plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/ic_done_white_24dp.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/ic_done_white_24dp.xml",
"repo_id": "plugins",
"token_count": 175
} | 1,178 |
// 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:local_auth_android/local_auth_android.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('LocalAuth', () {
const MethodChannel channel = MethodChannel(
'plugins.flutter.io/local_auth_android',
);
final List<MethodCall> log = <MethodCall>[];
late LocalAuthAndroid localAuthentication;
setUp(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) {
log.add(methodCall);
switch (methodCall.method) {
case 'getEnrolledBiometrics':
return Future<List<String>>.value(<String>['weak', 'strong']);
default:
return Future<dynamic>.value(true);
}
});
localAuthentication = LocalAuthAndroid();
log.clear();
});
test('deviceSupportsBiometrics calls platform', () async {
final bool result = await localAuthentication.deviceSupportsBiometrics();
expect(
log,
<Matcher>[
isMethodCall('deviceSupportsBiometrics', arguments: null),
],
);
expect(result, true);
});
test('getEnrolledBiometrics calls platform', () async {
final List<BiometricType> result =
await localAuthentication.getEnrolledBiometrics();
expect(
log,
<Matcher>[
isMethodCall('getEnrolledBiometrics', arguments: null),
],
);
expect(result, <BiometricType>[
BiometricType.weak,
BiometricType.strong,
]);
});
test('isDeviceSupported calls platform', () async {
await localAuthentication.isDeviceSupported();
expect(
log,
<Matcher>[
isMethodCall('isDeviceSupported', arguments: null),
],
);
});
test('stopAuthentication calls platform', () async {
await localAuthentication.stopAuthentication();
expect(
log,
<Matcher>[
isMethodCall('stopAuthentication', arguments: null),
],
);
});
group('With device auth fail over', () {
test('authenticate with no args.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const AndroidAuthMessages()],
localizedReason: 'Needs secure',
options: const AuthenticationOptions(biometricOnly: true),
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Needs secure',
'useErrorDialogs': true,
'stickyAuth': false,
'sensitiveTransaction': true,
'biometricOnly': true,
}..addAll(const AndroidAuthMessages().args)),
],
);
});
test('authenticate with no sensitive transaction.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const AndroidAuthMessages()],
localizedReason: 'Insecure',
options: const AuthenticationOptions(
sensitiveTransaction: false,
useErrorDialogs: false,
biometricOnly: true,
),
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Insecure',
'useErrorDialogs': false,
'stickyAuth': false,
'sensitiveTransaction': false,
'biometricOnly': true,
}..addAll(const AndroidAuthMessages().args)),
],
);
});
});
group('With biometrics only', () {
test('authenticate with no args.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const AndroidAuthMessages()],
localizedReason: 'Needs secure',
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Needs secure',
'useErrorDialogs': true,
'stickyAuth': false,
'sensitiveTransaction': true,
'biometricOnly': false,
}..addAll(const AndroidAuthMessages().args)),
],
);
});
test('authenticate with no sensitive transaction.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const AndroidAuthMessages()],
localizedReason: 'Insecure',
options: const AuthenticationOptions(
sensitiveTransaction: false,
useErrorDialogs: false,
),
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Insecure',
'useErrorDialogs': false,
'stickyAuth': false,
'sensitiveTransaction': false,
'biometricOnly': false,
}..addAll(const AndroidAuthMessages().args)),
],
);
});
});
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/local_auth/local_auth_android/test/local_auth_test.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/test/local_auth_test.dart",
"repo_id": "plugins",
"token_count": 2624
} | 1,179 |
name: local_auth_ios
description: iOS implementation of the local_auth plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/local_auth/local_auth_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
version: 1.0.12
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: local_auth
platforms:
ios:
pluginClass: FLTLocalAuthPlugin
dartPluginClass: LocalAuthIOS
dependencies:
flutter:
sdk: flutter
intl: ">=0.17.0 <0.19.0"
local_auth_platform_interface: ^1.0.1
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/local_auth/local_auth_ios/pubspec.yaml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_ios/pubspec.yaml",
"repo_id": "plugins",
"token_count": 290
} | 1,180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Path Provider',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Path Provider'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final PathProviderPlatform provider = PathProviderPlatform.instance;
Future<String?>? _tempDirectory;
Future<String?>? _appSupportDirectory;
Future<String?>? _appDocumentsDirectory;
Future<String?>? _externalDocumentsDirectory;
Future<List<String>?>? _externalStorageDirectories;
Future<List<String>?>? _externalCacheDirectories;
void _requestTempDirectory() {
setState(() {
_tempDirectory = provider.getTemporaryPath();
});
}
Widget _buildDirectory(
BuildContext context, AsyncSnapshot<String?> snapshot) {
Text text = const Text('');
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
text = Text('path: ${snapshot.data}');
} else {
text = const Text('path unavailable');
}
}
return Padding(padding: const EdgeInsets.all(16.0), child: text);
}
Widget _buildDirectories(
BuildContext context, AsyncSnapshot<List<String>?> snapshot) {
Text text = const Text('');
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
final String combined = snapshot.data!.join(', ');
text = Text('paths: $combined');
} else {
text = const Text('path unavailable');
}
}
return Padding(padding: const EdgeInsets.all(16.0), child: text);
}
void _requestAppDocumentsDirectory() {
setState(() {
_appDocumentsDirectory = provider.getApplicationDocumentsPath();
});
}
void _requestAppSupportDirectory() {
setState(() {
_appSupportDirectory = provider.getApplicationSupportPath();
});
}
void _requestExternalStorageDirectory() {
setState(() {
_externalDocumentsDirectory = provider.getExternalStoragePath();
});
}
void _requestExternalStorageDirectories(StorageDirectory type) {
setState(() {
_externalStorageDirectories =
provider.getExternalStoragePaths(type: type);
});
}
void _requestExternalCacheDirectories() {
setState(() {
_externalCacheDirectories = provider.getExternalCachePaths();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestTempDirectory,
child: const Text('Get Temporary Directory'),
),
),
FutureBuilder<String?>(
future: _tempDirectory, builder: _buildDirectory),
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestAppDocumentsDirectory,
child: const Text('Get Application Documents Directory'),
),
),
FutureBuilder<String?>(
future: _appDocumentsDirectory, builder: _buildDirectory),
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestAppSupportDirectory,
child: const Text('Get Application Support Directory'),
),
),
FutureBuilder<String?>(
future: _appSupportDirectory, builder: _buildDirectory),
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestExternalStorageDirectory,
child: const Text('Get External Storage Directory'),
),
),
FutureBuilder<String?>(
future: _externalDocumentsDirectory, builder: _buildDirectory),
Column(children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
child: const Text('Get External Storage Directories'),
onPressed: () {
_requestExternalStorageDirectories(
StorageDirectory.music,
);
},
),
),
]),
FutureBuilder<List<String>?>(
future: _externalStorageDirectories,
builder: _buildDirectories),
Column(children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestExternalCacheDirectories,
child: const Text('Get External Cache Directories'),
),
),
]),
FutureBuilder<List<String>?>(
future: _externalCacheDirectories, builder: _buildDirectories),
],
),
),
);
}
}
| plugins/packages/path_provider/path_provider_android/example/lib/main.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 2610
} | 1,181 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,182 |
org.gradle.jvmargs=-Xmx4G
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/quick_actions/quick_actions/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,183 |
// 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:quick_actions_android/quick_actions_android.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$QuickActionsAndroid', () {
late List<MethodCall> log;
setUp(() {
log = <MethodCall>[];
});
QuickActionsAndroid buildQuickActionsPlugin() {
final QuickActionsAndroid quickActions = QuickActionsAndroid();
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(quickActions.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return '';
});
return quickActions;
}
test('registerWith() registers correct instance', () {
QuickActionsAndroid.registerWith();
expect(QuickActionsPlatform.instance, isA<QuickActionsAndroid>());
});
group('#initialize', () {
test('passes getLaunchAction on launch method', () {
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
});
test('initialize', () async {
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
final Completer<bool> quickActionsHandler = Completer<bool>();
await quickActions
.initialize((_) => quickActionsHandler.complete(true));
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
log.clear();
expect(quickActionsHandler.future, completion(isTrue));
});
});
group('#setShortCutItems', () {
test('passes shortcutItem through channel', () {
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
quickActions.setShortcutItems(<ShortcutItem>[
const ShortcutItem(
type: 'test', localizedTitle: 'title', icon: 'icon.svg')
]);
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('setShortcutItems', arguments: <Map<String, String>>[
<String, String>{
'type': 'test',
'localizedTitle': 'title',
'icon': 'icon.svg',
}
]),
],
);
});
test('setShortcutItems with demo data', () async {
const String type = 'type';
const String localizedTitle = 'localizedTitle';
const String icon = 'icon';
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
await quickActions.setShortcutItems(
const <ShortcutItem>[
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon)
],
);
expect(
log,
<Matcher>[
isMethodCall(
'setShortcutItems',
arguments: <Map<String, String>>[
<String, String>{
'type': type,
'localizedTitle': localizedTitle,
'icon': icon,
}
],
),
],
);
log.clear();
});
});
group('#clearShortCutItems', () {
test('send clearShortcutItems through channel', () {
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('clearShortcutItems', arguments: null),
],
);
});
test('clearShortcutItems', () {
final QuickActionsAndroid quickActions = buildQuickActionsPlugin();
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('clearShortcutItems', arguments: null),
],
);
log.clear();
});
});
});
group('$ShortcutItem', () {
test('Shortcut item can be constructed', () {
const String type = 'type';
const String localizedTitle = 'title';
const String icon = 'foo';
const ShortcutItem item =
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon);
expect(item.type, type);
expect(item.localizedTitle, localizedTitle);
expect(item.icon, icon);
});
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart",
"repo_id": "plugins",
"token_count": 2266
} | 1,184 |
<?xml version="1.0" encoding="UTF-8"?>
<issues format="5" by="lint 4.1.0" client="gradle" variant="debug" version="4.1.0">
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" commitAsync(preferences.edit().putBoolean(key, (boolean) call.argument("value")), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="66"
column="23"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" commitAsync(preferences.edit().putString(key, DOUBLE_PREFIX + doubleValueStr), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="71"
column="23"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" preferences"
errorLine2=" ^">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="78"
column="17"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" commitAsync(preferences.edit().putLong(key, number.longValue()), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="84"
column="25"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" commitAsync(preferences.edit().putString(key, value), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="96"
column="23"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" preferences.edit().putString(key, LIST_IDENTIFIER + encodeList(list)), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="101"
column="15"/>
</issue>
<issue
id="CommitPrefEdits"
message="`SharedPreferences.edit()` without a corresponding `commit()` or `apply()` call"
errorLine1=" commitAsync(preferences.edit().remove(key), result);"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java"
line="111"
column="23"/>
</issue>
</issues>
| plugins/packages/shared_preferences/shared_preferences_android/android/lint-baseline.xml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/android/lint-baseline.xml",
"repo_id": "plugins",
"token_count": 1607
} | 1,185 |
// 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:shared_preferences_foundation/shared_preferences_foundation.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'test_api.g.dart';
class _MockSharedPreferencesApi implements TestUserDefaultsApi {
final Map<String, Object> items = <String, Object>{};
@override
Map<String?, Object?> getAll() {
return items;
}
@override
void remove(String key) {
items.remove(key);
}
@override
void setBool(String key, bool value) {
items[key] = value;
}
@override
void setDouble(String key, double value) {
items[key] = value;
}
@override
void setValue(String key, Object value) {
items[key] = value;
}
@override
void clear() {
items.clear();
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _MockSharedPreferencesApi api;
setUp(() {
api = _MockSharedPreferencesApi();
TestUserDefaultsApi.setup(api);
});
test('registerWith', () {
SharedPreferencesFoundation.registerWith();
expect(SharedPreferencesStorePlatform.instance,
isA<SharedPreferencesFoundation>());
});
test('remove', () async {
final SharedPreferencesFoundation plugin = SharedPreferencesFoundation();
api.items['flutter.hi'] = 'world';
expect(await plugin.remove('flutter.hi'), isTrue);
expect(api.items.containsKey('flutter.hi'), isFalse);
});
test('clear', () async {
final SharedPreferencesFoundation plugin = SharedPreferencesFoundation();
api.items['flutter.hi'] = 'world';
expect(await plugin.clear(), isTrue);
expect(api.items.containsKey('flutter.hi'), isFalse);
});
test('getAll', () async {
final SharedPreferencesFoundation plugin = SharedPreferencesFoundation();
api.items['flutter.aBool'] = true;
api.items['flutter.aDouble'] = 3.14;
api.items['flutter.anInt'] = 42;
api.items['flutter.aString'] = 'hello world';
api.items['flutter.aStringList'] = <String>['hello', 'world'];
final Map<String?, Object?> all = await plugin.getAll();
expect(all.length, 5);
expect(all['flutter.aBool'], api.items['flutter.aBool']);
expect(all['flutter.aDouble'],
closeTo(api.items['flutter.aDouble']! as num, 0.0001));
expect(all['flutter.anInt'], api.items['flutter.anInt']);
expect(all['flutter.aString'], api.items['flutter.aString']);
expect(all['flutter.aStringList'], api.items['flutter.aStringList']);
});
test('setValue', () async {
final SharedPreferencesFoundation plugin = SharedPreferencesFoundation();
expect(await plugin.setValue('Bool', 'flutter.Bool', true), isTrue);
expect(api.items['flutter.Bool'], true);
expect(await plugin.setValue('Double', 'flutter.Double', 1.5), isTrue);
expect(api.items['flutter.Double'], 1.5);
expect(await plugin.setValue('Int', 'flutter.Int', 12), isTrue);
expect(api.items['flutter.Int'], 12);
expect(await plugin.setValue('String', 'flutter.String', 'hi'), isTrue);
expect(api.items['flutter.String'], 'hi');
expect(
await plugin
.setValue('StringList', 'flutter.StringList', <String>['hi']),
isTrue);
expect(api.items['flutter.StringList'], <String>['hi']);
});
test('setValue with unsupported type', () {
final SharedPreferencesFoundation plugin = SharedPreferencesFoundation();
expect(() async {
await plugin.setValue('Map', 'flutter.key', <String, String>{});
}, throwsA(isA<PlatformException>()));
});
}
| plugins/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart",
"repo_id": "plugins",
"token_count": 1361
} | 1,186 |
// 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:shared_preferences_platform_interface/method_channel_shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group(MethodChannelSharedPreferencesStore, () {
const MethodChannel channel = MethodChannel(
'plugins.flutter.io/shared_preferences',
);
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.Bool': true,
'flutter.Int': 42,
'flutter.Double': 3.14159,
'flutter.StringList': <String>['foo', 'bar'],
};
late InMemorySharedPreferencesStore testData;
final List<MethodCall> log = <MethodCall>[];
late MethodChannelSharedPreferencesStore store;
setUp(() async {
testData = InMemorySharedPreferencesStore.empty();
Map<String, Object?> getArgumentDictionary(MethodCall call) {
return (call.arguments as Map<Object?, Object?>)
.cast<String, Object?>();
}
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
log.add(methodCall);
if (methodCall.method == 'getAll') {
return testData.getAll();
}
if (methodCall.method == 'remove') {
final Map<String, Object?> arguments =
getArgumentDictionary(methodCall);
final String key = arguments['key']! as String;
return testData.remove(key);
}
if (methodCall.method == 'clear') {
return testData.clear();
}
final RegExp setterRegExp = RegExp(r'set(.*)');
final Match? match = setterRegExp.matchAsPrefix(methodCall.method);
if (match?.groupCount == 1) {
final String valueType = match!.group(1)!;
final Map<String, Object?> arguments =
getArgumentDictionary(methodCall);
final String key = arguments['key']! as String;
final Object value = arguments['value']!;
return testData.setValue(valueType, key, value);
}
fail('Unexpected method call: ${methodCall.method}');
});
store = MethodChannelSharedPreferencesStore();
log.clear();
});
tearDown(() async {
await testData.clear();
});
test('getAll', () async {
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await store.getAll(), kTestValues);
expect(log.single.method, 'getAll');
});
test('remove', () async {
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await store.remove('flutter.String'), true);
expect(await store.remove('flutter.Bool'), true);
expect(await store.remove('flutter.Int'), true);
expect(await store.remove('flutter.Double'), true);
expect(await testData.getAll(), <String, dynamic>{
'flutter.StringList': <String>['foo', 'bar'],
});
expect(log, hasLength(4));
for (final MethodCall call in log) {
expect(call.method, 'remove');
}
});
test('setValue', () async {
expect(await testData.getAll(), isEmpty);
for (final String key in kTestValues.keys) {
final Object value = kTestValues[key]!;
expect(await store.setValue(key.split('.').last, key, value), true);
}
expect(await testData.getAll(), kTestValues);
expect(log, hasLength(5));
expect(log[0].method, 'setString');
expect(log[1].method, 'setBool');
expect(log[2].method, 'setInt');
expect(log[3].method, 'setDouble');
expect(log[4].method, 'setStringList');
});
test('clear', () async {
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await testData.getAll(), isNotEmpty);
expect(await store.clear(), true);
expect(await testData.getAll(), isEmpty);
expect(log.single.method, 'clear');
});
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/shared_preferences/shared_preferences_platform_interface/test/method_channel_shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/test/method_channel_shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 1789
} | 1,187 |
// 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.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#105648)
// ignore: unnecessary_import
import 'dart:ui' show Brightness;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_test/flutter_test.dart';
import 'package:url_launcher/src/legacy_api.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../mocks/mock_url_launcher_platform.dart';
void main() {
final MockUrlLauncher mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
test('closeWebView default behavior', () async {
await closeWebView();
expect(mock.closeWebViewCalled, isTrue);
});
group('canLaunch', () {
test('returns true', () async {
mock
..setCanLaunchExpectations('foo')
..setResponse(true);
final bool result = await canLaunch('foo');
expect(result, isTrue);
});
test('returns false', () async {
mock
..setCanLaunchExpectations('foo')
..setResponse(false);
final bool result = await canLaunch('foo');
expect(result, isFalse);
});
});
group('launch', () {
test('default behavior', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(await launch('http://flutter.dev/'), isTrue);
});
test('with headers', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{'key': 'value'},
webOnlyWindowName: null,
)
..setResponse(true);
expect(
await launch(
'http://flutter.dev/',
headers: <String, String>{'key': 'value'},
),
isTrue);
});
test('force SafariVC', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(await launch('http://flutter.dev/', forceSafariVC: true), isTrue);
});
test('universal links only', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: true,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(
await launch('http://flutter.dev/',
forceSafariVC: false, universalLinksOnly: true),
isTrue);
});
test('force WebView', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: true,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(await launch('http://flutter.dev/', forceWebView: true), isTrue);
});
test('force WebView enable javascript', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: true,
enableJavaScript: true,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(
await launch('http://flutter.dev/',
forceWebView: true, enableJavaScript: true),
isTrue);
});
test('force WebView enable DOM storage', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: true,
enableJavaScript: false,
enableDomStorage: true,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(
await launch('http://flutter.dev/',
forceWebView: true, enableDomStorage: true),
isTrue);
});
test('force SafariVC to false', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(await launch('http://flutter.dev/', forceSafariVC: false), isTrue);
});
test('cannot launch a non-web in webview', () async {
expect(() async => launch('tel:555-555-5555', forceWebView: true),
throwsA(isA<PlatformException>()));
});
test('send e-mail', () async {
mock
..setLaunchExpectations(
url: 'mailto:[email protected]?subject=Hello',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(await launch('mailto:[email protected]?subject=Hello'),
isTrue);
});
test('cannot send e-mail with forceSafariVC: true', () async {
expect(
() async => launch('mailto:[email protected]?subject=Hello',
forceSafariVC: true),
throwsA(isA<PlatformException>()));
});
test('cannot send e-mail with forceWebView: true', () async {
expect(
() async => launch('mailto:[email protected]?subject=Hello',
forceWebView: true),
throwsA(isA<PlatformException>()));
});
test('controls system UI when changing statusBarBrightness', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
final TestWidgetsFlutterBinding binding =
_anonymize(TestWidgetsFlutterBinding.ensureInitialized())!
as TestWidgetsFlutterBinding;
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
binding.renderView.automaticSystemUiAdjustment = true;
final Future<bool> launchResult =
launch('http://flutter.dev/', statusBarBrightness: Brightness.dark);
// Should take over control of the automaticSystemUiAdjustment while it's
// pending, then restore it back to normal after the launch finishes.
expect(binding.renderView.automaticSystemUiAdjustment, isFalse);
await launchResult;
expect(binding.renderView.automaticSystemUiAdjustment, isTrue);
});
test('sets automaticSystemUiAdjustment to not be null', () async {
mock
..setLaunchExpectations(
url: 'http://flutter.dev/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
final TestWidgetsFlutterBinding binding =
_anonymize(TestWidgetsFlutterBinding.ensureInitialized())!
as TestWidgetsFlutterBinding;
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(binding.renderView.automaticSystemUiAdjustment, true);
final Future<bool> launchResult =
launch('http://flutter.dev/', statusBarBrightness: Brightness.dark);
// The automaticSystemUiAdjustment should be set before the launch
// and equal to true after the launch result is complete.
expect(binding.renderView.automaticSystemUiAdjustment, true);
await launchResult;
expect(binding.renderView.automaticSystemUiAdjustment, true);
});
test('open non-parseable url', () async {
mock
..setLaunchExpectations(
url:
'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
expect(
await launch(
'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'),
isTrue);
});
test('cannot open non-parseable url with forceSafariVC: true', () async {
expect(
() async => launch(
'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1',
forceSafariVC: true),
throwsA(isA<PlatformException>()));
});
test('cannot open non-parseable url with forceWebView: true', () async {
expect(
() async => launch(
'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1',
forceWebView: true),
throwsA(isA<PlatformException>()));
});
});
}
/// This removes the type information from a value so that it can be cast
/// to another type even if that cast is redundant.
/// We use this so that APIs whose type have become more descriptive can still
/// be used on the stable branch where they require a cast.
Object? _anonymize<T>(T? value) => value;
| plugins/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart",
"repo_id": "plugins",
"token_count": 4675
} | 1,188 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/url_launcher_linux/url_launcher_plugin.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <cstring>
#include "url_launcher_plugin_private.h"
// See url_launcher_channel.dart for documentation.
const char kChannelName[] = "plugins.flutter.io/url_launcher_linux";
const char kBadArgumentsError[] = "Bad Arguments";
const char kLaunchError[] = "Launch Error";
const char kCanLaunchMethod[] = "canLaunch";
const char kLaunchMethod[] = "launch";
const char kUrlKey[] = "url";
struct _FlUrlLauncherPlugin {
GObject parent_instance;
FlPluginRegistrar* registrar;
// Connection to Flutter engine.
FlMethodChannel* channel;
};
G_DEFINE_TYPE(FlUrlLauncherPlugin, fl_url_launcher_plugin, g_object_get_type())
// Gets the URL from the arguments or generates an error.
static gchar* get_url(FlValue* args, GError** error) {
if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) {
g_set_error(error, 0, 0, "Argument map missing or malformed");
return nullptr;
}
FlValue* url_value = fl_value_lookup_string(args, kUrlKey);
if (url_value == nullptr) {
g_set_error(error, 0, 0, "Missing URL");
return nullptr;
}
return g_strdup(fl_value_get_string(url_value));
}
// Checks if URI has launchable file resource.
static gboolean can_launch_uri_with_file_resource(FlUrlLauncherPlugin* self,
const gchar* url) {
g_autoptr(GError) error = nullptr;
g_autoptr(GFile) file = g_file_new_for_uri(url);
g_autoptr(GAppInfo) app_info =
g_file_query_default_handler(file, NULL, &error);
return app_info != nullptr;
}
// Called to check if a URL can be launched.
FlMethodResponse* can_launch(FlUrlLauncherPlugin* self, FlValue* args) {
g_autoptr(GError) error = nullptr;
g_autofree gchar* url = get_url(args, &error);
if (url == nullptr) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, error->message, nullptr));
}
gboolean is_launchable = FALSE;
g_autofree gchar* scheme = g_uri_parse_scheme(url);
if (scheme != nullptr) {
g_autoptr(GAppInfo) app_info =
g_app_info_get_default_for_uri_scheme(scheme);
is_launchable = app_info != nullptr;
if (!is_launchable) {
is_launchable = can_launch_uri_with_file_resource(self, url);
}
}
g_autoptr(FlValue) result = fl_value_new_bool(is_launchable);
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
// Called when a URL should launch.
static FlMethodResponse* launch(FlUrlLauncherPlugin* self, FlValue* args) {
g_autoptr(GError) error = nullptr;
g_autofree gchar* url = get_url(args, &error);
if (url == nullptr) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, error->message, nullptr));
}
FlView* view = fl_plugin_registrar_get_view(self->registrar);
gboolean launched;
if (view != nullptr) {
GtkWindow* window = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(view)));
launched = gtk_show_uri_on_window(window, url, GDK_CURRENT_TIME, &error);
} else {
launched = g_app_info_launch_default_for_uri(url, nullptr, &error);
}
if (!launched) {
g_autofree gchar* message =
g_strdup_printf("Failed to launch URL: %s", error->message);
return FL_METHOD_RESPONSE(
fl_method_error_response_new(kLaunchError, message, nullptr));
}
g_autoptr(FlValue) result = fl_value_new_bool(TRUE);
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
// Called when a method call is received from Flutter.
static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
gpointer user_data) {
FlUrlLauncherPlugin* self = FL_URL_LAUNCHER_PLUGIN(user_data);
const gchar* method = fl_method_call_get_name(method_call);
FlValue* args = fl_method_call_get_args(method_call);
g_autoptr(FlMethodResponse) response = nullptr;
if (strcmp(method, kCanLaunchMethod) == 0)
response = can_launch(self, args);
else if (strcmp(method, kLaunchMethod) == 0)
response = launch(self, args);
else
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
g_autoptr(GError) error = nullptr;
if (!fl_method_call_respond(method_call, response, &error))
g_warning("Failed to send method call response: %s", error->message);
}
static void fl_url_launcher_plugin_dispose(GObject* object) {
FlUrlLauncherPlugin* self = FL_URL_LAUNCHER_PLUGIN(object);
g_clear_object(&self->registrar);
g_clear_object(&self->channel);
G_OBJECT_CLASS(fl_url_launcher_plugin_parent_class)->dispose(object);
}
static void fl_url_launcher_plugin_class_init(FlUrlLauncherPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_url_launcher_plugin_dispose;
}
FlUrlLauncherPlugin* fl_url_launcher_plugin_new(FlPluginRegistrar* registrar) {
FlUrlLauncherPlugin* self = FL_URL_LAUNCHER_PLUGIN(
g_object_new(fl_url_launcher_plugin_get_type(), nullptr));
self->registrar = FL_PLUGIN_REGISTRAR(g_object_ref(registrar));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
self->channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
kChannelName, FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(self->channel, method_call_cb,
g_object_ref(self), g_object_unref);
return self;
}
static void fl_url_launcher_plugin_init(FlUrlLauncherPlugin* self) {}
void url_launcher_plugin_register_with_registrar(FlPluginRegistrar* registrar) {
FlUrlLauncherPlugin* plugin = fl_url_launcher_plugin_new(registrar);
g_object_unref(plugin);
}
| plugins/packages/url_launcher/url_launcher_linux/linux/url_launcher_plugin.cc/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/linux/url_launcher_plugin.cc",
"repo_id": "plugins",
"token_count": 2297
} | 1,189 |
# url_launcher_platform_interface
A common platform interface for the [`url_launcher`][1] plugin.
This interface allows platform-specific implementations of the `url_launcher`
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.
# Usage
To implement a new platform-specific implementation of `url_launcher`, extend
[`UrlLauncherPlatform`][2] with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the default
`UrlLauncherPlatform` by calling
`UrlLauncherPlatform.instance = MyPlatformUrlLauncher()`.
# 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]: ../url_launcher
[2]: lib/url_launcher_platform_interface.dart
| plugins/packages/url_launcher/url_launcher_platform_interface/README.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/README.md",
"repo_id": "plugins",
"token_count": 246
} | 1,190 |
// 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:html' as html;
import 'dart:js_util';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:integration_test/integration_test.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_web/src/link.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Link Widget', () {
testWidgets('creates anchor with correct attributes',
(WidgetTester tester) async {
final Uri uri = Uri.parse('http://foobar/example?q=1');
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: WebLinkDelegate(TestLinkInfo(
uri: uri,
target: LinkTarget.blank,
builder: (BuildContext context, FollowLink? followLink) {
return const SizedBox(width: 100, height: 100);
},
)),
));
// Platform view creation happens asynchronously.
await tester.pumpAndSettle();
final html.Element anchor = _findSingleAnchor();
expect(anchor.getAttribute('href'), uri.toString());
expect(anchor.getAttribute('target'), '_blank');
final Uri uri2 = Uri.parse('http://foobar2/example?q=2');
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: WebLinkDelegate(TestLinkInfo(
uri: uri2,
target: LinkTarget.self,
builder: (BuildContext context, FollowLink? followLink) {
return const SizedBox(width: 100, height: 100);
},
)),
));
await tester.pumpAndSettle();
// Check that the same anchor has been updated.
expect(anchor.getAttribute('href'), uri2.toString());
expect(anchor.getAttribute('target'), '_self');
final Uri uri3 = Uri.parse('/foobar');
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: WebLinkDelegate(TestLinkInfo(
uri: uri3,
target: LinkTarget.self,
builder: (BuildContext context, FollowLink? followLink) {
return const SizedBox(width: 100, height: 100);
},
)),
));
await tester.pumpAndSettle();
// Check that internal route properly prepares using the default
// [UrlStrategy]
expect(anchor.getAttribute('href'),
urlStrategy?.prepareExternalUrl(uri3.toString()));
expect(anchor.getAttribute('target'), '_self');
});
testWidgets('sizes itself correctly', (WidgetTester tester) async {
final Key containerKey = GlobalKey();
final Uri uri = Uri.parse('http://foobar');
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(100.0, 100.0)),
child: WebLinkDelegate(TestLinkInfo(
uri: uri,
target: LinkTarget.blank,
builder: (BuildContext context, FollowLink? followLink) {
return Container(
key: containerKey,
child: const SizedBox(width: 50.0, height: 50.0),
);
},
)),
),
),
));
await tester.pumpAndSettle();
final Size containerSize = tester.getSize(find.byKey(containerKey));
// The Stack widget inserted by the `WebLinkDelegate` shouldn't loosen the
// constraints before passing them to the inner container. So the inner
// container should respect the tight constraints given by the ancestor
// `ConstrainedBox` widget.
expect(containerSize.width, 100.0);
expect(containerSize.height, 100.0);
});
// See: https://github.com/flutter/plugins/pull/3522#discussion_r574703724
testWidgets('uri can be null', (WidgetTester tester) async {
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: WebLinkDelegate(TestLinkInfo(
uri: null,
target: LinkTarget.defaultTarget,
builder: (BuildContext context, FollowLink? followLink) {
return const SizedBox(width: 100, height: 100);
},
)),
));
// Platform view creation happens asynchronously.
await tester.pumpAndSettle();
final html.Element anchor = _findSingleAnchor();
expect(anchor.hasAttribute('href'), false);
});
testWidgets('can be created and disposed', (WidgetTester tester) async {
final Uri uri = Uri.parse('http://foobar');
const int itemCount = 500;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: ListView.builder(
itemCount: itemCount,
itemBuilder: (_, int index) => WebLinkDelegate(TestLinkInfo(
uri: uri,
target: LinkTarget.defaultTarget,
builder: (BuildContext context, FollowLink? followLink) =>
Text('#$index', textAlign: TextAlign.center),
)),
),
),
),
);
await tester.pumpAndSettle();
await tester.scrollUntilVisible(
find.text('#${itemCount - 1}'),
800,
maxScrolls: 1000,
);
});
});
}
html.Element _findSingleAnchor() {
final List<html.Element> foundAnchors = <html.Element>[];
for (final html.Element anchor in html.document.querySelectorAll('a')) {
if (hasProperty(anchor, linkViewIdProperty)) {
foundAnchors.add(anchor);
}
}
// Search inside the shadow DOM as well.
final html.ShadowRoot? shadowRoot =
html.document.querySelector('flt-glass-pane')?.shadowRoot;
if (shadowRoot != null) {
for (final html.Element anchor in shadowRoot.querySelectorAll('a')) {
if (hasProperty(anchor, linkViewIdProperty)) {
foundAnchors.add(anchor);
}
}
}
return foundAnchors.single;
}
class TestLinkInfo extends LinkInfo {
TestLinkInfo({
required this.uri,
required this.target,
required this.builder,
});
@override
final LinkWidgetBuilder builder;
@override
final Uri? uri;
@override
final LinkTarget target;
@override
bool get isDisabled => uri == null;
}
| plugins/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart",
"repo_id": "plugins",
"token_count": 2759
} | 1,191 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'src/link.dart';
import 'src/shims/dart_ui.dart' as ui;
import 'src/third_party/platform_detect/browser.dart';
const Set<String> _safariTargetTopSchemes = <String>{
'mailto',
'tel',
'sms',
};
String? _getUrlScheme(String url) => Uri.tryParse(url)?.scheme;
bool _isSafariTargetTopScheme(String url) =>
_safariTargetTopSchemes.contains(_getUrlScheme(url));
/// The web implementation of [UrlLauncherPlatform].
///
/// This class implements the `package:url_launcher` functionality for the web.
class UrlLauncherPlugin extends UrlLauncherPlatform {
/// A constructor that allows tests to override the window object used by the plugin.
UrlLauncherPlugin({@visibleForTesting html.Window? debugWindow})
: _window = debugWindow ?? html.window {
_isSafari = navigatorIsSafari(_window.navigator);
}
final html.Window _window;
bool _isSafari = false;
// The set of schemes that can be handled by the plugin
static final Set<String> _supportedSchemes = <String>{
'http',
'https',
}.union(_safariTargetTopSchemes);
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith(Registrar registrar) {
UrlLauncherPlatform.instance = UrlLauncherPlugin();
ui.platformViewRegistry
.registerViewFactory(linkViewType, linkViewFactory, isVisible: false);
}
@override
LinkDelegate get linkDelegate {
return (LinkInfo linkInfo) => WebLinkDelegate(linkInfo);
}
/// Opens the given [url] in the specified [webOnlyWindowName].
///
/// Returns the newly created window.
@visibleForTesting
html.WindowBase openNewWindow(String url, {String? webOnlyWindowName}) {
// We need to open mailto, tel and sms urls on the _top window context on safari browsers.
// See https://github.com/flutter/flutter/issues/51461 for reference.
final String target = webOnlyWindowName ??
((_isSafari && _isSafariTargetTopScheme(url)) ? '_top' : '');
// ignore: unsafe_html
return _window.open(url, target);
}
@override
Future<bool> canLaunch(String url) {
return Future<bool>.value(_supportedSchemes.contains(_getUrlScheme(url)));
}
@override
Future<bool> launch(
String url, {
bool useSafariVC = false,
bool useWebView = false,
bool enableJavaScript = false,
bool enableDomStorage = false,
bool universalLinksOnly = false,
Map<String, String> headers = const <String, String>{},
String? webOnlyWindowName,
}) {
return Future<bool>.value(
openNewWindow(url, webOnlyWindowName: webOnlyWindowName) != null);
}
}
| plugins/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart",
"repo_id": "plugins",
"token_count": 1025
} | 1,192 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show objectRuntimeType;
import 'sub_rip.dart';
import 'web_vtt.dart';
export 'sub_rip.dart' show SubRipCaptionFile;
export 'web_vtt.dart' show WebVTTCaptionFile;
/// A structured representation of a parsed closed caption file.
///
/// A closed caption file includes a list of captions, each with a start and end
/// time for when the given closed caption should be displayed.
///
/// The [captions] are a list of all captions in a file, in the order that they
/// appeared in the file.
///
/// See:
/// * [SubRipCaptionFile].
/// * [WebVTTCaptionFile].
abstract class ClosedCaptionFile {
/// The full list of captions from a given file.
///
/// The [captions] will be in the order that they appear in the given file.
List<Caption> get captions;
}
/// A representation of a single caption.
///
/// A typical closed captioning file will include several [Caption]s, each
/// linked to a start and end time.
class Caption {
/// Creates a new [Caption] object.
///
/// This is not recommended for direct use unless you are writing a parser for
/// a new closed captioning file type.
const Caption({
required this.number,
required this.start,
required this.end,
required this.text,
});
/// The number that this caption was assigned.
final int number;
/// When in the given video should this [Caption] begin displaying.
final Duration start;
/// When in the given video should this [Caption] be dismissed.
final Duration end;
/// The actual text that should appear on screen to be read between [start]
/// and [end].
final String text;
/// A no caption object. This is a caption with [start] and [end] durations of zero,
/// and an empty [text] string.
static const Caption none = Caption(
number: 0,
start: Duration.zero,
end: Duration.zero,
text: '',
);
@override
String toString() {
return '${objectRuntimeType(this, 'Caption')}('
'number: $number, '
'start: $start, '
'end: $end, '
'text: $text)';
}
}
| plugins/packages/video_player/video_player/lib/src/closed_caption_file.dart/0 | {
"file_path": "plugins/packages/video_player/video_player/lib/src/closed_caption_file.dart",
"repo_id": "plugins",
"token_count": 693
} | 1,193 |
rootProject.name = 'video_player_android'
| plugins/packages/video_player/video_player_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/video_player/video_player_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 13
} | 1,194 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
objcHeaderOut: 'ios/Classes/messages.g.h',
objcSourceOut: 'ios/Classes/messages.g.m',
objcOptions: ObjcOptions(
prefix: 'FLT',
),
copyrightHeader: 'pigeons/copyright.txt',
))
class TextureMessage {
TextureMessage(this.textureId);
int textureId;
}
class LoopingMessage {
LoopingMessage(this.textureId, this.isLooping);
int textureId;
bool isLooping;
}
class VolumeMessage {
VolumeMessage(this.textureId, this.volume);
int textureId;
double volume;
}
class PlaybackSpeedMessage {
PlaybackSpeedMessage(this.textureId, this.speed);
int textureId;
double speed;
}
class PositionMessage {
PositionMessage(this.textureId, this.position);
int textureId;
int position;
}
class CreateMessage {
CreateMessage({required this.httpHeaders});
String? asset;
String? uri;
String? packageName;
String? formatHint;
Map<String?, String?> httpHeaders;
}
class MixWithOthersMessage {
MixWithOthersMessage(this.mixWithOthers);
bool mixWithOthers;
}
@HostApi(dartHostTestHandler: 'TestHostVideoPlayerApi')
abstract class AVFoundationVideoPlayerApi {
@ObjCSelector('initialize')
void initialize();
@ObjCSelector('create:')
TextureMessage create(CreateMessage msg);
@ObjCSelector('dispose:')
void dispose(TextureMessage msg);
@ObjCSelector('setLooping:')
void setLooping(LoopingMessage msg);
@ObjCSelector('setVolume:')
void setVolume(VolumeMessage msg);
@ObjCSelector('setPlaybackSpeed:')
void setPlaybackSpeed(PlaybackSpeedMessage msg);
@ObjCSelector('play:')
void play(TextureMessage msg);
@ObjCSelector('position:')
PositionMessage position(TextureMessage msg);
@ObjCSelector('seekTo:')
void seekTo(PositionMessage msg);
@ObjCSelector('pause:')
void pause(TextureMessage msg);
@ObjCSelector('setMixWithOthers:')
void setMixWithOthers(MixWithOthersMessage msg);
}
| plugins/packages/video_player/video_player_avfoundation/pigeons/messages.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/pigeons/messages.dart",
"repo_id": "plugins",
"token_count": 723
} | 1,195 |
name: video_player_web
description: Web platform implementation of video_player.
repository: https://github.com/flutter/plugins/tree/main/packages/video_player/video_player_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.0.13
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: video_player
platforms:
web:
pluginClass: VideoPlayerPlugin
fileName: video_player_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
video_player_platform_interface: ">=4.2.0 <7.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/video_player/video_player_web/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player_web/pubspec.yaml",
"repo_id": "plugins",
"token_count": 296
} | 1,196 |
// 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.
/// Re-export the classes from the webview_flutter_platform_interface through
/// the `platform_interface.dart` file so we don't accidentally break any
/// non-endorsed existing implementations of the interface.
export 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'
show
AutoMediaPlaybackPolicy,
CreationParams,
JavascriptChannel,
JavascriptChannelRegistry,
JavascriptMessage,
JavascriptMode,
JavascriptMessageHandler,
WebViewPlatform,
WebViewPlatformCallbacksHandler,
WebViewPlatformController,
WebViewPlatformCreatedCallback,
WebSetting,
WebSettings,
WebResourceError,
WebResourceErrorType,
WebViewCookie,
WebViewRequest,
WebViewRequestMethod;
| plugins/packages/webview_flutter/webview_flutter/lib/src/legacy/platform_interface.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/lib/src/legacy/platform_interface.dart",
"repo_id": "plugins",
"token_count": 354
} | 1,197 |
// 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.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.view.KeyEvent;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.webkit.WebResourceErrorCompat;
import androidx.webkit.WebViewClientCompat;
import java.util.Objects;
/**
* Host api implementation for {@link WebViewClient}.
*
* <p>Handles creating {@link WebViewClient}s that intercommunicate with a paired Dart object.
*/
public class WebViewClientHostApiImpl implements GeneratedAndroidWebView.WebViewClientHostApi {
private final InstanceManager instanceManager;
private final WebViewClientCreator webViewClientCreator;
private final WebViewClientFlutterApiImpl flutterApi;
/** Implementation of {@link WebViewClient} that passes arguments of callback methods to Dart. */
@RequiresApi(Build.VERSION_CODES.N)
public static class WebViewClientImpl extends WebViewClient {
private final WebViewClientFlutterApiImpl flutterApi;
private boolean returnValueForShouldOverrideUrlLoading = false;
/**
* Creates a {@link WebViewClient} that passes arguments of callbacks methods to Dart.
*
* @param flutterApi handles sending messages to Dart
*/
public WebViewClientImpl(@NonNull WebViewClientFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
flutterApi.onPageStarted(this, view, url, reply -> {});
}
@Override
public void onPageFinished(WebView view, String url) {
flutterApi.onPageFinished(this, view, url, reply -> {});
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
flutterApi.onReceivedRequestError(this, view, request, error, reply -> {});
}
@Override
public void onReceivedError(
WebView view, int errorCode, String description, String failingUrl) {
flutterApi.onReceivedError(
this, view, (long) errorCode, description, failingUrl, reply -> {});
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
flutterApi.requestLoading(this, view, request, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
flutterApi.urlLoading(this, view, url, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
// Deliberately empty. Occasionally the webview will mark events as having failed to be
// handled even though they were handled. We don't want to propagate those as they're not
// truly lost.
}
/** Sets return value for {@link #shouldOverrideUrlLoading}. */
public void setReturnValueForShouldOverrideUrlLoading(boolean value) {
returnValueForShouldOverrideUrlLoading = value;
}
}
/**
* Implementation of {@link WebViewClientCompat} that passes arguments of callback methods to
* Dart.
*/
public static class WebViewClientCompatImpl extends WebViewClientCompat {
private final WebViewClientFlutterApiImpl flutterApi;
private boolean returnValueForShouldOverrideUrlLoading = false;
public WebViewClientCompatImpl(@NonNull WebViewClientFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
flutterApi.onPageStarted(this, view, url, reply -> {});
}
@Override
public void onPageFinished(WebView view, String url) {
flutterApi.onPageFinished(this, view, url, reply -> {});
}
// This method is only called when the WebViewFeature.RECEIVE_WEB_RESOURCE_ERROR feature is
// enabled. The deprecated method is called when a device doesn't support this.
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("RequiresFeature")
@Override
public void onReceivedError(
@NonNull WebView view,
@NonNull WebResourceRequest request,
@NonNull WebResourceErrorCompat error) {
flutterApi.onReceivedRequestError(this, view, request, error, reply -> {});
}
@Override
public void onReceivedError(
WebView view, int errorCode, String description, String failingUrl) {
flutterApi.onReceivedError(
this, view, (long) errorCode, description, failingUrl, reply -> {});
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView view, @NonNull WebResourceRequest request) {
flutterApi.requestLoading(this, view, request, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
flutterApi.urlLoading(this, view, url, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
// Deliberately empty. Occasionally the webview will mark events as having failed to be
// handled even though they were handled. We don't want to propagate those as they're not
// truly lost.
}
/** Sets return value for {@link #shouldOverrideUrlLoading}. */
public void setReturnValueForShouldOverrideUrlLoading(boolean value) {
returnValueForShouldOverrideUrlLoading = value;
}
}
/** Handles creating {@link WebViewClient}s for a {@link WebViewClientHostApiImpl}. */
public static class WebViewClientCreator {
/**
* Creates a {@link WebViewClient}.
*
* @param flutterApi handles sending messages to Dart
* @return the created {@link WebViewClient}
*/
public WebViewClient createWebViewClient(WebViewClientFlutterApiImpl flutterApi) {
// WebViewClientCompat is used to get
// shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
// invoked by the webview on older Android devices, without it pages that use iframes will
// be broken when a navigationDelegate is set on Android version earlier than N.
//
// However, this if statement attempts to avoid using WebViewClientCompat on versions >= N due
// to bug https://bugs.chromium.org/p/chromium/issues/detail?id=925887. Also, see
// https://github.com/flutter/flutter/issues/29446.
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return new WebViewClientImpl(flutterApi);
} else {
return new WebViewClientCompatImpl(flutterApi);
}
}
}
/**
* Creates a host API that handles creating {@link WebViewClient}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param webViewClientCreator handles creating {@link WebViewClient}s
* @param flutterApi handles sending messages to Dart
*/
public WebViewClientHostApiImpl(
InstanceManager instanceManager,
WebViewClientCreator webViewClientCreator,
WebViewClientFlutterApiImpl flutterApi) {
this.instanceManager = instanceManager;
this.webViewClientCreator = webViewClientCreator;
this.flutterApi = flutterApi;
}
@Override
public void create(@NonNull Long instanceId) {
final WebViewClient webViewClient = webViewClientCreator.createWebViewClient(flutterApi);
instanceManager.addDartCreatedInstance(webViewClient, instanceId);
}
@Override
public void setSynchronousReturnValueForShouldOverrideUrlLoading(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebViewClient webViewClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
if (webViewClient instanceof WebViewClientCompatImpl) {
((WebViewClientCompatImpl) webViewClient).setReturnValueForShouldOverrideUrlLoading(value);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& webViewClient instanceof WebViewClientImpl) {
((WebViewClientImpl) webViewClient).setReturnValueForShouldOverrideUrlLoading(value);
} else {
throw new IllegalStateException(
"This WebViewClient doesn't support setting the returnValueForShouldOverrideUrlLoading.");
}
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientHostApiImpl.java",
"repo_id": "plugins",
"token_count": 2859
} | 1,198 |
// 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 static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.webkit.WebSettings;
import io.flutter.plugins.webviewflutter.WebSettingsHostApiImpl.WebSettingsCreator;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class WebSettingsTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public WebSettings mockWebSettings;
@Mock WebSettingsCreator mockWebSettingsCreator;
InstanceManager testInstanceManager;
WebSettingsHostApiImpl testHostApiImpl;
@Before
public void setUp() {
testInstanceManager = InstanceManager.open(identifier -> {});
when(mockWebSettingsCreator.createWebSettings(any())).thenReturn(mockWebSettings);
testHostApiImpl = new WebSettingsHostApiImpl(testInstanceManager, mockWebSettingsCreator);
testHostApiImpl.create(0L, 0L);
}
@After
public void tearDown() {
testInstanceManager.close();
}
@Test
public void setDomStorageEnabled() {
testHostApiImpl.setDomStorageEnabled(0L, true);
verify(mockWebSettings).setDomStorageEnabled(true);
}
@Test
public void setJavaScriptCanOpenWindowsAutomatically() {
testHostApiImpl.setJavaScriptCanOpenWindowsAutomatically(0L, false);
verify(mockWebSettings).setJavaScriptCanOpenWindowsAutomatically(false);
}
@Test
public void setSupportMultipleWindows() {
testHostApiImpl.setSupportMultipleWindows(0L, true);
verify(mockWebSettings).setSupportMultipleWindows(true);
}
@Test
public void setJavaScriptEnabled() {
testHostApiImpl.setJavaScriptEnabled(0L, false);
verify(mockWebSettings).setJavaScriptEnabled(false);
}
@Test
public void setUserAgentString() {
testHostApiImpl.setUserAgentString(0L, "hello");
verify(mockWebSettings).setUserAgentString("hello");
}
@Test
public void setMediaPlaybackRequiresUserGesture() {
testHostApiImpl.setMediaPlaybackRequiresUserGesture(0L, false);
verify(mockWebSettings).setMediaPlaybackRequiresUserGesture(false);
}
@Test
public void setSupportZoom() {
testHostApiImpl.setSupportZoom(0L, true);
verify(mockWebSettings).setSupportZoom(true);
}
@Test
public void setLoadWithOverviewMode() {
testHostApiImpl.setLoadWithOverviewMode(0L, false);
verify(mockWebSettings).setLoadWithOverviewMode(false);
}
@Test
public void setUseWideViewPort() {
testHostApiImpl.setUseWideViewPort(0L, true);
verify(mockWebSettings).setUseWideViewPort(true);
}
@Test
public void setDisplayZoomControls() {
testHostApiImpl.setDisplayZoomControls(0L, false);
verify(mockWebSettings).setDisplayZoomControls(false);
}
@Test
public void setBuiltInZoomControls() {
testHostApiImpl.setBuiltInZoomControls(0L, true);
verify(mockWebSettings).setBuiltInZoomControls(true);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebSettingsTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebSettingsTest.java",
"repo_id": "plugins",
"token_count": 1086
} | 1,199 |
// 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.webviewflutterexample;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
public class DriverExtensionActivity extends FlutterActivity {
@Override
@NonNull
public String getDartEntrypointFunctionName() {
return "appMain";
}
}
| plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/main/java/io/flutter/plugins/webviewflutterexample/DriverExtensionActivity.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/main/java/io/flutter/plugins/webviewflutterexample/DriverExtensionActivity.java",
"repo_id": "plugins",
"token_count": 136
} | 1,200 |
h1 {
color: blue;
} | plugins/packages/webview_flutter/webview_flutter_android/example/assets/www/styles/style.css/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/assets/www/styles/style.css",
"repo_id": "plugins",
"token_count": 13
} | 1,201 |
// 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';
/// An immutable object that can provide functional copies of itself.
///
/// All implementers are expected to be immutable as defined by the annotation.
// TODO(bparrishMines): Uncomment annotation once
// https://github.com/flutter/plugins/pull/5831 lands or when making a breaking
// change for https://github.com/flutter/flutter/issues/107199.
// @immutable
mixin Copyable {
/// Instantiates and returns a functionally identical object to oneself.
///
/// Outside of tests, this method should only ever be called by
/// [InstanceManager].
///
/// Subclasses should always override their parent's implementation of this
/// method.
@protected
Copyable copy();
}
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// Added instances are stored as weak references and their copies are stored
/// as strong references to maintain access to their variables and callback
/// methods. Both are stored with the same identifier.
///
/// When a weak referenced instance becomes inaccessible,
/// [onWeakReferenceRemoved] is called with its associated identifier.
///
/// If an instance is retrieved and has the possibility to be used,
/// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference
/// is added as a weak reference with the same identifier. This prevents a
/// scenario where the weak referenced instance was released and then later
/// returned by the host platform.
class InstanceManager {
/// Constructs an [InstanceManager].
InstanceManager({required void Function(int) onWeakReferenceRemoved}) {
this.onWeakReferenceRemoved = (int identifier) {
_weakInstances.remove(identifier);
onWeakReferenceRemoved(identifier);
};
_finalizer = Finalizer<int>(this.onWeakReferenceRemoved);
}
// Identifiers are locked to a specific range to avoid collisions with objects
// created simultaneously by the host platform.
// Host uses identifiers >= 2^16 and Dart is expected to use values n where,
// 0 <= n < 2^16.
static const int _maxDartCreatedIdentifier = 65536;
// Expando is used because it doesn't prevent its keys from becoming
// inaccessible. This allows the manager to efficiently retrieve an identifier
// of an instance without holding a strong reference to that instance.
//
// It also doesn't use `==` to search for identifiers, which would lead to an
// infinite loop when comparing an object to its copy. (i.e. which was caused
// by calling instanceManager.getIdentifier() inside of `==` while this was a
// HashMap).
final Expando<int> _identifiers = Expando<int>();
final Map<int, WeakReference<Copyable>> _weakInstances =
<int, WeakReference<Copyable>>{};
final Map<int, Copyable> _strongInstances = <int, Copyable>{};
late final Finalizer<int> _finalizer;
int _nextIdentifier = 0;
/// Called when a weak referenced instance is removed by [removeWeakReference]
/// or becomes inaccessible.
late final void Function(int) onWeakReferenceRemoved;
/// Adds a new instance that was instantiated by Dart.
///
/// In other words, Dart wants to add a new instance that will represent
/// an object that will be instantiated on the host platform.
///
/// Throws assertion error if the instance has already been added.
///
/// Returns the randomly generated id of the [instance] added.
int addDartCreatedInstance(Copyable instance) {
assert(getIdentifier(instance) == null);
final int identifier = _nextUniqueIdentifier();
_addInstanceWithIdentifier(instance, identifier);
return identifier;
}
/// Removes the instance, if present, and call [onWeakReferenceRemoved] with
/// its identifier.
///
/// Returns the identifier associated with the removed instance. Otherwise,
/// `null` if the instance was not found in this manager.
///
/// This does not remove the the strong referenced instance associated with
/// [instance]. This can be done with [remove].
int? removeWeakReference(Copyable instance) {
final int? identifier = getIdentifier(instance);
if (identifier == null) {
return null;
}
_identifiers[instance] = null;
_finalizer.detach(instance);
onWeakReferenceRemoved(identifier);
return identifier;
}
/// Removes [identifier] and its associated strongly referenced instance, if
/// present, from the manager.
///
/// Returns the strong referenced instance associated with [identifier] before
/// it was removed. Returns `null` if [identifier] was not associated with
/// any strong reference.
///
/// This does not remove the the weak referenced instance associtated with
/// [identifier]. This can be done with [removeWeakReference].
T? remove<T extends Copyable>(int identifier) {
return _strongInstances.remove(identifier) as T?;
}
/// Retrieves the instance associated with identifier.
///
/// The value returned is chosen from the following order:
///
/// 1. A weakly referenced instance associated with identifier.
/// 2. If the only instance associated with identifier is a strongly
/// referenced instance, a copy of the instance is added as a weak reference
/// with the same identifier. Returning the newly created copy.
/// 3. If no instance is associated with identifier, returns null.
///
/// This method also expects the host `InstanceManager` to have a strong
/// reference to the instance the identifier is associated with.
T? getInstanceWithWeakReference<T extends Copyable>(int identifier) {
final Copyable? weakInstance = _weakInstances[identifier]?.target;
if (weakInstance == null) {
final Copyable? strongInstance = _strongInstances[identifier];
if (strongInstance != null) {
final Copyable copy = strongInstance.copy();
_identifiers[copy] = identifier;
_weakInstances[identifier] = WeakReference<Copyable>(copy);
_finalizer.attach(copy, identifier, detach: copy);
return copy as T;
}
return strongInstance as T?;
}
return weakInstance as T;
}
/// Retrieves the identifier associated with instance.
int? getIdentifier(Copyable instance) {
return _identifiers[instance];
}
/// Adds a new instance that was instantiated by the host platform.
///
/// In other words, the host platform wants to add a new instance that
/// represents an object on the host platform. Stored with [identifier].
///
/// Throws assertion error if the instance or its identifier has already been
/// added.
///
/// Returns unique identifier of the [instance] added.
void addHostCreatedInstance(Copyable instance, int identifier) {
assert(!containsIdentifier(identifier));
assert(getIdentifier(instance) == null);
assert(identifier >= 0);
_addInstanceWithIdentifier(instance, identifier);
}
void _addInstanceWithIdentifier(Copyable instance, int identifier) {
_identifiers[instance] = identifier;
_weakInstances[identifier] = WeakReference<Copyable>(instance);
_finalizer.attach(instance, identifier, detach: instance);
final Copyable copy = instance.copy();
_identifiers[copy] = identifier;
_strongInstances[identifier] = copy;
}
/// Whether this manager contains the given [identifier].
bool containsIdentifier(int identifier) {
return _weakInstances.containsKey(identifier) ||
_strongInstances.containsKey(identifier);
}
int _nextUniqueIdentifier() {
late int identifier;
do {
identifier = _nextIdentifier;
_nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier;
} while (containsIdentifier(identifier));
return identifier;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/instance_manager.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/instance_manager.dart",
"repo_id": "plugins",
"token_count": 2157
} | 1,202 |
// 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:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_webview.dart';
import 'package:webview_flutter_android/src/android_webview.g.dart';
import 'package:webview_flutter_android/src/android_webview_api_impls.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'android_webview_test.mocks.dart';
import 'test_android_webview.g.dart';
@GenerateMocks(<Type>[
CookieManagerHostApi,
DownloadListener,
JavaScriptChannel,
TestDownloadListenerHostApi,
TestJavaObjectHostApi,
TestJavaScriptChannelHostApi,
TestWebChromeClientHostApi,
TestWebSettingsHostApi,
TestWebStorageHostApi,
TestWebViewClientHostApi,
TestWebViewHostApi,
TestAssetManagerHostApi,
WebChromeClient,
WebView,
WebViewClient,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Android WebView', () {
group('JavaObject', () {
late MockTestJavaObjectHostApi mockPlatformHostApi;
setUp(() {
mockPlatformHostApi = MockTestJavaObjectHostApi();
TestJavaObjectHostApi.setup(mockPlatformHostApi);
});
tearDown(() {
TestJavaObjectHostApi.setup(null);
});
test('JavaObject.dispose', () async {
int? callbackIdentifier;
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (int identifier) {
callbackIdentifier = identifier;
},
);
final JavaObject object = JavaObject.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(object, 0);
JavaObject.dispose(object);
expect(callbackIdentifier, 0);
});
test('JavaObjectFlutterApi.dispose', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final JavaObject object = JavaObject.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(object, 0);
instanceManager.removeWeakReference(object);
expect(instanceManager.containsIdentifier(0), isTrue);
final JavaObjectFlutterApiImpl flutterApi = JavaObjectFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.dispose(0);
expect(instanceManager.containsIdentifier(0), isFalse);
});
});
group('WebView', () {
late MockTestWebViewHostApi mockPlatformHostApi;
late InstanceManager instanceManager;
late WebView webView;
late int webViewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestWebViewHostApi();
TestWebViewHostApi.setup(mockPlatformHostApi);
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
WebView.api = WebViewHostApiImpl(instanceManager: instanceManager);
webView = WebView();
webViewInstanceId = instanceManager.getIdentifier(webView)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webViewInstanceId, false));
});
test('setWebContentsDebuggingEnabled true', () {
WebView.setWebContentsDebuggingEnabled(true);
verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(true));
});
test('setWebContentsDebuggingEnabled false', () {
WebView.setWebContentsDebuggingEnabled(false);
verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(false));
});
test('loadData', () {
webView.loadData(
data: 'hello',
mimeType: 'text/plain',
encoding: 'base64',
);
verify(mockPlatformHostApi.loadData(
webViewInstanceId,
'hello',
'text/plain',
'base64',
));
});
test('loadData with null values', () {
webView.loadData(data: 'hello');
verify(mockPlatformHostApi.loadData(
webViewInstanceId,
'hello',
null,
null,
));
});
test('loadDataWithBaseUrl', () {
webView.loadDataWithBaseUrl(
baseUrl: 'https://base.url',
data: 'hello',
mimeType: 'text/plain',
encoding: 'base64',
historyUrl: 'https://history.url',
);
verify(mockPlatformHostApi.loadDataWithBaseUrl(
webViewInstanceId,
'https://base.url',
'hello',
'text/plain',
'base64',
'https://history.url',
));
});
test('loadDataWithBaseUrl with null values', () {
webView.loadDataWithBaseUrl(data: 'hello');
verify(mockPlatformHostApi.loadDataWithBaseUrl(
webViewInstanceId,
null,
'hello',
null,
null,
null,
));
});
test('loadUrl', () {
webView.loadUrl('hello', <String, String>{'a': 'header'});
verify(mockPlatformHostApi.loadUrl(
webViewInstanceId,
'hello',
<String, String>{'a': 'header'},
));
});
test('canGoBack', () {
when(mockPlatformHostApi.canGoBack(webViewInstanceId))
.thenReturn(false);
expect(webView.canGoBack(), completion(false));
});
test('canGoForward', () {
when(mockPlatformHostApi.canGoForward(webViewInstanceId))
.thenReturn(true);
expect(webView.canGoForward(), completion(true));
});
test('goBack', () {
webView.goBack();
verify(mockPlatformHostApi.goBack(webViewInstanceId));
});
test('goForward', () {
webView.goForward();
verify(mockPlatformHostApi.goForward(webViewInstanceId));
});
test('reload', () {
webView.reload();
verify(mockPlatformHostApi.reload(webViewInstanceId));
});
test('clearCache', () {
webView.clearCache(false);
verify(mockPlatformHostApi.clearCache(webViewInstanceId, false));
});
test('evaluateJavascript', () {
when(
mockPlatformHostApi.evaluateJavascript(
webViewInstanceId, 'runJavaScript'),
).thenAnswer((_) => Future<String>.value('returnValue'));
expect(
webView.evaluateJavascript('runJavaScript'),
completion('returnValue'),
);
});
test('getTitle', () {
when(mockPlatformHostApi.getTitle(webViewInstanceId))
.thenReturn('aTitle');
expect(webView.getTitle(), completion('aTitle'));
});
test('scrollTo', () {
webView.scrollTo(12, 13);
verify(mockPlatformHostApi.scrollTo(webViewInstanceId, 12, 13));
});
test('scrollBy', () {
webView.scrollBy(12, 14);
verify(mockPlatformHostApi.scrollBy(webViewInstanceId, 12, 14));
});
test('getScrollX', () {
when(mockPlatformHostApi.getScrollX(webViewInstanceId)).thenReturn(67);
expect(webView.getScrollX(), completion(67));
});
test('getScrollY', () {
when(mockPlatformHostApi.getScrollY(webViewInstanceId)).thenReturn(56);
expect(webView.getScrollY(), completion(56));
});
test('getScrollPosition', () async {
when(mockPlatformHostApi.getScrollPosition(webViewInstanceId))
.thenReturn(WebViewPoint(x: 2, y: 16));
await expectLater(
webView.getScrollPosition(),
completion(const Offset(2.0, 16.0)),
);
});
test('setWebViewClient', () {
TestWebViewClientHostApi.setup(MockTestWebViewClientHostApi());
WebViewClient.api = WebViewClientHostApiImpl(
instanceManager: instanceManager,
);
final WebViewClient mockWebViewClient = MockWebViewClient();
when(mockWebViewClient.copy()).thenReturn(MockWebViewClient());
instanceManager.addDartCreatedInstance(mockWebViewClient);
webView.setWebViewClient(mockWebViewClient);
final int webViewClientInstanceId =
instanceManager.getIdentifier(mockWebViewClient)!;
verify(mockPlatformHostApi.setWebViewClient(
webViewInstanceId,
webViewClientInstanceId,
));
});
test('addJavaScriptChannel', () {
TestJavaScriptChannelHostApi.setup(MockTestJavaScriptChannelHostApi());
JavaScriptChannel.api = JavaScriptChannelHostApiImpl(
instanceManager: instanceManager,
);
final JavaScriptChannel mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
when(mockJavaScriptChannel.channelName).thenReturn('aChannel');
webView.addJavaScriptChannel(mockJavaScriptChannel);
final int javaScriptChannelInstanceId =
instanceManager.getIdentifier(mockJavaScriptChannel)!;
verify(mockPlatformHostApi.addJavaScriptChannel(
webViewInstanceId,
javaScriptChannelInstanceId,
));
});
test('removeJavaScriptChannel', () {
TestJavaScriptChannelHostApi.setup(MockTestJavaScriptChannelHostApi());
JavaScriptChannel.api = JavaScriptChannelHostApiImpl(
instanceManager: instanceManager,
);
final JavaScriptChannel mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
when(mockJavaScriptChannel.channelName).thenReturn('aChannel');
expect(
webView.removeJavaScriptChannel(mockJavaScriptChannel),
completes,
);
webView.addJavaScriptChannel(mockJavaScriptChannel);
webView.removeJavaScriptChannel(mockJavaScriptChannel);
final int javaScriptChannelInstanceId =
instanceManager.getIdentifier(mockJavaScriptChannel)!;
verify(mockPlatformHostApi.removeJavaScriptChannel(
webViewInstanceId,
javaScriptChannelInstanceId,
));
});
test('setDownloadListener', () {
TestDownloadListenerHostApi.setup(MockTestDownloadListenerHostApi());
DownloadListener.api = DownloadListenerHostApiImpl(
instanceManager: instanceManager,
);
final DownloadListener mockDownloadListener = MockDownloadListener();
when(mockDownloadListener.copy()).thenReturn(MockDownloadListener());
instanceManager.addDartCreatedInstance(mockDownloadListener);
webView.setDownloadListener(mockDownloadListener);
final int downloadListenerInstanceId =
instanceManager.getIdentifier(mockDownloadListener)!;
verify(mockPlatformHostApi.setDownloadListener(
webViewInstanceId,
downloadListenerInstanceId,
));
});
test('setWebChromeClient', () {
TestWebChromeClientHostApi.setup(MockTestWebChromeClientHostApi());
WebChromeClient.api = WebChromeClientHostApiImpl(
instanceManager: instanceManager,
);
final WebChromeClient mockWebChromeClient = MockWebChromeClient();
when(mockWebChromeClient.copy()).thenReturn(MockWebChromeClient());
instanceManager.addDartCreatedInstance(mockWebChromeClient);
webView.setWebChromeClient(mockWebChromeClient);
final int webChromeClientInstanceId =
instanceManager.getIdentifier(mockWebChromeClient)!;
verify(mockPlatformHostApi.setWebChromeClient(
webViewInstanceId,
webChromeClientInstanceId,
));
});
test('copy', () {
expect(webView.copy(), isA<WebView>());
});
});
group('WebSettings', () {
late MockTestWebSettingsHostApi mockPlatformHostApi;
late InstanceManager instanceManager;
late WebSettings webSettings;
late int webSettingsInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
TestWebViewHostApi.setup(MockTestWebViewHostApi());
WebView.api = WebViewHostApiImpl(instanceManager: instanceManager);
mockPlatformHostApi = MockTestWebSettingsHostApi();
TestWebSettingsHostApi.setup(mockPlatformHostApi);
WebSettings.api = WebSettingsHostApiImpl(
instanceManager: instanceManager,
);
webSettings = WebSettings(WebView());
webSettingsInstanceId = instanceManager.getIdentifier(webSettings)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webSettingsInstanceId, any));
});
test('setDomStorageEnabled', () {
webSettings.setDomStorageEnabled(false);
verify(mockPlatformHostApi.setDomStorageEnabled(
webSettingsInstanceId,
false,
));
});
test('setJavaScriptCanOpenWindowsAutomatically', () {
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
verify(mockPlatformHostApi.setJavaScriptCanOpenWindowsAutomatically(
webSettingsInstanceId,
true,
));
});
test('setSupportMultipleWindows', () {
webSettings.setSupportMultipleWindows(false);
verify(mockPlatformHostApi.setSupportMultipleWindows(
webSettingsInstanceId,
false,
));
});
test('setJavaScriptEnabled', () {
webSettings.setJavaScriptEnabled(true);
verify(mockPlatformHostApi.setJavaScriptEnabled(
webSettingsInstanceId,
true,
));
});
test('setUserAgentString', () {
webSettings.setUserAgentString('hola');
verify(mockPlatformHostApi.setUserAgentString(
webSettingsInstanceId,
'hola',
));
});
test('setMediaPlaybackRequiresUserGesture', () {
webSettings.setMediaPlaybackRequiresUserGesture(false);
verify(mockPlatformHostApi.setMediaPlaybackRequiresUserGesture(
webSettingsInstanceId,
false,
));
});
test('setSupportZoom', () {
webSettings.setSupportZoom(true);
verify(mockPlatformHostApi.setSupportZoom(
webSettingsInstanceId,
true,
));
});
test('setLoadWithOverviewMode', () {
webSettings.setLoadWithOverviewMode(false);
verify(mockPlatformHostApi.setLoadWithOverviewMode(
webSettingsInstanceId,
false,
));
});
test('setUseWideViewPort', () {
webSettings.setUseWideViewPort(true);
verify(mockPlatformHostApi.setUseWideViewPort(
webSettingsInstanceId,
true,
));
});
test('setDisplayZoomControls', () {
webSettings.setDisplayZoomControls(false);
verify(mockPlatformHostApi.setDisplayZoomControls(
webSettingsInstanceId,
false,
));
});
test('setBuiltInZoomControls', () {
webSettings.setBuiltInZoomControls(true);
verify(mockPlatformHostApi.setBuiltInZoomControls(
webSettingsInstanceId,
true,
));
});
test('setAllowFileAccess', () {
webSettings.setAllowFileAccess(true);
verify(mockPlatformHostApi.setAllowFileAccess(
webSettingsInstanceId,
true,
));
});
test('copy', () {
expect(webSettings.copy(), isA<WebSettings>());
});
});
group('JavaScriptChannel', () {
late JavaScriptChannelFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockJavaScriptChannel mockJavaScriptChannel;
late int mockJavaScriptChannelInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = JavaScriptChannelFlutterApiImpl(
instanceManager: instanceManager,
);
mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
mockJavaScriptChannelInstanceId =
instanceManager.addDartCreatedInstance(mockJavaScriptChannel);
});
test('postMessage', () {
late final String result;
when(mockJavaScriptChannel.postMessage).thenReturn((String message) {
result = message;
});
flutterApi.postMessage(
mockJavaScriptChannelInstanceId,
'Hello, World!',
);
expect(result, 'Hello, World!');
});
test('copy', () {
expect(
JavaScriptChannel.detached('channel', postMessage: (_) {}).copy(),
isA<JavaScriptChannel>(),
);
});
});
group('WebViewClient', () {
late WebViewClientFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockWebViewClient mockWebViewClient;
late int mockWebViewClientInstanceId;
late MockWebView mockWebView;
late int mockWebViewInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = WebViewClientFlutterApiImpl(
instanceManager: instanceManager,
);
mockWebViewClient = MockWebViewClient();
when(mockWebViewClient.copy()).thenReturn(MockWebViewClient());
mockWebViewClientInstanceId =
instanceManager.addDartCreatedInstance(mockWebViewClient);
mockWebView = MockWebView();
when(mockWebView.copy()).thenReturn(MockWebView());
mockWebViewInstanceId =
instanceManager.addDartCreatedInstance(mockWebView);
});
test('onPageStarted', () {
late final List<Object> result;
when(mockWebViewClient.onPageStarted).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.onPageStarted(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
'https://www.google.com',
);
expect(result, <Object>[mockWebView, 'https://www.google.com']);
});
test('onPageFinished', () {
late final List<Object> result;
when(mockWebViewClient.onPageFinished).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.onPageFinished(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
'https://www.google.com',
);
expect(result, <Object>[mockWebView, 'https://www.google.com']);
});
test('onReceivedRequestError', () {
late final List<Object> result;
when(mockWebViewClient.onReceivedRequestError).thenReturn(
(
WebView webView,
WebResourceRequest request,
WebResourceError error,
) {
result = <Object>[webView, request, error];
},
);
flutterApi.onReceivedRequestError(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
WebResourceRequestData(
url: 'https://www.google.com',
isForMainFrame: true,
hasGesture: true,
method: 'POST',
isRedirect: false,
requestHeaders: <String?, String?>{},
),
WebResourceErrorData(errorCode: 34, description: 'error description'),
);
expect(
result,
containsAllInOrder(<Object?>[mockWebView, isNotNull, isNotNull]),
);
});
test('onReceivedError', () {
late final List<Object> result;
when(mockWebViewClient.onReceivedError).thenReturn(
(
WebView webView,
int errorCode,
String description,
String failingUrl,
) {
result = <Object>[webView, errorCode, description, failingUrl];
},
);
flutterApi.onReceivedError(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
14,
'desc',
'https://www.google.com',
);
expect(
result,
containsAllInOrder(
<Object?>[mockWebView, 14, 'desc', 'https://www.google.com'],
),
);
});
test('requestLoading', () {
late final List<Object> result;
when(mockWebViewClient.requestLoading).thenReturn(
(WebView webView, WebResourceRequest request) {
result = <Object>[webView, request];
},
);
flutterApi.requestLoading(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
WebResourceRequestData(
url: 'https://www.google.com',
isForMainFrame: true,
hasGesture: true,
method: 'POST',
isRedirect: true,
requestHeaders: <String?, String?>{},
),
);
expect(
result,
containsAllInOrder(<Object?>[mockWebView, isNotNull]),
);
});
test('urlLoading', () {
late final List<Object> result;
when(mockWebViewClient.urlLoading).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.urlLoading(mockWebViewClientInstanceId,
mockWebViewInstanceId, 'https://www.google.com');
expect(
result,
containsAllInOrder(<Object?>[mockWebView, 'https://www.google.com']),
);
});
test('copy', () {
expect(WebViewClient.detached().copy(), isA<WebViewClient>());
});
});
group('DownloadListener', () {
late DownloadListenerFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockDownloadListener mockDownloadListener;
late int mockDownloadListenerInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = DownloadListenerFlutterApiImpl(
instanceManager: instanceManager,
);
mockDownloadListener = MockDownloadListener();
when(mockDownloadListener.copy()).thenReturn(MockDownloadListener());
mockDownloadListenerInstanceId =
instanceManager.addDartCreatedInstance(mockDownloadListener);
});
test('onDownloadStart', () {
late final List<Object> result;
when(mockDownloadListener.onDownloadStart).thenReturn(
(
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
result = <Object>[
url,
userAgent,
contentDisposition,
mimetype,
contentLength,
];
},
);
flutterApi.onDownloadStart(
mockDownloadListenerInstanceId,
'url',
'userAgent',
'contentDescription',
'mimetype',
45,
);
expect(
result,
containsAllInOrder(<Object?>[
'url',
'userAgent',
'contentDescription',
'mimetype',
45,
]),
);
});
test('copy', () {
expect(
DownloadListener.detached(
onDownloadStart: (_, __, ____, _____, ______) {},
).copy(),
isA<DownloadListener>(),
);
});
});
group('WebChromeClient', () {
late WebChromeClientFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockWebChromeClient mockWebChromeClient;
late int mockWebChromeClientInstanceId;
late MockWebView mockWebView;
late int mockWebViewInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = WebChromeClientFlutterApiImpl(
instanceManager: instanceManager,
);
mockWebChromeClient = MockWebChromeClient();
when(mockWebChromeClient.copy()).thenReturn(MockWebChromeClient());
mockWebChromeClientInstanceId =
instanceManager.addDartCreatedInstance(mockWebChromeClient);
mockWebView = MockWebView();
when(mockWebView.copy()).thenReturn(MockWebView());
mockWebViewInstanceId =
instanceManager.addDartCreatedInstance(mockWebView);
});
test('onProgressChanged', () {
late final List<Object> result;
when(mockWebChromeClient.onProgressChanged).thenReturn(
(WebView webView, int progress) {
result = <Object>[webView, progress];
},
);
flutterApi.onProgressChanged(
mockWebChromeClientInstanceId,
mockWebViewInstanceId,
76,
);
expect(result, containsAllInOrder(<Object?>[mockWebView, 76]));
});
test('onShowFileChooser', () async {
late final List<Object> result;
when(mockWebChromeClient.onShowFileChooser).thenReturn(
(WebView webView, FileChooserParams params) {
result = <Object>[webView, params];
return Future<List<String>>.value(<String>['fileOne', 'fileTwo']);
},
);
final FileChooserParams params = FileChooserParams.detached(
isCaptureEnabled: false,
acceptTypes: <String>[],
filenameHint: 'filenameHint',
mode: FileChooserMode.open,
);
instanceManager.addHostCreatedInstance(params, 3);
await expectLater(
flutterApi.onShowFileChooser(
mockWebChromeClientInstanceId,
mockWebViewInstanceId,
3,
),
completion(<String>['fileOne', 'fileTwo']),
);
expect(result[0], mockWebView);
expect(result[1], params);
});
test('setSynchronousReturnValueForOnShowFileChooser', () {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient webChromeClient = WebChromeClient.detached();
instanceManager.addHostCreatedInstance(webChromeClient, 2);
webChromeClient.setSynchronousReturnValueForOnShowFileChooser(false);
verify(
mockHostApi.setSynchronousReturnValueForOnShowFileChooser(2, false),
);
});
test(
'setSynchronousReturnValueForOnShowFileChooser throws StateError when onShowFileChooser is null',
() {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient clientWithNullCallback =
WebChromeClient.detached();
instanceManager.addHostCreatedInstance(clientWithNullCallback, 2);
expect(
() => clientWithNullCallback
.setSynchronousReturnValueForOnShowFileChooser(true),
throwsStateError,
);
final WebChromeClient clientWithNonnullCallback =
WebChromeClient.detached(
onShowFileChooser: (_, __) async => <String>[],
);
instanceManager.addHostCreatedInstance(clientWithNonnullCallback, 3);
clientWithNonnullCallback
.setSynchronousReturnValueForOnShowFileChooser(true);
verify(
mockHostApi.setSynchronousReturnValueForOnShowFileChooser(3, true),
);
});
test('copy', () {
expect(WebChromeClient.detached().copy(), isA<WebChromeClient>());
});
});
group('FileChooserParams', () {
test('FlutterApi create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final FileChooserParamsFlutterApiImpl flutterApi =
FileChooserParamsFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(
0,
false,
const <String>['my', 'list'],
FileChooserModeEnumData(value: FileChooserMode.openMultiple),
'filenameHint',
);
final FileChooserParams instance = instanceManager
.getInstanceWithWeakReference(0)! as FileChooserParams;
expect(instance.isCaptureEnabled, false);
expect(instance.acceptTypes, const <String>['my', 'list']);
expect(instance.mode, FileChooserMode.openMultiple);
expect(instance.filenameHint, 'filenameHint');
});
});
});
group('CookieManager', () {
test('setCookie calls setCookie on CookieManagerHostApi', () {
CookieManager.api = MockCookieManagerHostApi();
CookieManager.instance.setCookie('foo', 'bar');
verify(CookieManager.api.setCookie('foo', 'bar'));
});
test('clearCookies calls clearCookies on CookieManagerHostApi', () {
CookieManager.api = MockCookieManagerHostApi();
when(CookieManager.api.clearCookies())
.thenAnswer((_) => Future<bool>.value(true));
CookieManager.instance.clearCookies();
verify(CookieManager.api.clearCookies());
});
});
group('WebStorage', () {
late MockTestWebStorageHostApi mockPlatformHostApi;
late WebStorage webStorage;
late int webStorageInstanceId;
setUp(() {
mockPlatformHostApi = MockTestWebStorageHostApi();
TestWebStorageHostApi.setup(mockPlatformHostApi);
webStorage = WebStorage();
webStorageInstanceId =
WebStorage.api.instanceManager.getIdentifier(webStorage)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webStorageInstanceId));
});
test('deleteAllData', () {
webStorage.deleteAllData();
verify(mockPlatformHostApi.deleteAllData(webStorageInstanceId));
});
test('copy', () {
expect(WebStorage.detached().copy(), isA<WebStorage>());
});
});
}
| plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_test.dart",
"repo_id": "plugins",
"token_count": 13123
} | 1,203 |
// 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/widgets.dart';
import '../platform_interface/javascript_channel_registry.dart';
import '../types/types.dart';
import 'webview_platform_callbacks_handler.dart';
import 'webview_platform_controller.dart';
/// Signature for callbacks reporting that a [WebViewPlatformController] was created.
///
/// See also the `onWebViewPlatformCreated` argument for [WebViewPlatform.build].
typedef WebViewPlatformCreatedCallback = void Function(
WebViewPlatformController? webViewPlatformController);
/// Interface for a platform implementation of a WebView.
///
/// [WebView.platform] controls the builder that is used by [WebView].
/// [AndroidWebViewPlatform] and [CupertinoWebViewPlatform] are the default implementations
/// for Android and iOS respectively.
abstract class WebViewPlatform {
/// Builds a new WebView.
///
/// Returns a Widget tree that embeds the created webview.
///
/// `creationParams` are the initial parameters used to setup the webview.
///
/// `webViewPlatformHandler` will be used for handling callbacks that are made by the created
/// [WebViewPlatformController].
///
/// `onWebViewPlatformCreated` will be invoked after the platform specific [WebViewPlatformController]
/// implementation is created with the [WebViewPlatformController] instance as a parameter.
///
/// `gestureRecognizers` specifies which gestures should be consumed by the web view.
/// It is possible for other gesture recognizers to be competing with the web view on pointer
/// events, e.g if the web view is inside a [ListView] the [ListView] will want to handle
/// vertical drags. The web view will claim gestures that are recognized by any of the
/// recognizers on this list.
/// When `gestureRecognizers` is empty or null, the web view will only handle pointer events for gestures that
/// were not claimed by any other gesture recognizer.
///
/// `webViewPlatformHandler` must not be null.
Widget build({
required BuildContext context,
// TODO(amirh): convert this to be the actual parameters.
// I'm starting without it as the PR is starting to become pretty big.
// I'll followup with the conversion PR.
required CreationParams creationParams,
required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
required JavascriptChannelRegistry javascriptChannelRegistry,
WebViewPlatformCreatedCallback? onWebViewPlatformCreated,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
});
/// Clears all cookies for all [WebView] instances.
///
/// Returns true if cookies were present before clearing, else false.
/// Soon to be deprecated. 'Use `WebViewCookieManagerPlatform.clearCookies` instead.
Future<bool> clearCookies() {
throw UnimplementedError(
'WebView clearCookies is not implemented on the current platform');
}
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform.dart",
"repo_id": "plugins",
"token_count": 832
} | 1,204 |
// 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:plugin_platform_interface/plugin_platform_interface.dart';
import 'webview_platform.dart';
/// Interface for a platform implementation of a cookie manager.
///
/// Platform implementations should extend this class rather than implement it
/// as `webview_flutter` does not consider newly added methods to be breaking
/// changes. Extending this class (using `extends`) ensures that the subclass
/// will get the default implementation, while platform implementations that
/// `implements` this interface will be broken by newly added
/// [PlatformWebViewCookieManager] methods.
abstract class PlatformWebViewCookieManager extends PlatformInterface {
/// Creates a new [PlatformWebViewCookieManager]
factory PlatformWebViewCookieManager(
PlatformWebViewCookieManagerCreationParams params) {
assert(
WebViewPlatform.instance != null,
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
);
final PlatformWebViewCookieManager cookieManagerDelegate =
WebViewPlatform.instance!.createPlatformCookieManager(params);
PlatformInterface.verify(cookieManagerDelegate, _token);
return cookieManagerDelegate;
}
/// Used by the platform implementation to create a new
/// [PlatformWebViewCookieManager].
///
/// Should only be used by platform implementations because they can't extend
/// a class that only contains a factory constructor.
@protected
PlatformWebViewCookieManager.implementation(this.params)
: super(token: _token);
static final Object _token = Object();
/// The parameters used to initialize the [PlatformWebViewCookieManager].
final PlatformWebViewCookieManagerCreationParams params;
/// Clears all cookies for all [WebView] instances.
///
/// Returns true if cookies were present before clearing, else false.
Future<bool> clearCookies() {
throw UnimplementedError(
'clearCookies is not implemented on the current platform');
}
/// Sets a cookie for all [WebView] instances.
Future<void> setCookie(WebViewCookie cookie) {
throw UnimplementedError(
'setCookie is not implemented on the current platform');
}
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_cookie_manager.dart",
"repo_id": "plugins",
"token_count": 711
} | 1,205 |
# webview\_flutter\_web
This is an implementation of the [`webview_flutter`](https://pub.dev/packages/webview_flutter) plugin for web.
It is currently severely limited and doesn't implement most of the available functionality.
The following functionality is currently available:
- `loadRequest`
- `loadHtmlString` (Without `baseUrl`)
Nothing else is currently supported.
## Usage
This package is not an endorsed implementation of the `webview_flutter` plugin
yet, so it currently requires extra setup to use:
* [Add this package](https://pub.dev/packages/webview_flutter_web/install)
as an explicit dependency of your project, in addition to depending on
`webview_flutter`.
Once the step above is complete, the APIs from `webview_flutter` listed
above can be used as normal on web.
## Tests
Tests are contained in the `test` directory. You can run all tests from the root
of the package with the following command:
```bash
$ flutter test --platform chrome
```
This package uses `package:mockito` in some tests. Mock files can be updated
from the root of the package like so:
```bash
$ flutter pub run build_runner build --delete-conflicting-outputs
```
| plugins/packages/webview_flutter/webview_flutter_web/README.md/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_web/README.md",
"repo_id": "plugins",
"token_count": 324
} | 1,206 |
// 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 webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFWebsiteDataStoreHostApiTests : XCTestCase
@end
@implementation FWFWebsiteDataStoreHostApiTests
- (void)testCreateFromWebViewConfigurationWithIdentifier {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFWebsiteDataStoreHostApiImpl *hostAPI =
[[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager];
[instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0];
FlutterError *error;
[hostAPI createFromWebViewConfigurationWithIdentifier:@1 configurationIdentifier:@0 error:&error];
WKWebsiteDataStore *dataStore = (WKWebsiteDataStore *)[instanceManager instanceForIdentifier:1];
XCTAssertTrue([dataStore isKindOfClass:[WKWebsiteDataStore class]]);
XCTAssertNil(error);
}
- (void)testCreateDefaultDataStoreWithIdentifier {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFWebsiteDataStoreHostApiImpl *hostAPI =
[[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI createDefaultDataStoreWithIdentifier:@0 error:&error];
WKWebsiteDataStore *dataStore = (WKWebsiteDataStore *)[instanceManager instanceForIdentifier:0];
XCTAssertEqualObjects(dataStore, [WKWebsiteDataStore defaultDataStore]);
XCTAssertNil(error);
}
- (void)testRemoveDataOfTypes {
WKWebsiteDataStore *mockWebsiteDataStore = OCMClassMock([WKWebsiteDataStore class]);
WKWebsiteDataRecord *mockDataRecord = OCMClassMock([WKWebsiteDataRecord class]);
OCMStub([mockWebsiteDataStore
fetchDataRecordsOfTypes:[NSSet setWithObject:WKWebsiteDataTypeLocalStorage]
completionHandler:([OCMArg invokeBlockWithArgs:@[ mockDataRecord ], nil])]);
OCMStub([mockWebsiteDataStore
removeDataOfTypes:[NSSet setWithObject:WKWebsiteDataTypeLocalStorage]
modifiedSince:[NSDate dateWithTimeIntervalSince1970:45.0]
completionHandler:([OCMArg invokeBlock])]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockWebsiteDataStore withIdentifier:0];
FWFWebsiteDataStoreHostApiImpl *hostAPI =
[[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager];
NSNumber __block *returnValue;
FlutterError *__block blockError;
[hostAPI removeDataFromDataStoreWithIdentifier:@0
ofTypes:@[
[FWFWKWebsiteDataTypeEnumData
makeWithValue:FWFWKWebsiteDataTypeEnumLocalStorage]
]
modifiedSince:@45.0
completion:^(NSNumber *result, FlutterError *error) {
returnValue = result;
blockError = error;
}];
XCTAssertEqualObjects(returnValue, @YES);
// Asserts whether the NSNumber will be deserialized by the standard codec as a boolean.
XCTAssertEqual(CFGetTypeID((__bridge CFTypeRef)(returnValue)), CFBooleanGetTypeID());
XCTAssertNil(blockError);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebsiteDataStoreHostApiTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebsiteDataStoreHostApiTests.m",
"repo_id": "plugins",
"token_count": 1344
} | 1,207 |
// 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 (v4.2.13), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "FWFGeneratedWebKitApis.h"
#import <Flutter/Flutter.h>
#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 FWFNSKeyValueObservingOptionsEnumData ()
+ (FWFNSKeyValueObservingOptionsEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSKeyValueObservingOptionsEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSKeyValueChangeKeyEnumData ()
+ (FWFNSKeyValueChangeKeyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSKeyValueChangeKeyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKUserScriptInjectionTimeEnumData ()
+ (FWFWKUserScriptInjectionTimeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKUserScriptInjectionTimeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKAudiovisualMediaTypeEnumData ()
+ (FWFWKAudiovisualMediaTypeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKAudiovisualMediaTypeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKWebsiteDataTypeEnumData ()
+ (FWFWKWebsiteDataTypeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKWebsiteDataTypeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKNavigationActionPolicyEnumData ()
+ (FWFWKNavigationActionPolicyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKNavigationActionPolicyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSHttpCookiePropertyKeyEnumData ()
+ (FWFNSHttpCookiePropertyKeyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSHttpCookiePropertyKeyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSUrlRequestData ()
+ (FWFNSUrlRequestData *)fromList:(NSArray *)list;
+ (nullable FWFNSUrlRequestData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKUserScriptData ()
+ (FWFWKUserScriptData *)fromList:(NSArray *)list;
+ (nullable FWFWKUserScriptData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKNavigationActionData ()
+ (FWFWKNavigationActionData *)fromList:(NSArray *)list;
+ (nullable FWFWKNavigationActionData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKFrameInfoData ()
+ (FWFWKFrameInfoData *)fromList:(NSArray *)list;
+ (nullable FWFWKFrameInfoData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSErrorData ()
+ (FWFNSErrorData *)fromList:(NSArray *)list;
+ (nullable FWFNSErrorData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKScriptMessageData ()
+ (FWFWKScriptMessageData *)fromList:(NSArray *)list;
+ (nullable FWFWKScriptMessageData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSHttpCookieData ()
+ (FWFNSHttpCookieData *)fromList:(NSArray *)list;
+ (nullable FWFNSHttpCookieData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@implementation FWFNSKeyValueObservingOptionsEnumData
+ (instancetype)makeWithValue:(FWFNSKeyValueObservingOptionsEnum)value {
FWFNSKeyValueObservingOptionsEnumData *pigeonResult =
[[FWFNSKeyValueObservingOptionsEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSKeyValueObservingOptionsEnumData *)fromList:(NSArray *)list {
FWFNSKeyValueObservingOptionsEnumData *pigeonResult =
[[FWFNSKeyValueObservingOptionsEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSKeyValueObservingOptionsEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSKeyValueObservingOptionsEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSKeyValueChangeKeyEnumData
+ (instancetype)makeWithValue:(FWFNSKeyValueChangeKeyEnum)value {
FWFNSKeyValueChangeKeyEnumData *pigeonResult = [[FWFNSKeyValueChangeKeyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSKeyValueChangeKeyEnumData *)fromList:(NSArray *)list {
FWFNSKeyValueChangeKeyEnumData *pigeonResult = [[FWFNSKeyValueChangeKeyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSKeyValueChangeKeyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSKeyValueChangeKeyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKUserScriptInjectionTimeEnumData
+ (instancetype)makeWithValue:(FWFWKUserScriptInjectionTimeEnum)value {
FWFWKUserScriptInjectionTimeEnumData *pigeonResult =
[[FWFWKUserScriptInjectionTimeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKUserScriptInjectionTimeEnumData *)fromList:(NSArray *)list {
FWFWKUserScriptInjectionTimeEnumData *pigeonResult =
[[FWFWKUserScriptInjectionTimeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKUserScriptInjectionTimeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKUserScriptInjectionTimeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKAudiovisualMediaTypeEnumData
+ (instancetype)makeWithValue:(FWFWKAudiovisualMediaTypeEnum)value {
FWFWKAudiovisualMediaTypeEnumData *pigeonResult =
[[FWFWKAudiovisualMediaTypeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKAudiovisualMediaTypeEnumData *)fromList:(NSArray *)list {
FWFWKAudiovisualMediaTypeEnumData *pigeonResult =
[[FWFWKAudiovisualMediaTypeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKAudiovisualMediaTypeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKAudiovisualMediaTypeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKWebsiteDataTypeEnumData
+ (instancetype)makeWithValue:(FWFWKWebsiteDataTypeEnum)value {
FWFWKWebsiteDataTypeEnumData *pigeonResult = [[FWFWKWebsiteDataTypeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKWebsiteDataTypeEnumData *)fromList:(NSArray *)list {
FWFWKWebsiteDataTypeEnumData *pigeonResult = [[FWFWKWebsiteDataTypeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKWebsiteDataTypeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKWebsiteDataTypeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKNavigationActionPolicyEnumData
+ (instancetype)makeWithValue:(FWFWKNavigationActionPolicyEnum)value {
FWFWKNavigationActionPolicyEnumData *pigeonResult =
[[FWFWKNavigationActionPolicyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKNavigationActionPolicyEnumData *)fromList:(NSArray *)list {
FWFWKNavigationActionPolicyEnumData *pigeonResult =
[[FWFWKNavigationActionPolicyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKNavigationActionPolicyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKNavigationActionPolicyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSHttpCookiePropertyKeyEnumData
+ (instancetype)makeWithValue:(FWFNSHttpCookiePropertyKeyEnum)value {
FWFNSHttpCookiePropertyKeyEnumData *pigeonResult =
[[FWFNSHttpCookiePropertyKeyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSHttpCookiePropertyKeyEnumData *)fromList:(NSArray *)list {
FWFNSHttpCookiePropertyKeyEnumData *pigeonResult =
[[FWFNSHttpCookiePropertyKeyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSHttpCookiePropertyKeyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSHttpCookiePropertyKeyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSUrlRequestData
+ (instancetype)makeWithUrl:(NSString *)url
httpMethod:(nullable NSString *)httpMethod
httpBody:(nullable FlutterStandardTypedData *)httpBody
allHttpHeaderFields:(NSDictionary<NSString *, NSString *> *)allHttpHeaderFields {
FWFNSUrlRequestData *pigeonResult = [[FWFNSUrlRequestData alloc] init];
pigeonResult.url = url;
pigeonResult.httpMethod = httpMethod;
pigeonResult.httpBody = httpBody;
pigeonResult.allHttpHeaderFields = allHttpHeaderFields;
return pigeonResult;
}
+ (FWFNSUrlRequestData *)fromList:(NSArray *)list {
FWFNSUrlRequestData *pigeonResult = [[FWFNSUrlRequestData alloc] init];
pigeonResult.url = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.url != nil, @"");
pigeonResult.httpMethod = GetNullableObjectAtIndex(list, 1);
pigeonResult.httpBody = GetNullableObjectAtIndex(list, 2);
pigeonResult.allHttpHeaderFields = GetNullableObjectAtIndex(list, 3);
NSAssert(pigeonResult.allHttpHeaderFields != nil, @"");
return pigeonResult;
}
+ (nullable FWFNSUrlRequestData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSUrlRequestData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.url ?: [NSNull null]),
(self.httpMethod ?: [NSNull null]),
(self.httpBody ?: [NSNull null]),
(self.allHttpHeaderFields ?: [NSNull null]),
];
}
@end
@implementation FWFWKUserScriptData
+ (instancetype)makeWithSource:(NSString *)source
injectionTime:(nullable FWFWKUserScriptInjectionTimeEnumData *)injectionTime
isMainFrameOnly:(NSNumber *)isMainFrameOnly {
FWFWKUserScriptData *pigeonResult = [[FWFWKUserScriptData alloc] init];
pigeonResult.source = source;
pigeonResult.injectionTime = injectionTime;
pigeonResult.isMainFrameOnly = isMainFrameOnly;
return pigeonResult;
}
+ (FWFWKUserScriptData *)fromList:(NSArray *)list {
FWFWKUserScriptData *pigeonResult = [[FWFWKUserScriptData alloc] init];
pigeonResult.source = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.source != nil, @"");
pigeonResult.injectionTime =
[FWFWKUserScriptInjectionTimeEnumData nullableFromList:(GetNullableObjectAtIndex(list, 1))];
pigeonResult.isMainFrameOnly = GetNullableObjectAtIndex(list, 2);
NSAssert(pigeonResult.isMainFrameOnly != nil, @"");
return pigeonResult;
}
+ (nullable FWFWKUserScriptData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKUserScriptData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.source ?: [NSNull null]),
(self.injectionTime ? [self.injectionTime toList] : [NSNull null]),
(self.isMainFrameOnly ?: [NSNull null]),
];
}
@end
@implementation FWFWKNavigationActionData
+ (instancetype)makeWithRequest:(FWFNSUrlRequestData *)request
targetFrame:(FWFWKFrameInfoData *)targetFrame
navigationType:(FWFWKNavigationType)navigationType {
FWFWKNavigationActionData *pigeonResult = [[FWFWKNavigationActionData alloc] init];
pigeonResult.request = request;
pigeonResult.targetFrame = targetFrame;
pigeonResult.navigationType = navigationType;
return pigeonResult;
}
+ (FWFWKNavigationActionData *)fromList:(NSArray *)list {
FWFWKNavigationActionData *pigeonResult = [[FWFWKNavigationActionData alloc] init];
pigeonResult.request = [FWFNSUrlRequestData nullableFromList:(GetNullableObjectAtIndex(list, 0))];
NSAssert(pigeonResult.request != nil, @"");
pigeonResult.targetFrame =
[FWFWKFrameInfoData nullableFromList:(GetNullableObjectAtIndex(list, 1))];
NSAssert(pigeonResult.targetFrame != nil, @"");
pigeonResult.navigationType = [GetNullableObjectAtIndex(list, 2) integerValue];
return pigeonResult;
}
+ (nullable FWFWKNavigationActionData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKNavigationActionData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.request ? [self.request toList] : [NSNull null]),
(self.targetFrame ? [self.targetFrame toList] : [NSNull null]),
@(self.navigationType),
];
}
@end
@implementation FWFWKFrameInfoData
+ (instancetype)makeWithIsMainFrame:(NSNumber *)isMainFrame {
FWFWKFrameInfoData *pigeonResult = [[FWFWKFrameInfoData alloc] init];
pigeonResult.isMainFrame = isMainFrame;
return pigeonResult;
}
+ (FWFWKFrameInfoData *)fromList:(NSArray *)list {
FWFWKFrameInfoData *pigeonResult = [[FWFWKFrameInfoData alloc] init];
pigeonResult.isMainFrame = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.isMainFrame != nil, @"");
return pigeonResult;
}
+ (nullable FWFWKFrameInfoData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKFrameInfoData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.isMainFrame ?: [NSNull null]),
];
}
@end
@implementation FWFNSErrorData
+ (instancetype)makeWithCode:(NSNumber *)code
domain:(NSString *)domain
localizedDescription:(NSString *)localizedDescription {
FWFNSErrorData *pigeonResult = [[FWFNSErrorData alloc] init];
pigeonResult.code = code;
pigeonResult.domain = domain;
pigeonResult.localizedDescription = localizedDescription;
return pigeonResult;
}
+ (FWFNSErrorData *)fromList:(NSArray *)list {
FWFNSErrorData *pigeonResult = [[FWFNSErrorData alloc] init];
pigeonResult.code = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.code != nil, @"");
pigeonResult.domain = GetNullableObjectAtIndex(list, 1);
NSAssert(pigeonResult.domain != nil, @"");
pigeonResult.localizedDescription = GetNullableObjectAtIndex(list, 2);
NSAssert(pigeonResult.localizedDescription != nil, @"");
return pigeonResult;
}
+ (nullable FWFNSErrorData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSErrorData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.code ?: [NSNull null]),
(self.domain ?: [NSNull null]),
(self.localizedDescription ?: [NSNull null]),
];
}
@end
@implementation FWFWKScriptMessageData
+ (instancetype)makeWithName:(NSString *)name body:(id)body {
FWFWKScriptMessageData *pigeonResult = [[FWFWKScriptMessageData alloc] init];
pigeonResult.name = name;
pigeonResult.body = body;
return pigeonResult;
}
+ (FWFWKScriptMessageData *)fromList:(NSArray *)list {
FWFWKScriptMessageData *pigeonResult = [[FWFWKScriptMessageData alloc] init];
pigeonResult.name = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.name != nil, @"");
pigeonResult.body = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable FWFWKScriptMessageData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKScriptMessageData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.name ?: [NSNull null]),
(self.body ?: [NSNull null]),
];
}
@end
@implementation FWFNSHttpCookieData
+ (instancetype)makeWithPropertyKeys:(NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *)propertyKeys
propertyValues:(NSArray<id> *)propertyValues {
FWFNSHttpCookieData *pigeonResult = [[FWFNSHttpCookieData alloc] init];
pigeonResult.propertyKeys = propertyKeys;
pigeonResult.propertyValues = propertyValues;
return pigeonResult;
}
+ (FWFNSHttpCookieData *)fromList:(NSArray *)list {
FWFNSHttpCookieData *pigeonResult = [[FWFNSHttpCookieData alloc] init];
pigeonResult.propertyKeys = GetNullableObjectAtIndex(list, 0);
NSAssert(pigeonResult.propertyKeys != nil, @"");
pigeonResult.propertyValues = GetNullableObjectAtIndex(list, 1);
NSAssert(pigeonResult.propertyValues != nil, @"");
return pigeonResult;
}
+ (nullable FWFNSHttpCookieData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSHttpCookieData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.propertyKeys ?: [NSNull null]),
(self.propertyValues ?: [NSNull null]),
];
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKWebsiteDataTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKWebsiteDataTypeEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebsiteDataStoreHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebsiteDataStoreHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebsiteDataStoreHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebsiteDataStoreHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebsiteDataStoreHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFWKWebsiteDataStoreHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebsiteDataStoreHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_configurationIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createDefaultDataStore"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createDefaultDataStoreWithIdentifier:error:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(createDefaultDataStoreWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api createDefaultDataStoreWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(removeDataFromDataStoreWithIdentifier:ofTypes:modifiedSince:completion:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(removeDataFromDataStoreWithIdentifier:ofTypes:modifiedSince:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSArray<FWFWKWebsiteDataTypeEnumData *> *arg_dataTypes = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_modificationTimeInSecondsSinceEpoch = GetNullableObjectAtIndex(args, 2);
[api removeDataFromDataStoreWithIdentifier:arg_identifier
ofTypes:arg_dataTypes
modifiedSince:arg_modificationTimeInSecondsSinceEpoch
completion:^(NSNumber *_Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFUIViewHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFUIViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFUIViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIViewHostApi.setBackgroundColor"
binaryMessenger:binaryMessenger
codec:FWFUIViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setBackgroundColorForViewWithIdentifier:
toValue:error:)],
@"FWFUIViewHostApi api (%@) doesn't respond to "
@"@selector(setBackgroundColorForViewWithIdentifier:toValue:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_value = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setBackgroundColorForViewWithIdentifier:arg_identifier toValue:arg_value error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIViewHostApi.setOpaque"
binaryMessenger:binaryMessenger
codec:FWFUIViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setOpaqueForViewWithIdentifier:isOpaque:error:)],
@"FWFUIViewHostApi api (%@) doesn't respond to "
@"@selector(setOpaqueForViewWithIdentifier:isOpaque:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_opaque = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setOpaqueForViewWithIdentifier:arg_identifier isOpaque:arg_opaque error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFUIScrollViewHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFUIScrollViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFUIScrollViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIScrollViewHostApi.createFromWebView"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebViewWithIdentifier:
webViewIdentifier:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewWithIdentifier:webViewIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_webViewIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebViewWithIdentifier:arg_identifier
webViewIdentifier:arg_webViewIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIScrollViewHostApi.getContentOffset"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(contentOffsetForScrollViewWithIdentifier:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(contentOffsetForScrollViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSArray<NSNumber *> *output = [api contentOffsetForScrollViewWithIdentifier:arg_identifier
error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIScrollViewHostApi.scrollBy"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(scrollByForScrollViewWithIdentifier:x:y:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(scrollByForScrollViewWithIdentifier:x:y:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_x = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_y = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api scrollByForScrollViewWithIdentifier:arg_identifier x:arg_x y:arg_y error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setContentOffsetForScrollViewWithIdentifier:toX:y:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(setContentOffsetForScrollViewWithIdentifier:toX:y:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_x = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_y = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api setContentOffsetForScrollViewWithIdentifier:arg_identifier
toX:arg_x
y:arg_y
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKWebViewConfigurationHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebViewConfigurationHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKAudiovisualMediaTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebViewConfigurationHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebViewConfigurationHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKAudiovisualMediaTypeEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebViewConfigurationHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebViewConfigurationHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebViewConfigurationHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebViewConfigurationHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebViewConfigurationHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebViewConfigurationHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFWKWebViewConfigurationHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebViewConfigurationHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewConfigurationHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewConfigurationHostApi.createFromWebView"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebViewWithIdentifier:
webViewIdentifier:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewWithIdentifier:webViewIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_webViewIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebViewWithIdentifier:arg_identifier
webViewIdentifier:arg_webViewIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:isAllowed:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:isAllowed:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_allow = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:arg_identifier
isAllowed:arg_allow
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewConfigurationHostApi."
@"setMediaTypesRequiringUserActionForPlayback"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setMediaTypesRequiresUserActionForConfigurationWithIdentifier:
forTypes:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(setMediaTypesRequiresUserActionForConfigurationWithIdentifier:forTypes:"
@"error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSArray<FWFWKAudiovisualMediaTypeEnumData *> *arg_types = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setMediaTypesRequiresUserActionForConfigurationWithIdentifier:arg_identifier
forTypes:arg_types
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationFlutterApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFWKWebViewConfigurationFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKWebViewConfigurationFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)createWithIdentifier:(NSNumber *)arg_identifier
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.WKWebViewConfigurationFlutterApi.create"
binaryMessenger:self.binaryMessenger
codec:FWFWKWebViewConfigurationFlutterApiGetCodec()];
[channel sendMessage:@[ arg_identifier ?: [NSNull null] ]
reply:^(id reply) {
completion(nil);
}];
}
@end
@interface FWFWKUserContentControllerHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKUserContentControllerHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKUserScriptData fromList:[self readValue]];
case 129:
return [FWFWKUserScriptInjectionTimeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKUserContentControllerHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKUserContentControllerHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKUserScriptData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptInjectionTimeEnumData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKUserContentControllerHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKUserContentControllerHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKUserContentControllerHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKUserContentControllerHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKUserContentControllerHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKUserContentControllerHostApiCodecReaderWriter *readerWriter =
[[FWFWKUserContentControllerHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFWKUserContentControllerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKUserContentControllerHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKUserContentControllerHostApi.createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_configurationIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(addScriptMessageHandlerForControllerWithIdentifier:
handlerIdentifier:ofName:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(addScriptMessageHandlerForControllerWithIdentifier:handlerIdentifier:"
@"ofName:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_handlerIdentifier = GetNullableObjectAtIndex(args, 1);
NSString *arg_name = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api addScriptMessageHandlerForControllerWithIdentifier:arg_identifier
handlerIdentifier:arg_handlerIdentifier
ofName:arg_name
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKUserContentControllerHostApi.removeScriptMessageHandler"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeScriptMessageHandlerForControllerWithIdentifier:name:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeScriptMessageHandlerForControllerWithIdentifier:name:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_name = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api removeScriptMessageHandlerForControllerWithIdentifier:arg_identifier
name:arg_name
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllScriptMessageHandlers"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeAllScriptMessageHandlersForControllerWithIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeAllScriptMessageHandlersForControllerWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api removeAllScriptMessageHandlersForControllerWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKUserContentControllerHostApi.addUserScript"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(addUserScriptForControllerWithIdentifier:
userScript:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(addUserScriptForControllerWithIdentifier:userScript:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FWFWKUserScriptData *arg_userScript = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api addUserScriptForControllerWithIdentifier:arg_identifier
userScript:arg_userScript
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllUserScripts"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeAllUserScriptsForControllerWithIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeAllUserScriptsForControllerWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api removeAllUserScriptsForControllerWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKPreferencesHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFWKPreferencesHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKPreferencesHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKPreferencesHostApi.createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKPreferencesHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKPreferencesHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_configurationIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKPreferencesHostApi.setJavaScriptEnabled"
binaryMessenger:binaryMessenger
codec:FWFWKPreferencesHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setJavaScriptEnabledForPreferencesWithIdentifier:isEnabled:error:)],
@"FWFWKPreferencesHostApi api (%@) doesn't respond to "
@"@selector(setJavaScriptEnabledForPreferencesWithIdentifier:isEnabled:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setJavaScriptEnabledForPreferencesWithIdentifier:arg_identifier
isEnabled:arg_enabled
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFWKScriptMessageHandlerHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKScriptMessageHandlerHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKScriptMessageHandlerHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKScriptMessageHandlerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKScriptMessageHandlerHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKScriptMessageHandlerFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKScriptMessageData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKScriptMessageHandlerFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKScriptMessageData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKScriptMessageHandlerFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKScriptMessageHandlerFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerFlutterApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKScriptMessageHandlerFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKScriptMessageHandlerFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)didReceiveScriptMessageForHandlerWithIdentifier:(NSNumber *)arg_identifier
userContentControllerIdentifier:
(NSNumber *)arg_userContentControllerIdentifier
message:(FWFWKScriptMessageData *)arg_message
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage"
binaryMessenger:self.binaryMessenger
codec:FWFWKScriptMessageHandlerFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_userContentControllerIdentifier ?: [NSNull null],
arg_message ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
@end
NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFWKNavigationDelegateHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKNavigationDelegateHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKNavigationDelegateHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKNavigationDelegateHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKNavigationDelegateHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKNavigationDelegateFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSErrorData fromList:[self readValue]];
case 129:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 130:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 131:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 132:
return [FWFWKNavigationActionPolicyEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKNavigationDelegateFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSErrorData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionPolicyEnumData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKNavigationDelegateFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKNavigationDelegateFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKNavigationDelegateFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateFlutterApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKNavigationDelegateFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKNavigationDelegateFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKNavigationDelegateFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKNavigationDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)didFinishNavigationForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
URL:(nullable NSString *)arg_url
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.didFinishNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_url ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
- (void)didStartProvisionalNavigationForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
URL:(nullable NSString *)arg_url
completion:
(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.didStartProvisionalNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_url ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
- (void)
decidePolicyForNavigationActionForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
navigationAction:
(FWFWKNavigationActionData *)arg_navigationAction
completion:
(void (^)(FWFWKNavigationActionPolicyEnumData
*_Nullable,
NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_navigationAction ?: [NSNull null]
]
reply:^(id reply) {
FWFWKNavigationActionPolicyEnumData *output = reply;
completion(output, nil);
}];
}
- (void)didFailNavigationForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
error:(FWFNSErrorData *)arg_error
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.didFailNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_error ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
- (void)didFailProvisionalNavigationForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
error:(FWFNSErrorData *)arg_error
completion:
(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_error ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
- (void)webViewWebContentProcessDidTerminateForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:
(NSNumber *)arg_webViewIdentifier
completion:(void (^)(NSError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[ arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null] ]
reply:^(id reply) {
completion(nil);
}];
}
@end
@interface FWFNSObjectHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFNSObjectHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSKeyValueObservingOptionsEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFNSObjectHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFNSObjectHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSKeyValueObservingOptionsEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFNSObjectHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFNSObjectHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFNSObjectHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFNSObjectHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFNSObjectHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFNSObjectHostApiCodecReaderWriter *readerWriter =
[[FWFNSObjectHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFNSObjectHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFNSObjectHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.NSObjectHostApi.dispose"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(disposeObjectWithIdentifier:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(disposeObjectWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api disposeObjectWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.NSObjectHostApi.addObserver"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(addObserverForObjectWithIdentifier:
observerIdentifier:keyPath:options:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(addObserverForObjectWithIdentifier:observerIdentifier:keyPath:options:"
@"error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_observerIdentifier = GetNullableObjectAtIndex(args, 1);
NSString *arg_keyPath = GetNullableObjectAtIndex(args, 2);
NSArray<FWFNSKeyValueObservingOptionsEnumData *> *arg_options =
GetNullableObjectAtIndex(args, 3);
FlutterError *error;
[api addObserverForObjectWithIdentifier:arg_identifier
observerIdentifier:arg_observerIdentifier
keyPath:arg_keyPath
options:arg_options
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.NSObjectHostApi.removeObserver"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(removeObserverForObjectWithIdentifier:
observerIdentifier:keyPath:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(removeObserverForObjectWithIdentifier:observerIdentifier:keyPath:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_observerIdentifier = GetNullableObjectAtIndex(args, 1);
NSString *arg_keyPath = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api removeObserverForObjectWithIdentifier:arg_identifier
observerIdentifier:arg_observerIdentifier
keyPath:arg_keyPath
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFNSObjectFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFNSObjectFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSErrorData fromList:[self readValue]];
case 129:
return [FWFNSHttpCookieData fromList:[self readValue]];
case 130:
return [FWFNSHttpCookiePropertyKeyEnumData fromList:[self readValue]];
case 131:
return [FWFNSKeyValueChangeKeyEnumData fromList:[self readValue]];
case 132:
return [FWFNSKeyValueObservingOptionsEnumData fromList:[self readValue]];
case 133:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 134:
return [FWFWKAudiovisualMediaTypeEnumData fromList:[self readValue]];
case 135:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 136:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 137:
return [FWFWKNavigationActionPolicyEnumData fromList:[self readValue]];
case 138:
return [FWFWKScriptMessageData fromList:[self readValue]];
case 139:
return [FWFWKUserScriptData fromList:[self readValue]];
case 140:
return [FWFWKUserScriptInjectionTimeEnumData fromList:[self readValue]];
case 141:
return [FWFWKWebsiteDataTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFNSObjectFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFNSObjectFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSErrorData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookieData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookiePropertyKeyEnumData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueChangeKeyEnumData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueObservingOptionsEnumData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKAudiovisualMediaTypeEnumData class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:135];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:136];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionPolicyEnumData class]]) {
[self writeByte:137];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKScriptMessageData class]]) {
[self writeByte:138];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptData class]]) {
[self writeByte:139];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptInjectionTimeEnumData class]]) {
[self writeByte:140];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKWebsiteDataTypeEnumData class]]) {
[self writeByte:141];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFNSObjectFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFNSObjectFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFNSObjectFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFNSObjectFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFNSObjectFlutterApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFNSObjectFlutterApiCodecReaderWriter *readerWriter =
[[FWFNSObjectFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFNSObjectFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFNSObjectFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)observeValueForObjectWithIdentifier:(NSNumber *)arg_identifier
keyPath:(NSString *)arg_keyPath
objectIdentifier:(NSNumber *)arg_objectIdentifier
changeKeys:
(NSArray<FWFNSKeyValueChangeKeyEnumData *> *)arg_changeKeys
changeValues:(NSArray<id> *)arg_changeValues
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.NSObjectFlutterApi.observeValue"
binaryMessenger:self.binaryMessenger
codec:FWFNSObjectFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_keyPath ?: [NSNull null],
arg_objectIdentifier ?: [NSNull null], arg_changeKeys ?: [NSNull null],
arg_changeValues ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
- (void)disposeObjectWithIdentifier:(NSNumber *)arg_identifier
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.NSObjectFlutterApi.dispose"
binaryMessenger:self.binaryMessenger
codec:FWFNSObjectFlutterApiGetCodec()];
[channel sendMessage:@[ arg_identifier ?: [NSNull null] ]
reply:^(id reply) {
completion(nil);
}];
}
@end
@interface FWFWKWebViewHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebViewHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSErrorData fromList:[self readValue]];
case 129:
return [FWFNSHttpCookieData fromList:[self readValue]];
case 130:
return [FWFNSHttpCookiePropertyKeyEnumData fromList:[self readValue]];
case 131:
return [FWFNSKeyValueChangeKeyEnumData fromList:[self readValue]];
case 132:
return [FWFNSKeyValueObservingOptionsEnumData fromList:[self readValue]];
case 133:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 134:
return [FWFWKAudiovisualMediaTypeEnumData fromList:[self readValue]];
case 135:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 136:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 137:
return [FWFWKNavigationActionPolicyEnumData fromList:[self readValue]];
case 138:
return [FWFWKScriptMessageData fromList:[self readValue]];
case 139:
return [FWFWKUserScriptData fromList:[self readValue]];
case 140:
return [FWFWKUserScriptInjectionTimeEnumData fromList:[self readValue]];
case 141:
return [FWFWKWebsiteDataTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebViewHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebViewHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSErrorData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookieData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookiePropertyKeyEnumData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueChangeKeyEnumData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueObservingOptionsEnumData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKAudiovisualMediaTypeEnumData class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:135];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:136];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionPolicyEnumData class]]) {
[self writeByte:137];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKScriptMessageData class]]) {
[self writeByte:138];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptData class]]) {
[self writeByte:139];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptInjectionTimeEnumData class]]) {
[self writeByte:140];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKWebsiteDataTypeEnumData class]]) {
[self writeByte:141];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebViewHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebViewHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebViewHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebViewHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebViewHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebViewHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebViewHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFWKWebViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_configurationIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.setUIDelegate"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setUIDelegateForWebViewWithIdentifier:
delegateIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setUIDelegateForWebViewWithIdentifier:delegateIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_uiDelegateIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setUIDelegateForWebViewWithIdentifier:arg_identifier
delegateIdentifier:arg_uiDelegateIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.setNavigationDelegate"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(setNavigationDelegateForWebViewWithIdentifier:
delegateIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setNavigationDelegateForWebViewWithIdentifier:delegateIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_navigationDelegateIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setNavigationDelegateForWebViewWithIdentifier:arg_identifier
delegateIdentifier:arg_navigationDelegateIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.getUrl"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(URLForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(URLForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSString *output = [api URLForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.getEstimatedProgress"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(estimatedProgressForWebViewWithIdentifier:
error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(estimatedProgressForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSNumber *output = [api estimatedProgressForWebViewWithIdentifier:arg_identifier
error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.loadRequest"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadRequestForWebViewWithIdentifier:
request:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadRequestForWebViewWithIdentifier:request:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FWFNSUrlRequestData *arg_request = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api loadRequestForWebViewWithIdentifier:arg_identifier request:arg_request error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.loadHtmlString"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadHTMLForWebViewWithIdentifier:
HTMLString:baseURL:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadHTMLForWebViewWithIdentifier:HTMLString:baseURL:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_string = GetNullableObjectAtIndex(args, 1);
NSString *arg_baseUrl = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api loadHTMLForWebViewWithIdentifier:arg_identifier
HTMLString:arg_string
baseURL:arg_baseUrl
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(loadFileForWebViewWithIdentifier:fileURL:readAccessURL:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadFileForWebViewWithIdentifier:fileURL:readAccessURL:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_url = GetNullableObjectAtIndex(args, 1);
NSString *arg_readAccessUrl = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api loadFileForWebViewWithIdentifier:arg_identifier
fileURL:arg_url
readAccessURL:arg_readAccessUrl
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.loadFlutterAsset"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadAssetForWebViewWithIdentifier:
assetKey:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadAssetForWebViewWithIdentifier:assetKey:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_key = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api loadAssetForWebViewWithIdentifier:arg_identifier assetKey:arg_key error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.canGoBack"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(canGoBackForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(canGoBackForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSNumber *output = [api canGoBackForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.canGoForward"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(canGoForwardForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(canGoForwardForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSNumber *output = [api canGoForwardForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.goBack"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(goBackForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(goBackForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api goBackForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.goForward"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(goForwardForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(goForwardForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api goForwardForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.reload"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(reloadWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(reloadWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api reloadWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.getTitle"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(titleForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(titleForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
NSString *output = [api titleForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.WKWebViewHostApi.setAllowsBackForwardNavigationGestures"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setAllowsBackForwardForWebViewWithIdentifier:isAllowed:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setAllowsBackForwardForWebViewWithIdentifier:isAllowed:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_allow = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setAllowsBackForwardForWebViewWithIdentifier:arg_identifier
isAllowed:arg_allow
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.setCustomUserAgent"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setUserAgentForWebViewWithIdentifier:
userAgent:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setUserAgentForWebViewWithIdentifier:userAgent:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_userAgent = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setUserAgentForWebViewWithIdentifier:arg_identifier
userAgent:arg_userAgent
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKWebViewHostApi.evaluateJavaScript"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(evaluateJavaScriptForWebViewWithIdentifier:javaScriptString:completion:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(evaluateJavaScriptForWebViewWithIdentifier:javaScriptString:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSString *arg_javaScriptString = GetNullableObjectAtIndex(args, 1);
[api evaluateJavaScriptForWebViewWithIdentifier:arg_identifier
javaScriptString:arg_javaScriptString
completion:^(id _Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKUIDelegateHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void FWFWKUIDelegateHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKUIDelegateHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKUIDelegateHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKUIDelegateHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKUIDelegateHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKUIDelegateFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKUIDelegateFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 129:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 130:
return [FWFWKNavigationActionData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKUIDelegateFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKUIDelegateFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKUIDelegateFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKUIDelegateFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKUIDelegateFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKUIDelegateFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKUIDelegateFlutterApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKUIDelegateFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKUIDelegateFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKUIDelegateFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKUIDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)onCreateWebViewForDelegateWithIdentifier:(NSNumber *)arg_identifier
webViewIdentifier:(NSNumber *)arg_webViewIdentifier
configurationIdentifier:(NSNumber *)arg_configurationIdentifier
navigationAction:(FWFWKNavigationActionData *)arg_navigationAction
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.WKUIDelegateFlutterApi.onCreateWebView"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
arg_identifier ?: [NSNull null], arg_webViewIdentifier ?: [NSNull null],
arg_configurationIdentifier ?: [NSNull null], arg_navigationAction ?: [NSNull null]
]
reply:^(id reply) {
completion(nil);
}];
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKHttpCookieStoreHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSHttpCookieData fromList:[self readValue]];
case 129:
return [FWFNSHttpCookiePropertyKeyEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKHttpCookieStoreHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSHttpCookieData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookiePropertyKeyEnumData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKHttpCookieStoreHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKHttpCookieStoreHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKHttpCookieStoreHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKHttpCookieStoreHostApiGetCodec() {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKHttpCookieStoreHostApiCodecReaderWriter *readerWriter =
[[FWFWKHttpCookieStoreHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FWFWKHttpCookieStoreHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKHttpCookieStoreHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKHttpCookieStoreHostApi.createFromWebsiteDataStore"
binaryMessenger:binaryMessenger
codec:FWFWKHttpCookieStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebsiteDataStoreWithIdentifier:
dataStoreIdentifier:error:)],
@"FWFWKHttpCookieStoreHostApi api (%@) doesn't respond to "
@"@selector(createFromWebsiteDataStoreWithIdentifier:dataStoreIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_websiteDataStoreIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api createFromWebsiteDataStoreWithIdentifier:arg_identifier
dataStoreIdentifier:arg_websiteDataStoreIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.WKHttpCookieStoreHostApi.setCookie"
binaryMessenger:binaryMessenger
codec:FWFWKHttpCookieStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setCookieForStoreWithIdentifier:
cookie:completion:)],
@"FWFWKHttpCookieStoreHostApi api (%@) doesn't respond to "
@"@selector(setCookieForStoreWithIdentifier:cookie:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSNumber *arg_identifier = GetNullableObjectAtIndex(args, 0);
FWFNSHttpCookieData *arg_cookie = GetNullableObjectAtIndex(args, 1);
[api setCookieForStoreWithIdentifier:arg_identifier
cookie:arg_cookie
completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.m",
"repo_id": "plugins",
"token_count": 46944
} | 1,208 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'webview_flutter_wkwebview'
s.version = '0.0.1'
s.summary = 'A WebView Plugin for Flutter.'
s.description = <<-DESC
A Flutter plugin that provides a WebView widget.
Downloaded by pub (not CocoaPods).
DESC
s.homepage = 'https://github.com/flutter/plugins'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/webview_flutter/webview_flutter_wkwebview' }
s.documentation_url = 'https://pub.dev/packages/webview_flutter'
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/FlutterWebView.modulemap'
s.dependency 'Flutter'
s.platform = :ios, '9.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/webview_flutter_wkwebview.podspec/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/webview_flutter_wkwebview.podspec",
"repo_id": "plugins",
"token_count": 491
} | 1,209 |
// 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:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'webkit_webview_controller.dart';
import 'webkit_webview_cookie_manager.dart';
/// Implementation of [WebViewPlatform] using the WebKit API.
class WebKitWebViewPlatform extends WebViewPlatform {
/// Registers this class as the default instance of [WebViewPlatform].
static void registerWith() {
WebViewPlatform.instance = WebKitWebViewPlatform();
}
@override
WebKitWebViewController createPlatformWebViewController(
PlatformWebViewControllerCreationParams params,
) {
return WebKitWebViewController(params);
}
@override
WebKitNavigationDelegate createPlatformNavigationDelegate(
PlatformNavigationDelegateCreationParams params,
) {
return WebKitNavigationDelegate(params);
}
@override
WebKitWebViewWidget createPlatformWebViewWidget(
PlatformWebViewWidgetCreationParams params,
) {
return WebKitWebViewWidget(params);
}
@override
WebKitWebViewCookieManager createPlatformCookieManager(
PlatformWebViewCookieManagerCreationParams params,
) {
return WebKitWebViewCookieManager(params);
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_platform.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_platform.dart",
"repo_id": "plugins",
"token_count": 391
} | 1,210 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_wkwebview/test/src/web_kit/web_kit_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart' as _i4;
import '../common/test_web_kit.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestWKHttpCookieStoreHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKHttpCookieStoreHostApi extends _i1.Mock
implements _i2.TestWKHttpCookieStoreHostApi {
MockTestWKHttpCookieStoreHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void createFromWebsiteDataStore(
int? identifier,
int? websiteDataStoreIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebsiteDataStore,
[
identifier,
websiteDataStoreIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<void> setCookie(
int? identifier,
_i4.NSHttpCookieData? cookie,
) =>
(super.noSuchMethod(
Invocation.method(
#setCookie,
[
identifier,
cookie,
],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
}
/// A class which mocks [TestWKNavigationDelegateHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKNavigationDelegateHostApi extends _i1.Mock
implements _i2.TestWKNavigationDelegateHostApi {
MockTestWKNavigationDelegateHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKPreferencesHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKPreferencesHostApi extends _i1.Mock
implements _i2.TestWKPreferencesHostApi {
MockTestWKPreferencesHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void createFromWebViewConfiguration(
int? identifier,
int? configurationIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebViewConfiguration,
[
identifier,
configurationIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setJavaScriptEnabled(
int? identifier,
bool? enabled,
) =>
super.noSuchMethod(
Invocation.method(
#setJavaScriptEnabled,
[
identifier,
enabled,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKScriptMessageHandlerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKScriptMessageHandlerHostApi extends _i1.Mock
implements _i2.TestWKScriptMessageHandlerHostApi {
MockTestWKScriptMessageHandlerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKUIDelegateHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKUIDelegateHostApi extends _i1.Mock
implements _i2.TestWKUIDelegateHostApi {
MockTestWKUIDelegateHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKUserContentControllerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKUserContentControllerHostApi extends _i1.Mock
implements _i2.TestWKUserContentControllerHostApi {
MockTestWKUserContentControllerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void createFromWebViewConfiguration(
int? identifier,
int? configurationIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebViewConfiguration,
[
identifier,
configurationIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void addScriptMessageHandler(
int? identifier,
int? handlerIdentifier,
String? name,
) =>
super.noSuchMethod(
Invocation.method(
#addScriptMessageHandler,
[
identifier,
handlerIdentifier,
name,
],
),
returnValueForMissingStub: null,
);
@override
void removeScriptMessageHandler(
int? identifier,
String? name,
) =>
super.noSuchMethod(
Invocation.method(
#removeScriptMessageHandler,
[
identifier,
name,
],
),
returnValueForMissingStub: null,
);
@override
void removeAllScriptMessageHandlers(int? identifier) => super.noSuchMethod(
Invocation.method(
#removeAllScriptMessageHandlers,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void addUserScript(
int? identifier,
_i4.WKUserScriptData? userScript,
) =>
super.noSuchMethod(
Invocation.method(
#addUserScript,
[
identifier,
userScript,
],
),
returnValueForMissingStub: null,
);
@override
void removeAllUserScripts(int? identifier) => super.noSuchMethod(
Invocation.method(
#removeAllUserScripts,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKWebViewConfigurationHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKWebViewConfigurationHostApi extends _i1.Mock
implements _i2.TestWKWebViewConfigurationHostApi {
MockTestWKWebViewConfigurationHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void createFromWebView(
int? identifier,
int? webViewIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebView,
[
identifier,
webViewIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setAllowsInlineMediaPlayback(
int? identifier,
bool? allow,
) =>
super.noSuchMethod(
Invocation.method(
#setAllowsInlineMediaPlayback,
[
identifier,
allow,
],
),
returnValueForMissingStub: null,
);
@override
void setMediaTypesRequiringUserActionForPlayback(
int? identifier,
List<_i4.WKAudiovisualMediaTypeEnumData?>? types,
) =>
super.noSuchMethod(
Invocation.method(
#setMediaTypesRequiringUserActionForPlayback,
[
identifier,
types,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKWebViewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKWebViewHostApi extends _i1.Mock
implements _i2.TestWKWebViewHostApi {
MockTestWKWebViewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? configurationIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
configurationIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setUIDelegate(
int? identifier,
int? uiDelegateIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#setUIDelegate,
[
identifier,
uiDelegateIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setNavigationDelegate(
int? identifier,
int? navigationDelegateIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#setNavigationDelegate,
[
identifier,
navigationDelegateIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
String? getUrl(int? identifier) => (super.noSuchMethod(Invocation.method(
#getUrl,
[identifier],
)) as String?);
@override
double getEstimatedProgress(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getEstimatedProgress,
[identifier],
),
returnValue: 0.0,
) as double);
@override
void loadRequest(
int? identifier,
_i4.NSUrlRequestData? request,
) =>
super.noSuchMethod(
Invocation.method(
#loadRequest,
[
identifier,
request,
],
),
returnValueForMissingStub: null,
);
@override
void loadHtmlString(
int? identifier,
String? string,
String? baseUrl,
) =>
super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[
identifier,
string,
baseUrl,
],
),
returnValueForMissingStub: null,
);
@override
void loadFileUrl(
int? identifier,
String? url,
String? readAccessUrl,
) =>
super.noSuchMethod(
Invocation.method(
#loadFileUrl,
[
identifier,
url,
readAccessUrl,
],
),
returnValueForMissingStub: null,
);
@override
void loadFlutterAsset(
int? identifier,
String? key,
) =>
super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[
identifier,
key,
],
),
returnValueForMissingStub: null,
);
@override
bool canGoBack(int? identifier) => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[identifier],
),
returnValue: false,
) as bool);
@override
bool canGoForward(int? identifier) => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[identifier],
),
returnValue: false,
) as bool);
@override
void goBack(int? identifier) => super.noSuchMethod(
Invocation.method(
#goBack,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void goForward(int? identifier) => super.noSuchMethod(
Invocation.method(
#goForward,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void reload(int? identifier) => super.noSuchMethod(
Invocation.method(
#reload,
[identifier],
),
returnValueForMissingStub: null,
);
@override
String? getTitle(int? identifier) => (super.noSuchMethod(Invocation.method(
#getTitle,
[identifier],
)) as String?);
@override
void setAllowsBackForwardNavigationGestures(
int? identifier,
bool? allow,
) =>
super.noSuchMethod(
Invocation.method(
#setAllowsBackForwardNavigationGestures,
[
identifier,
allow,
],
),
returnValueForMissingStub: null,
);
@override
void setCustomUserAgent(
int? identifier,
String? userAgent,
) =>
super.noSuchMethod(
Invocation.method(
#setCustomUserAgent,
[
identifier,
userAgent,
],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<Object?> evaluateJavaScript(
int? identifier,
String? javaScriptString,
) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavaScript,
[
identifier,
javaScriptString,
],
),
returnValue: _i3.Future<Object?>.value(),
) as _i3.Future<Object?>);
}
/// A class which mocks [TestWKWebsiteDataStoreHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKWebsiteDataStoreHostApi extends _i1.Mock
implements _i2.TestWKWebsiteDataStoreHostApi {
MockTestWKWebsiteDataStoreHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void createFromWebViewConfiguration(
int? identifier,
int? configurationIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebViewConfiguration,
[
identifier,
configurationIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void createDefaultDataStore(int? identifier) => super.noSuchMethod(
Invocation.method(
#createDefaultDataStore,
[identifier],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<bool> removeDataOfTypes(
int? identifier,
List<_i4.WKWebsiteDataTypeEnumData?>? dataTypes,
double? modificationTimeInSecondsSinceEpoch,
) =>
(super.noSuchMethod(
Invocation.method(
#removeDataOfTypes,
[
identifier,
dataTypes,
modificationTimeInSecondsSinceEpoch,
],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.mocks.dart",
"repo_id": "plugins",
"token_count": 6646
} | 1,211 |
# Currently missing: https://github.com/flutter/flutter/issues/82211
- file_selector
| plugins/script/configs/exclude_integration_web.yaml/0 | {
"file_path": "plugins/script/configs/exclude_integration_web.yaml",
"repo_id": "plugins",
"token_count": 28
} | 1,212 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:path/path.dart' as p;
import 'package:pubspec_parse/pubspec_parse.dart';
import 'core.dart';
export 'package:pubspec_parse/pubspec_parse.dart' show Pubspec;
export 'core.dart' show FlutterPlatform;
/// A package in the repository.
//
// TODO(stuartmorgan): Add more package-related info here, such as an on-demand
// cache of the parsed pubspec.
class RepositoryPackage {
/// Creates a representation of the package at [directory].
RepositoryPackage(this.directory);
/// The location of the package.
final Directory directory;
/// The path to the package.
String get path => directory.path;
/// Returns the string to use when referring to the package in user-targeted
/// messages.
///
/// Callers should not expect a specific format for this string, since
/// it uses heuristics to try to be precise without being overly verbose. If
/// an exact format (e.g., published name, or basename) is required, that
/// should be used instead.
String get displayName {
List<String> components = directory.fileSystem.path.split(directory.path);
// Remove everything up to the packages directory.
final int packagesIndex = components.indexOf('packages');
if (packagesIndex != -1) {
components = components.sublist(packagesIndex + 1);
}
// For the common federated plugin pattern of `foo/foo_subpackage`, drop
// the first part since it's not useful.
if (components.length >= 2 &&
components[1].startsWith('${components[0]}_')) {
components = components.sublist(1);
}
return p.posix.joinAll(components);
}
/// The package's top-level pubspec.yaml.
File get pubspecFile => directory.childFile('pubspec.yaml');
/// The package's top-level README.
File get readmeFile => directory.childFile('README.md');
/// The package's top-level README.
File get changelogFile => directory.childFile('CHANGELOG.md');
/// The package's top-level README.
File get authorsFile => directory.childFile('AUTHORS');
/// The lib directory containing the package's code.
Directory get libDirectory => directory.childDirectory('lib');
/// The test directory containing the package's Dart tests.
Directory get testDirectory => directory.childDirectory('test');
/// Returns the directory containing support for [platform].
Directory platformDirectory(FlutterPlatform platform) {
late final String directoryName;
switch (platform) {
case FlutterPlatform.android:
directoryName = 'android';
break;
case FlutterPlatform.ios:
directoryName = 'ios';
break;
case FlutterPlatform.linux:
directoryName = 'linux';
break;
case FlutterPlatform.macos:
directoryName = 'macos';
break;
case FlutterPlatform.web:
directoryName = 'web';
break;
case FlutterPlatform.windows:
directoryName = 'windows';
break;
}
return directory.childDirectory(directoryName);
}
late final Pubspec _parsedPubspec =
Pubspec.parse(pubspecFile.readAsStringSync());
/// Returns the parsed [pubspecFile].
///
/// Caches for future use.
Pubspec parsePubspec() => _parsedPubspec;
/// Returns true if the package depends on Flutter.
bool requiresFlutter() {
final Pubspec pubspec = parsePubspec();
return pubspec.dependencies.containsKey('flutter');
}
/// True if this appears to be a federated plugin package, according to
/// repository conventions.
bool get isFederated =>
directory.parent.basename != 'packages' &&
directory.basename.startsWith(directory.parent.basename);
/// True if this appears to be the app-facing package of a federated plugin,
/// according to repository conventions.
bool get isAppFacing =>
directory.parent.basename != 'packages' &&
directory.basename == directory.parent.basename;
/// True if this appears to be a platform interface package, according to
/// repository conventions.
bool get isPlatformInterface =>
directory.basename.endsWith('_platform_interface');
/// True if this appears to be a platform implementation package, according to
/// repository conventions.
bool get isPlatformImplementation =>
// Any part of a federated plugin that isn't the platform interface and
// isn't the app-facing package should be an implementation package.
isFederated &&
!isPlatformInterface &&
directory.basename != directory.parent.basename;
/// Returns the Flutter example packages contained in the package, if any.
Iterable<RepositoryPackage> getExamples() {
final Directory exampleDirectory = directory.childDirectory('example');
if (!exampleDirectory.existsSync()) {
return <RepositoryPackage>[];
}
if (isPackage(exampleDirectory)) {
return <RepositoryPackage>[RepositoryPackage(exampleDirectory)];
}
// Only look at the subdirectories of the example directory if the example
// directory itself is not a Dart package, and only look one level below the
// example directory for other Dart packages.
return exampleDirectory
.listSync()
.where((FileSystemEntity entity) => isPackage(entity))
// isPackage guarantees that the cast to Directory is safe.
.map((FileSystemEntity entity) =>
RepositoryPackage(entity as Directory));
}
}
| plugins/script/tool/lib/src/common/repository_package.dart/0 | {
"file_path": "plugins/script/tool/lib/src/common/repository_package.dart",
"repo_id": "plugins",
"token_count": 1709
} | 1,213 |
# android_view
An example of an Android app that integrates a Flutter add-to-app module at a
view level. For more information see [../README.md](../README.md).
| samples/add_to_app/android_view/android_view/README.md/0 | {
"file_path": "samples/add_to_app/android_view/android_view/README.md",
"repo_id": "samples",
"token_count": 48
} | 1,214 |
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
| samples/add_to_app/books/android_books/gradlew/0 | {
"file_path": "samples/add_to_app/books/android_books/gradlew",
"repo_id": "samples",
"token_count": 2352
} | 1,215 |
// Autogenerated from Pigeon (v1.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "api.h"
#import <Flutter/Flutter.h>
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
static NSDictionary<NSString *, id> *wrapResult(id result,
FlutterError *error) {
NSDictionary *errorDict = (NSDictionary *)[NSNull null];
if (error) {
errorDict = @{
@"code" : (error.code ? error.code : [NSNull null]),
@"message" : (error.message ? error.message : [NSNull null]),
@"details" : (error.details ? error.details : [NSNull null]),
};
}
return @{
@"result" : (result ? result : [NSNull null]),
@"error" : errorDict,
};
}
@interface BKBook ()
+ (BKBook *)fromMap:(NSDictionary *)dict;
- (NSDictionary *)toMap;
@end
@interface BKThumbnail ()
+ (BKThumbnail *)fromMap:(NSDictionary *)dict;
- (NSDictionary *)toMap;
@end
@implementation BKBook
+ (BKBook *)fromMap:(NSDictionary *)dict {
BKBook *result = [[BKBook alloc] init];
result.title = dict[@"title"];
if ((NSNull *)result.title == [NSNull null]) {
result.title = nil;
}
result.subtitle = dict[@"subtitle"];
if ((NSNull *)result.subtitle == [NSNull null]) {
result.subtitle = nil;
}
result.author = dict[@"author"];
if ((NSNull *)result.author == [NSNull null]) {
result.author = nil;
}
result.summary = dict[@"summary"];
if ((NSNull *)result.summary == [NSNull null]) {
result.summary = nil;
}
result.publishDate = dict[@"publishDate"];
if ((NSNull *)result.publishDate == [NSNull null]) {
result.publishDate = nil;
}
result.pageCount = dict[@"pageCount"];
if ((NSNull *)result.pageCount == [NSNull null]) {
result.pageCount = nil;
}
result.thumbnail = [BKThumbnail fromMap:dict[@"thumbnail"]];
if ((NSNull *)result.thumbnail == [NSNull null]) {
result.thumbnail = nil;
}
return result;
}
- (NSDictionary *)toMap {
return [NSDictionary
dictionaryWithObjectsAndKeys:
(self.title ? self.title : [NSNull null]), @"title",
(self.subtitle ? self.subtitle : [NSNull null]), @"subtitle",
(self.author ? self.author : [NSNull null]), @"author",
(self.summary ? self.summary : [NSNull null]), @"summary",
(self.publishDate ? self.publishDate : [NSNull null]), @"publishDate",
(self.pageCount ? self.pageCount : [NSNull null]), @"pageCount",
(self.thumbnail ? [self.thumbnail toMap] : [NSNull null]),
@"thumbnail", nil];
}
@end
@implementation BKThumbnail
+ (BKThumbnail *)fromMap:(NSDictionary *)dict {
BKThumbnail *result = [[BKThumbnail alloc] init];
result.url = dict[@"url"];
if ((NSNull *)result.url == [NSNull null]) {
result.url = nil;
}
return result;
}
- (NSDictionary *)toMap {
return [NSDictionary
dictionaryWithObjectsAndKeys:(self.url ? self.url : [NSNull null]),
@"url", nil];
}
@end
@interface BKFlutterBookApiCodecReader : FlutterStandardReader
@end
@implementation BKFlutterBookApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [BKBook fromMap:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface BKFlutterBookApiCodecWriter : FlutterStandardWriter
@end
@implementation BKFlutterBookApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[BKBook class]]) {
[self writeByte:128];
[self writeValue:[value toMap]];
} else {
[super writeValue:value];
}
}
@end
@interface BKFlutterBookApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation BKFlutterBookApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[BKFlutterBookApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[BKFlutterBookApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *BKFlutterBookApiGetCodec() {
static dispatch_once_t s_pred = 0;
static FlutterStandardMessageCodec *s_sharedObject = nil;
dispatch_once(&s_pred, ^{
BKFlutterBookApiCodecReaderWriter *readerWriter =
[[BKFlutterBookApiCodecReaderWriter alloc] init];
s_sharedObject =
[FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return s_sharedObject;
}
@interface BKFlutterBookApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation BKFlutterBookApi
- (instancetype)initWithBinaryMessenger:
(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)displayBookDetailsBook:(BKBook *)arg_book
completion:(void (^)(NSError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.FlutterBookApi.displayBookDetails"
binaryMessenger:self.binaryMessenger
codec:BKFlutterBookApiGetCodec()];
[channel sendMessage:@[ arg_book ]
reply:^(id reply) {
completion(nil);
}];
}
@end
@interface BKHostBookApiCodecReader : FlutterStandardReader
@end
@implementation BKHostBookApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [BKBook fromMap:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface BKHostBookApiCodecWriter : FlutterStandardWriter
@end
@implementation BKHostBookApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[BKBook class]]) {
[self writeByte:128];
[self writeValue:[value toMap]];
} else {
[super writeValue:value];
}
}
@end
@interface BKHostBookApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation BKHostBookApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[BKHostBookApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[BKHostBookApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *BKHostBookApiGetCodec() {
static dispatch_once_t s_pred = 0;
static FlutterStandardMessageCodec *s_sharedObject = nil;
dispatch_once(&s_pred, ^{
BKHostBookApiCodecReaderWriter *readerWriter =
[[BKHostBookApiCodecReaderWriter alloc] init];
s_sharedObject =
[FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return s_sharedObject;
}
void BKHostBookApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<BKHostBookApi> *api) {
{
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.HostBookApi.cancel"
binaryMessenger:binaryMessenger
codec:BKHostBookApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(cancelWithError:)],
@"BKHostBookApi api doesn't respond to @selector(cancelWithError:)");
[channel
setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api cancelWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.HostBookApi.finishEditingBook"
binaryMessenger:binaryMessenger
codec:BKHostBookApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(finishEditingBookBook:
error:)],
@"BKHostBookApi api doesn't respond to "
@"@selector(finishEditingBookBook:error:)");
[channel
setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
BKBook *arg_book = args[0];
FlutterError *error;
[api finishEditingBookBook:arg_book error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| samples/add_to_app/books/ios_books/IosBooks/api.m/0 | {
"file_path": "samples/add_to_app/books/ios_books/IosBooks/api.m",
"repo_id": "samples",
"token_count": 3472
} | 1,216 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
import UIKit
/// The app's UIApplicationDelegate.
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
let engines = FlutterEngineGroup(name: "multiple-flutters", project: nil)
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
#if DEBUG
let isDebug = true
#else
let isDebug = false
#endif
if isDebug {
NSLog(
"📣 NOTICE: the memory and CPU costs for Flutter engine groups are significantly greater in debug builds. See also: https://github.com/dart-lang/sdk/issues/36097"
)
} else {
NSLog(
"📣 NOTICE: the memory and CPU costs for Flutter engine groups are significantly less here than in debug builds. See also: https://github.com/dart-lang/sdk/issues/36097"
)
}
return true
}
func application(
_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
return UISceneConfiguration(
name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(
_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>
) {
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/AppDelegate.swift/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/AppDelegate.swift",
"repo_id": "samples",
"token_count": 503
} | 1,217 |
# multiple_flutters_module
This is the Flutter module that is embedded in the `multiple_flutters` projects.
See also: [multiple_flutters/README.md](../README.md) | samples/add_to_app/multiple_flutters/multiple_flutters_module/README.md/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_module/README.md",
"repo_id": "samples",
"token_count": 50
} | 1,218 |
# Splash Screen Sample
A Flutter app that exemplifies how to implement an animated splash screen for Android devices running at least Android 12, the version that supplies the new [SplashScreen API](https://developer.android.com/about/versions/12/features/splash-screen).
**NOTE:** There is a pub package available to implement static splash screens in your Flutter app: [flutter_native_splash](https://pub.dev/packages/flutter_native_splash).
## Goals
- Demonstrate the compatibility of animated splash screens and Flutter apps running on Android
- Demonstrate the smoothness achievable by a splash screen as a transition to the Flutter UI
## The important bits
### Remove deprecated code
When creating a Flutter app, the Android code generated may include the deprecated implementation of a splash screen. This includes a definition of `io.flutter.embedding.android.SplashScreenDrawable` in the ` /android/app/src/main/AndroidManifest.xml` file and an implementation of `provideSplashScreen()` in the `/android/app/src/main/kotlin/MainActivity.kt` file. Make sure to remove this code.
**NOTE:** This should no longer be a concern as of Flutter 2.5.
### Modify Android build files
In order to support the Android 12 SplashScreen API, you need to:
1. Update the Android `compileSdkVersion` to 31 in the `/android/app/build.gradle` file, and
2. Update the `ext.kotlin_version` to the latest Kotlin extension version (1.5.31 at the time of publication) in the `/android/build.gradle` file.
### Timing the splash screen animation
In order to ensure a smooth transition between the animated splash screen and the Flutter UI displaying for the first time, be sure to handle both the case where the Flutter UI is ready to be displayed before the animation finishes and vice versa. This can be done by overriding `onFlutterUiDisplayed()` and `onFlutterUiNoLongerDisplayed()` in `/android/app/src/main/kotlin/com/example/splash-screen-sample/MainActivity.kt`, the implementation of `FlutterActivity` in this project.
## Questions/Issues
If you have a general question about splash screens or their implementation in Flutter, the best places to go are:
* [Android 12 Splash Screen Documentation](https://developer.android.com/about/versions/12/features/splash-screen)
* [Flutter Guidance on Adding a Splash Screen to Your App](https://flutter.dev/docs/development/ui/advanced/splash-screen?tab=android-splash-alignment-kotlin-tab)
If you run into an issue with the sample itself, please file an issue
in the [main Flutter repo](https://github.com/flutter/flutter/issues).
| samples/android_splash_screen/README.md/0 | {
"file_path": "samples/android_splash_screen/README.md",
"repo_id": "samples",
"token_count": 681
} | 1,219 |
# Animation Samples
Sample apps that showcase Flutter's animation features
## Goals
- Demonstrate the building blocks for animations and how they work together.
- Provide samples for common patterns and use-cases.
## Samples
### Basics
Building blocks and patterns
1. **AnimatedContainerDemo**: Demonstrates how to use `AnimatedContainer`.
2. **PageRouteBuilderDemo**: Demonstrates how to use `Tween` and `Animation` to
build a custom page route transition.
3. **AnimationControllerDemo**: Demonstrates how to use an
`AnimationController`.
4. **TweenDemo**: Demonstrates how to use a `Tween` with an
`AnimationController`.
5. **AnimatedBuilderDemo**: Demonstrates how to use an `AnimatedBuilder` with an
`AnimationController`.
6. **CustomTweenDemo**: Demonstrates how to extend `Tween`.
7. **TweenSequenceDemo**: Demonstrates how to use `TweenSequence` to build a
button that changes between different colors.
8. **FadeTransitionDemo**: Demonstrates how to use `FadeTransition`.
### Misc
Other uses-cases and examples
- **RepeatingAnimationDemo**: Demonstrates how to repeat an animation.
- **ExpandCardDemo**: Demonstrates how to use `AnimatedCrossFade` to fade
between two widgets and change the size.
- **CarouselDemo**: Demonstrates how to use `PageView` with a custom animation.
- **FocusImageDemo**: Demonstrates how to measure the size of a widget and
expand it using a `PageRouteBuilder`.
- **PhysicsCardDragDemo**: Demonstrates how to run an AnimationController with a
spring simulation.
- **CardSwipeDemo**: A swipeable card that demonstrates how to use gesture
detection to drive an animation.
- **AnimatedList**: Demonstrates how to use `AnimatedList`.
- **AnimatedPositionedDemo**: Demonstrates how to use `AnimatedPositioned`.
- **AnimatedSwitcherDemo**: Demonstrates how to use `AnimatedSwitcher`.
- **HeroAnimationDemo**: Demonstrates how to use `Hero` animation.
- **CurvedAnimationDemo**: Demonstrates how to use different curves in
`CurvedAnimation`.
## Other Resources
- [Introduction to animations](https://flutter.dev/docs/development/ui/animations)
- [Animation widgets](https://flutter.dev/docs/development/ui/widgets/animation)
- [Flutter cookbook - Animations](https://flutter.dev/docs/cookbook/animation)
- [Animations tutorial](https://flutter.dev/docs/development/ui/animations/tutorial)
- [Implicit animation codelab](https://flutter.dev/docs/codelabs/implicit-animations)
| samples/animations/README.md/0 | {
"file_path": "samples/animations/README.md",
"repo_id": "samples",
"token_count": 713
} | 1,220 |
// Copyright 2019 The Flutter team. 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/physics.dart';
class CardSwipeDemo extends StatefulWidget {
const CardSwipeDemo({super.key});
static String routeName = 'misc/card_swipe';
@override
State<CardSwipeDemo> createState() => _CardSwipeDemoState();
}
class _CardSwipeDemoState extends State<CardSwipeDemo> {
late List<String> fileNames;
@override
void initState() {
super.initState();
_resetCards();
}
void _resetCards() {
fileNames = [
'assets/eat_cape_town_sm.jpg',
'assets/eat_new_orleans_sm.jpg',
'assets/eat_sydney_sm.jpg',
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Card Swipe'),
),
body: Padding(
padding: const EdgeInsets.all(12.0),
child: Center(
child: Column(
children: [
Expanded(
child: ClipRect(
child: Stack(
children: [
for (final fileName in fileNames)
SwipeableCard(
imageAssetName: fileName,
onSwiped: () {
setState(() {
fileNames.remove(fileName);
});
},
),
],
),
),
),
ElevatedButton(
child: const Text('Refill'),
onPressed: () {
setState(() {
_resetCards();
});
},
),
],
),
),
),
);
}
}
class Card extends StatelessWidget {
final String imageAssetName;
const Card({required this.imageAssetName, super.key});
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 3 / 5,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
image: DecorationImage(
image: AssetImage(imageAssetName),
fit: BoxFit.cover,
),
),
),
);
}
}
class SwipeableCard extends StatefulWidget {
final String imageAssetName;
final VoidCallback onSwiped;
const SwipeableCard(
{required this.onSwiped, required this.imageAssetName, super.key});
@override
State<SwipeableCard> createState() => _SwipeableCardState();
}
class _SwipeableCardState extends State<SwipeableCard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _animation;
late double _dragStartX;
bool _isSwipingLeft = false;
@override
void initState() {
super.initState();
_controller = AnimationController.unbounded(vsync: this);
_animation = _controller.drive(Tween<Offset>(
begin: Offset.zero,
end: const Offset(1, 0),
));
}
@override
Widget build(BuildContext context) {
return SlideTransition(
position: _animation,
child: GestureDetector(
onHorizontalDragStart: _dragStart,
onHorizontalDragUpdate: _dragUpdate,
onHorizontalDragEnd: _dragEnd,
child: Card(imageAssetName: widget.imageAssetName),
),
);
}
/// Sets the starting position the user dragged from.
void _dragStart(DragStartDetails details) {
_dragStartX = details.localPosition.dx;
}
/// Changes the animation to animate to the left or right depending on the
/// swipe, and sets the AnimationController's value to the swiped amount.
void _dragUpdate(DragUpdateDetails details) {
var isSwipingLeft = (details.localPosition.dx - _dragStartX) < 0;
if (isSwipingLeft != _isSwipingLeft) {
_isSwipingLeft = isSwipingLeft;
_updateAnimation(details.localPosition.dx);
}
setState(() {
final size = context.size;
if (size == null) {
return;
}
// Calculate the amount dragged in unit coordinates (between 0 and 1)
// using this widgets width.
_controller.value =
(details.localPosition.dx - _dragStartX).abs() / size.width;
});
}
/// Runs the fling / spring animation using the final velocity of the drag
/// gesture.
void _dragEnd(DragEndDetails details) {
final size = context.size;
if (size == null) {
return;
}
var velocity = (details.velocity.pixelsPerSecond.dx / size.width).abs();
_animate(velocity: velocity);
}
void _updateAnimation(double dragPosition) {
_animation = _controller.drive(Tween<Offset>(
begin: Offset.zero,
end: _isSwipingLeft ? const Offset(-1, 0) : const Offset(1, 0),
));
}
void _animate({double velocity = 0}) {
var description =
const SpringDescription(mass: 50, stiffness: 1, damping: 1);
var simulation =
SpringSimulation(description, _controller.value, 1, velocity);
_controller.animateWith(simulation).then<void>((_) {
widget.onSwiped();
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
| samples/animations/lib/src/misc/card_swipe.dart/0 | {
"file_path": "samples/animations/lib/src/misc/card_swipe.dart",
"repo_id": "samples",
"token_count": 2337
} | 1,221 |
name: animations
description: A new Flutter project.
version: 1.0.0+1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
flutter_animate: ^4.1.0
go_router: ^13.0.0
window_size: # plugin is not yet part of the flutter framework
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
fonts:
- family: SpecialElite
fonts:
- asset: fonts/SpecialElite-Regular.ttf
| samples/animations/pubspec.yaml/0 | {
"file_path": "samples/animations/pubspec.yaml",
"repo_id": "samples",
"token_count": 261
} | 1,222 |
name: server
description: A server app using the shelf package and Docker.
version: 1.0.0
publish_to: "none"
environment:
sdk: ^3.2.0
dependencies:
args: ^2.0.0
shelf: ^1.1.0
shelf_router: ^1.0.0
shared:
path: ../shared
dev_dependencies:
http: ^1.0.0
lints: ^3.0.0
test: ^1.15.0
| samples/code_sharing/server/pubspec.yaml/0 | {
"file_path": "samples/code_sharing/server/pubspec.yaml",
"repo_id": "samples",
"token_count": 138
} | 1,223 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/context_menus/android/gradle.properties/0 | {
"file_path": "samples/context_menus/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,224 |
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'platform_selector.dart';
class CustomMenuPage extends StatelessWidget {
CustomMenuPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'custom-menu';
static const String title = 'Custom Menu';
static const String subtitle =
'A custom menu built from scratch, but using the default buttons.';
final PlatformCallback onChangedPlatform;
final TextEditingController _controller = TextEditingController(
text: 'Show the menu to see a custom menu with the default buttons.',
);
static const String url = '$kCodeUrl/custom_menu_page.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(CustomMenuPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Center(
child: SizedBox(
width: 300.0,
child: TextField(
controller: _controller,
maxLines: 4,
minLines: 2,
contextMenuBuilder: (context, editableTextState) {
return _MyContextMenu(
anchor: editableTextState.contextMenuAnchors.primaryAnchor,
children: AdaptiveTextSelectionToolbar.getAdaptiveButtons(
context,
editableTextState.contextMenuButtonItems,
).toList(),
);
},
),
),
),
);
}
}
class _MyContextMenu extends StatelessWidget {
const _MyContextMenu({
required this.anchor,
required this.children,
});
final Offset anchor;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Positioned(
top: anchor.dy,
left: anchor.dx,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.amberAccent,
child: Column(
children: children,
),
),
),
],
);
}
}
| samples/context_menus/lib/custom_menu_page.dart/0 | {
"file_path": "samples/context_menus/lib/custom_menu_page.dart",
"repo_id": "samples",
"token_count": 1129
} | 1,225 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
// Returns the first RenderEditable.
RenderEditable findRenderEditable(WidgetTester tester) {
final RenderObject root = tester.renderObject(find.byType(EditableText));
expect(root, isNotNull);
late RenderEditable renderEditable;
void recursiveFinder(RenderObject child) {
if (child is RenderEditable) {
renderEditable = child;
return;
}
child.visitChildren(recursiveFinder);
}
root.visitChildren(recursiveFinder);
expect(renderEditable, isNotNull);
return renderEditable;
}
Offset textOffsetToPosition(WidgetTester tester, int offset) {
final RenderEditable renderEditable = findRenderEditable(tester);
final List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(
TextSelection.collapsed(offset: offset),
),
renderEditable,
);
expect(endpoints.length, 1);
return endpoints[0].point + const Offset(kIsWeb ? 1.0 : 0.0, -2.0);
}
List<TextSelectionPoint> globalize(
Iterable<TextSelectionPoint> points, RenderBox box) {
return points.map<TextSelectionPoint>((point) {
return TextSelectionPoint(
box.localToGlobal(point.point),
point.direction,
);
}).toList();
}
| samples/context_menus/test/utils.dart/0 | {
"file_path": "samples/context_menus/test/utils.dart",
"repo_id": "samples",
"token_count": 484
} | 1,226 |
# Photo Search app
This desktop application enables you to search
[Unsplash](https://unsplash.com/) for photographs that interest you.
To use it, you need to add an **Access Key** from
[Unsplash API](https://unsplash.com/developers) to
`lib/unsplash_access_key.dart`.
This is the Photo Search app, built out with two different widget sets:
- [Material](material) shows the Photo Search app built with [Material widgets][]
- [Fluent UI](fluent_ui) shows the Photo Search app built with [Fluent UI][] widgets
[Fluent UI]: https://pub.dev/packages/fluent_ui
[Material widgets]: https://docs.flutter.dev/development/ui/widgets/material
| samples/desktop_photo_search/README.md/0 | {
"file_path": "samples/desktop_photo_search/README.md",
"repo_id": "samples",
"token_count": 191
} | 1,227 |
// Copyright 2019 The Flutter team. 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 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
part 'exif.g.dart';
abstract class Exif implements Built<Exif, ExifBuilder> {
factory Exif([void Function(ExifBuilder)? updates]) = _$Exif;
Exif._();
@BuiltValueField(wireName: 'make')
String? get make;
@BuiltValueField(wireName: 'model')
String? get model;
@BuiltValueField(wireName: 'exposure_time')
String? get exposureTime;
@BuiltValueField(wireName: 'aperture')
String? get aperture;
@BuiltValueField(wireName: 'focal_length')
String? get focalLength;
@BuiltValueField(wireName: 'iso')
int? get iso;
String toJson() {
return json.encode(serializers.serializeWith(Exif.serializer, this));
}
static Exif? fromJson(String jsonString) {
return serializers.deserializeWith(
Exif.serializer, json.decode(jsonString));
}
static Serializer<Exif> get serializer => _$exifSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/exif.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/exif.dart",
"repo_id": "samples",
"token_count": 392
} | 1,228 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'urls.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Urls> _$urlsSerializer = new _$UrlsSerializer();
class _$UrlsSerializer implements StructuredSerializer<Urls> {
@override
final Iterable<Type> types = const [Urls, _$Urls];
@override
final String wireName = 'Urls';
@override
Iterable<Object?> serialize(Serializers serializers, Urls object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[];
Object? value;
value = object.raw;
if (value != null) {
result
..add('raw')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.full;
if (value != null) {
result
..add('full')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.regular;
if (value != null) {
result
..add('regular')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.small;
if (value != null) {
result
..add('small')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.thumb;
if (value != null) {
result
..add('thumb')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
return result;
}
@override
Urls deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new UrlsBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'raw':
result.raw = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'full':
result.full = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'regular':
result.regular = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'small':
result.small = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'thumb':
result.thumb = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
}
}
return result.build();
}
}
class _$Urls extends Urls {
@override
final String? raw;
@override
final String? full;
@override
final String? regular;
@override
final String? small;
@override
final String? thumb;
factory _$Urls([void Function(UrlsBuilder)? updates]) =>
(new UrlsBuilder()..update(updates))._build();
_$Urls._({this.raw, this.full, this.regular, this.small, this.thumb})
: super._();
@override
Urls rebuild(void Function(UrlsBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
UrlsBuilder toBuilder() => new UrlsBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Urls &&
raw == other.raw &&
full == other.full &&
regular == other.regular &&
small == other.small &&
thumb == other.thumb;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, raw.hashCode);
_$hash = $jc(_$hash, full.hashCode);
_$hash = $jc(_$hash, regular.hashCode);
_$hash = $jc(_$hash, small.hashCode);
_$hash = $jc(_$hash, thumb.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Urls')
..add('raw', raw)
..add('full', full)
..add('regular', regular)
..add('small', small)
..add('thumb', thumb))
.toString();
}
}
class UrlsBuilder implements Builder<Urls, UrlsBuilder> {
_$Urls? _$v;
String? _raw;
String? get raw => _$this._raw;
set raw(String? raw) => _$this._raw = raw;
String? _full;
String? get full => _$this._full;
set full(String? full) => _$this._full = full;
String? _regular;
String? get regular => _$this._regular;
set regular(String? regular) => _$this._regular = regular;
String? _small;
String? get small => _$this._small;
set small(String? small) => _$this._small = small;
String? _thumb;
String? get thumb => _$this._thumb;
set thumb(String? thumb) => _$this._thumb = thumb;
UrlsBuilder();
UrlsBuilder get _$this {
final $v = _$v;
if ($v != null) {
_raw = $v.raw;
_full = $v.full;
_regular = $v.regular;
_small = $v.small;
_thumb = $v.thumb;
_$v = null;
}
return this;
}
@override
void replace(Urls other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Urls;
}
@override
void update(void Function(UrlsBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Urls build() => _build();
_$Urls _build() {
final _$result = _$v ??
new _$Urls._(
raw: raw, full: full, regular: regular, small: small, thumb: thumb);
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/urls.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/urls.g.dart",
"repo_id": "samples",
"token_count": 2398
} | 1,229 |
name: desktop_photo_search
description: Search for Photos, using the Unsplash API.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
built_collection: ^5.1.1
built_value: ^8.6.1
cupertino_icons: ^1.0.5
file_selector: ^1.0.0
fluent_ui: ^4.7.2
fluentui_system_icons: ^1.1.208
flutter:
sdk: flutter
http: ^1.2.1
logging: ^1.2.0
menubar:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/menubar
provider: ^6.0.5
transparent_image: ^2.0.1
url_launcher: ^6.1.12
uuid: ^4.0.0
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
dev_dependencies:
analysis_defaults:
path: ../../analysis_defaults
async: ^2.11.0
build: ^2.4.1
build_runner: ^2.4.6
built_value_generator: ^8.6.1
flutter_test:
sdk: flutter
grinder: ^0.9.4
msix: ^3.16.1
flutter:
uses-material-design: true
msix_config:
display_name: Flutter Desktop Photo Search
publisher_display_name: flutter.dev
store: false # Set to true to deploy to Microsoft Store
publisher: CN=01A6D5C0-D51A-4EEE-8DD0-F134DDD378F7
identity_name: 16354flutter.dev.FlutterDesktopPhotoSearch
msix_version: 1.0.0.1
icons_background_color: "#ffffff"
architecture: x64
# See https://docs.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations
capabilities: "internetClient"
| samples/desktop_photo_search/fluent_ui/pubspec.yaml/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/pubspec.yaml",
"repo_id": "samples",
"token_count": 610
} | 1,230 |
package dev.flutter.federated_plugin_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/experimental/federated_plugin/federated_plugin/example/android/app/src/main/kotlin/dev/flutter/federated_plugin_example/MainActivity.kt/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/android/app/src/main/kotlin/dev/flutter/federated_plugin_example/MainActivity.kt",
"repo_id": "samples",
"token_count": 43
} | 1,231 |
#import <Flutter/Flutter.h>
@interface FederatedPlugin : NSObject<FlutterPlugin>
@end
| samples/experimental/federated_plugin/federated_plugin/ios/Classes/FederatedPlugin.h/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/ios/Classes/FederatedPlugin.h",
"repo_id": "samples",
"token_count": 30
} | 1,232 |
// Copyright 2021 The Flutter team. 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:linting_tool/model/profile.dart';
import 'package:linting_tool/model/profiles_store.dart';
import 'package:linting_tool/model/rule.dart';
/// Used to control editing of the saved profiles on the RulesPage.
class EditingController extends ChangeNotifier {
bool _isEditing;
EditingController({bool isEditing = false}) : _isEditing = isEditing;
bool get isEditing => _isEditing;
set isEditing(bool enabled) {
_selectedRules.clear();
_isEditing = enabled;
notifyListeners();
}
final Set<Rule> _selectedRules = {};
Set<Rule> get selectedRules => _selectedRules;
void selectRule(Rule rule) {
_selectedRules.add(rule);
notifyListeners();
}
void deselectRule(Rule rule) {
_selectedRules.remove(rule);
notifyListeners();
}
Future deleteSelected(
RulesProfile profile, ProfilesStore profilesStore) async {
final rules = profile.rules;
rules.removeWhere((rule) => _selectedRules.contains(rule));
final newProfile = RulesProfile(name: profile.name, rules: rules);
await profilesStore.updateProfile(profile, newProfile);
isEditing = false;
notifyListeners();
}
}
| samples/experimental/linting_tool/lib/model/editing_controller.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/model/editing_controller.dart",
"repo_id": "samples",
"token_count": 434
} | 1,233 |
// Copyright 2021 The Flutter team. 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_markdown/flutter_markdown.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:linting_tool/theme/colors.dart';
abstract class AppTheme {
static ThemeData buildReplyLightTheme(BuildContext context) {
final base = ThemeData.light();
return base.copyWith(
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: AppColors.blue700,
modalBackgroundColor: Colors.white.withOpacity(0.7),
),
navigationRailTheme: NavigationRailThemeData(
backgroundColor: AppColors.blue700,
selectedIconTheme: const IconThemeData(
color: AppColors.orange500,
),
selectedLabelTextStyle:
GoogleFonts.workSansTextTheme().headlineSmall!.copyWith(
color: AppColors.orange500,
),
unselectedIconTheme: const IconThemeData(
color: AppColors.blue200,
),
unselectedLabelTextStyle:
GoogleFonts.workSansTextTheme().headlineSmall!.copyWith(
color: AppColors.blue200,
),
),
canvasColor: AppColors.white50,
cardColor: AppColors.white50,
chipTheme: _buildChipTheme(
AppColors.blue700,
AppColors.lightChipBackground,
Brightness.light,
),
colorScheme: ColorScheme.fromSwatch(
primarySwatch: Colors.blueGrey,
),
textTheme: _buildReplyLightTextTheme(base.textTheme),
scaffoldBackgroundColor: AppColors.blue50,
bottomAppBarTheme: const BottomAppBarTheme(color: AppColors.blue700),
);
}
static ThemeData buildReplyDarkTheme(BuildContext context) {
final base = ThemeData.dark();
return base.copyWith(
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: AppColors.darkDrawerBackground,
modalBackgroundColor: Colors.black.withOpacity(0.7),
),
navigationRailTheme: NavigationRailThemeData(
backgroundColor: AppColors.darkBottomAppBarBackground,
selectedIconTheme: const IconThemeData(
color: AppColors.orange300,
),
selectedLabelTextStyle:
GoogleFonts.workSansTextTheme().headlineSmall!.copyWith(
color: AppColors.orange300,
),
unselectedIconTheme: const IconThemeData(
color: AppColors.greyLabel,
),
unselectedLabelTextStyle:
GoogleFonts.workSansTextTheme().headlineSmall!.copyWith(
color: AppColors.greyLabel,
),
),
canvasColor: AppColors.black900,
cardColor: AppColors.darkCardBackground,
chipTheme: _buildChipTheme(
AppColors.blue200,
AppColors.darkChipBackground,
Brightness.dark,
),
colorScheme: const ColorScheme.dark(
primary: AppColors.blue200,
secondary: AppColors.orange300,
surface: AppColors.black800,
error: AppColors.red200,
onPrimary: AppColors.black900,
onSecondary: AppColors.black900,
onBackground: AppColors.white50,
onSurface: AppColors.white50,
onError: AppColors.black900,
background: AppColors.black900Alpha087,
),
textTheme: _buildReplyDarkTextTheme(base.textTheme),
scaffoldBackgroundColor: AppColors.black900,
bottomAppBarTheme:
const BottomAppBarTheme(color: AppColors.darkBottomAppBarBackground),
);
}
static ChipThemeData _buildChipTheme(
Color primaryColor,
Color chipBackground,
Brightness brightness,
) {
return ChipThemeData(
backgroundColor: primaryColor.withOpacity(0.12),
disabledColor: primaryColor.withOpacity(0.87),
selectedColor: primaryColor.withOpacity(0.05),
secondarySelectedColor: chipBackground,
padding: const EdgeInsets.all(4),
shape: const StadiumBorder(),
labelStyle: GoogleFonts.workSansTextTheme().bodyMedium!.copyWith(
color: brightness == Brightness.dark
? AppColors.white50
: AppColors.black900,
),
secondaryLabelStyle: GoogleFonts.workSansTextTheme().bodyMedium!,
brightness: brightness,
);
}
static TextTheme _buildReplyLightTextTheme(TextTheme base) {
return base.copyWith(
headlineMedium: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 34,
letterSpacing: 0.4,
height: 0.9,
color: AppColors.black900,
),
headlineSmall: GoogleFonts.workSans(
fontWeight: FontWeight.bold,
fontSize: 24,
letterSpacing: 0.27,
color: AppColors.black900,
),
titleLarge: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 20,
letterSpacing: 0.18,
color: AppColors.black900,
),
titleSmall: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 14,
letterSpacing: -0.04,
color: AppColors.black900,
),
bodyLarge: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 18,
letterSpacing: 0.2,
color: AppColors.black900,
),
bodyMedium: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 14,
letterSpacing: -0.05,
color: AppColors.black900,
),
bodySmall: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 12,
letterSpacing: 0.2,
color: AppColors.black900,
),
);
}
static TextTheme _buildReplyDarkTextTheme(TextTheme base) {
return base.copyWith(
headlineMedium: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 34,
letterSpacing: 0.4,
height: 0.9,
color: AppColors.white50,
),
headlineSmall: GoogleFonts.workSans(
fontWeight: FontWeight.bold,
fontSize: 24,
letterSpacing: 0.27,
color: AppColors.white50,
),
titleLarge: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 20,
letterSpacing: 0.18,
color: AppColors.white50,
),
titleSmall: GoogleFonts.workSans(
fontWeight: FontWeight.w600,
fontSize: 14,
letterSpacing: -0.04,
color: AppColors.white50,
),
bodyLarge: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 18,
letterSpacing: 0.2,
color: AppColors.white50,
),
bodyMedium: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 14,
letterSpacing: -0.05,
color: AppColors.white50,
),
bodySmall: GoogleFonts.workSans(
fontWeight: FontWeight.normal,
fontSize: 12,
letterSpacing: 0.2,
color: AppColors.white50,
),
);
}
static MarkdownStyleSheet buildMarkDownTheme(ThemeData theme) {
final textTheme = theme.textTheme;
return MarkdownStyleSheet.largeFromTheme(theme).copyWith(
strong: textTheme.titleSmall!,
em: textTheme.bodyMedium!.copyWith(
fontWeight: FontWeight.w900,
fontStyle: FontStyle.italic,
),
codeblockPadding: const EdgeInsets.all(8),
codeblockDecoration: BoxDecoration(
color: Colors.grey.shade100,
),
code: TextStyle(
backgroundColor: Colors.grey.shade100,
),
);
}
}
| samples/experimental/linting_tool/lib/theme/app_theme.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/theme/app_theme.dart",
"repo_id": "samples",
"token_count": 3378
} | 1,234 |
import 'dart:async';
import 'dart:collection';
import 'dart:ffi' as ffi;
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:jni/jni.dart' as jni;
import 'package:pedometer/pedometer_bindings_generated.dart' as pd;
import 'package:pedometer/health_connect.dart' as hc;
/// Class to hold the information needed for the chart
class Steps {
String startHour;
int steps;
Steps(this.startHour, this.steps);
}
abstract class StepsRepo {
static const _formatString = "yyyy-MM-dd HH:mm:ss";
static StepsRepo? _instance;
static StepsRepo get instance =>
_instance ??= Platform.isAndroid ? _AndroidStepsRepo() : _IOSStepsRepo();
Future<List<Steps>> getSteps();
}
class _IOSStepsRepo implements StepsRepo {
static const _dylibPath =
'/System/Library/Frameworks/CoreMotion.framework/CoreMotion';
// Bindings for the CMPedometer class
final lib = pd.PedometerBindings(ffi.DynamicLibrary.open(_dylibPath));
// Bindings for the helper function
final helpLib = pd.PedometerBindings(ffi.DynamicLibrary.process());
late final pd.CMPedometer client;
late final pd.NSDateFormatter formatter;
late final pd.NSDateFormatter hourFormatter;
_IOSStepsRepo() {
// Contains the Dart API helper functions
final dylib = ffi.DynamicLibrary.open("pedometer.framework/pedometer");
// Initialize the Dart API
final initializeApi = dylib.lookupFunction<
ffi.IntPtr Function(ffi.Pointer<ffi.Void>),
int Function(ffi.Pointer<ffi.Void>)>('Dart_InitializeApiDL');
final initializeResult = initializeApi(ffi.NativeApi.initializeApiDLData);
if (initializeResult != 0) {
throw StateError('failed to init API.');
}
// Create a new CMPedometer instance.
client = pd.CMPedometer.new1(lib);
// Setting the formatter for date strings.
formatter =
pd.NSDateFormatter.castFrom(pd.NSDateFormatter.alloc(lib).init());
formatter.dateFormat = pd.NSString(lib, "${StepsRepo._formatString} zzz");
hourFormatter =
pd.NSDateFormatter.castFrom(pd.NSDateFormatter.alloc(lib).init());
hourFormatter.dateFormat = pd.NSString(lib, "HH");
}
pd.NSDate dateConverter(DateTime dartDate) {
// Format dart date to string.
final formattedDate = DateFormat(StepsRepo._formatString).format(dartDate);
// Get current timezone. If eastern african change to AST to follow with NSDate.
final tz = dartDate.timeZoneName == "EAT" ? "AST" : dartDate.timeZoneName;
// Create a new NSString with the formatted date and timezone.
final nString = pd.NSString(lib, "$formattedDate $tz");
// Convert the NSString to NSDate.
return formatter.dateFromString_(nString)!;
}
@override
Future<List<Steps>> getSteps() async {
if (!pd.CMPedometer.isStepCountingAvailable(lib)) {
debugPrint("Step counting is not available.");
return [];
}
final handlers = [];
final futures = <Future<Steps?>>[];
final now = DateTime.now();
for (var h = 0; h <= now.hour; h++) {
final start = dateConverter(DateTime(now.year, now.month, now.day, h));
final end = dateConverter(DateTime(now.year, now.month, now.day, h + 1));
final completer = Completer<Steps?>();
futures.add(completer.future);
final handler = helpLib.wrapCallback(
pd.ObjCBlock_ffiVoid_CMPedometerData_NSError.listener(lib,
(pd.CMPedometerData? result, pd.NSError? error) {
if (result != null) {
final stepCount = result.numberOfSteps.intValue;
final startHour =
hourFormatter.stringFromDate_(result.startDate).toString();
completer.complete(Steps(startHour, stepCount));
} else {
debugPrint("Query error: ${error?.localizedDescription}");
completer.complete(null);
}
}));
handlers.add(handler);
client.queryPedometerDataFromDate_toDate_withHandler_(
start, end, handler);
}
return (await Future.wait(futures)).nonNulls.toList();
}
}
class _AndroidStepsRepo implements StepsRepo {
late final hc.Activity activity;
late final hc.Context applicationContext;
late final hc.HealthConnectClient client;
_AndroidStepsRepo() {
jni.Jni.initDLApi();
activity = hc.Activity.fromRef(jni.Jni.getCurrentActivity());
applicationContext =
hc.Context.fromRef(jni.Jni.getCachedApplicationContext());
client = hc.HealthConnectClient.getOrCreate1(applicationContext);
}
@override
Future<List<Steps>> getSteps() async {
final futures = <Future<hc.AggregationResult>>[];
final now = DateTime.now();
for (var h = 0; h <= now.hour; h++) {
final start =
DateTime(now.year, now.month, now.day, h).millisecondsSinceEpoch;
final end =
DateTime(now.year, now.month, now.day, h + 1).millisecondsSinceEpoch;
final request = hc.AggregateRequest(
{hc.StepsRecord.COUNT_TOTAL}
.toJSet(hc.AggregateMetric.type(jni.JLong.type)),
hc.TimeRangeFilter.between(
hc.Instant.ofEpochMilli(start),
hc.Instant.ofEpochMilli(end),
),
jni.JSet.hash(jni.JObject.type),
);
futures.add(client.aggregate(request));
}
final data = await Future.wait(futures);
return data.asMap().entries.map((entry) {
final stepsLong = entry.value.get0(hc.StepsRecord.COUNT_TOTAL);
final steps = stepsLong.isNull ? 0 : stepsLong.intValue();
return Steps(entry.key.toString().padLeft(2, '0'), steps);
}).toList();
}
}
| samples/experimental/pedometer/example/lib/steps_repo.dart/0 | {
"file_path": "samples/experimental/pedometer/example/lib/steps_repo.dart",
"repo_id": "samples",
"token_count": 2189
} | 1,235 |
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
#define RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
typedef struct {
const char* name;
void (*function)();
} DartApiEntry;
typedef struct {
const int major;
const int minor;
const DartApiEntry* const functions;
} DartApi;
#endif /* RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ */ /* NOLINT */
| samples/experimental/pedometer/src/dart-sdk/include/internal/dart_api_dl_impl.h/0 | {
"file_path": "samples/experimental/pedometer/src/dart-sdk/include/internal/dart_api_dl_impl.h",
"repo_id": "samples",
"token_count": 215
} | 1,236 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,237 |
// Copyright 2023 The Flutter team. 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:varfont_shader_puzzle/main.dart';
void main() {
const welcomeText =
'Welcome to your first day on the FontCo team! Are you ready to help us publish our newest font, Designer Pro?';
const welcomeTextStep2 =
'Oh no, you clicked the button too hard! Now the font file is glitched. Help us put the letters back together so we can launch!';
testWidgets('Initial display', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const TypePuzzle());
// Verify intro text
expect(find.text(welcomeText), findsOneWidget);
expect(find.text(welcomeTextStep2), findsNothing);
// Verify OK button
expect(find.text('OK'), findsOneWidget);
});
}
| samples/experimental/varfont_shader_puzzle/test/widget_test.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/test/widget_test.dart",
"repo_id": "samples",
"token_count": 292
} | 1,238 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. 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:firebase_auth/firebase_auth.dart' hide User;
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'auth.dart';
class FirebaseAuthService implements Auth {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Future<bool> get isSignedIn => _googleSignIn.isSignedIn();
@override
Future<User> signIn() async {
try {
return await _signIn();
} on PlatformException {
throw SignInException();
}
}
Future<User> _signIn() async {
GoogleSignInAccount? googleUser;
if (await isSignedIn) {
googleUser = await _googleSignIn.signInSilently();
} else {
googleUser = await _googleSignIn.signIn();
}
var googleAuth = await googleUser!.authentication;
var credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
var authResult = await _auth.signInWithCredential(credential);
return _FirebaseUser(authResult.user!.uid);
}
@override
Future<void> signOut() async {
await Future.wait([
_auth.signOut(),
_googleSignIn.signOut(),
]);
}
}
class _FirebaseUser implements User {
@override
final String uid;
_FirebaseUser(this.uid);
}
| samples/experimental/web_dashboard/lib/src/auth/firebase.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/auth/firebase.dart",
"repo_id": "samples",
"token_count": 529
} | 1,239 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. 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:web_dashboard/src/api/api.dart';
import 'package:web_dashboard/src/api/mock.dart';
void main() {
group('mock dashboard API', () {
late DashboardApi api;
setUp(() {
api = MockDashboardApi();
});
group('items', () {
test('insert', () async {
var category = await api.categories.insert(Category('Coffees Drank'));
expect(category.name, 'Coffees Drank');
});
test('delete', () async {
await api.categories.insert(Category('Coffees Drank'));
var category = await api.categories.insert(Category('Miles Ran'));
var removed = await api.categories.delete(category.id!);
expect(removed, isNotNull);
expect(removed!.name, 'Miles Ran');
var categories = await api.categories.list();
expect(categories, hasLength(1));
});
test('update', () async {
var category = await api.categories.insert(Category('Coffees Drank'));
await api.categories.update(Category('Bagels Consumed'), category.id!);
var latest = await api.categories.get(category.id!);
expect(latest, isNotNull);
expect(latest!.name, equals('Bagels Consumed'));
});
test('subscribe', () async {
var stream = api.categories.subscribe();
stream.listen(expectAsync1((x) {
expect(x, hasLength(1));
expect(x.first.name, equals('Coffees Drank'));
}, count: 1));
await api.categories.insert(Category('Coffees Drank'));
});
});
group('entry service', () {
late Category category;
DateTime dateTime = DateTime(2020, 1, 1, 30, 45);
setUp(() async {
category =
await api.categories.insert(Category('Lines of code committed'));
});
test('insert', () async {
var entry = await api.entries.insert(category.id!, Entry(1, dateTime));
expect(entry.value, 1);
expect(entry.time, dateTime);
});
test('delete', () async {
await api.entries.insert(category.id!, Entry(1, dateTime));
var entry2 = await api.entries.insert(category.id!, Entry(2, dateTime));
await api.entries.delete(category.id!, entry2.id!);
var entries = await api.entries.list(category.id!);
expect(entries, hasLength(1));
});
test('update', () async {
var entry = await api.entries.insert(category.id!, Entry(1, dateTime));
var updated = await api.entries
.update(category.id!, entry.id!, Entry(2, dateTime));
expect(updated.value, 2);
});
test('subscribe', () async {
var stream = api.entries.subscribe(category.id!);
stream.listen(expectAsync1((x) {
expect(x, hasLength(1));
expect(x.first.value, equals(1));
}, count: 1));
await api.entries.insert(category.id!, Entry(1, dateTime));
});
});
});
}
| samples/experimental/web_dashboard/test/mock_service_test.dart/0 | {
"file_path": "samples/experimental/web_dashboard/test/mock_service_test.dart",
"repo_id": "samples",
"token_count": 1306
} | 1,240 |
<?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>
<!--
TODO: Replace this file with credentials from Cloud Firestore.
See https://pub.dev/packages/cloud_firestore#setup for more detail.
-->
</dict>
</plist>
| samples/flutter_maps_firestore/ios/GoogleService-Info.plist/0 | {
"file_path": "samples/flutter_maps_firestore/ios/GoogleService-Info.plist",
"repo_id": "samples",
"token_count": 130
} | 1,241 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. 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:english_words/english_words.dart' as english_words;
import 'package:flutter/material.dart';
class FormValidationDemo extends StatefulWidget {
const FormValidationDemo({super.key});
@override
State<FormValidationDemo> createState() => _FormValidationDemoState();
}
class _FormValidationDemoState extends State<FormValidationDemo> {
final _formKey = GlobalKey<FormState>();
String? adjective;
String? noun;
bool? agreedToTerms = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('📖 Story Generator'),
actions: [
Padding(
padding: const EdgeInsets.all(8),
child: TextButton(
child: const Text('Submit'),
onPressed: () {
// Validate the form by getting the FormState from the GlobalKey
// and calling validate() on it.
var valid = _formKey.currentState!.validate();
if (!valid) {
return;
}
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Your story'),
content: Text('The $adjective developer saw a $noun'),
actions: [
TextButton(
child: const Text('Done'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
},
),
),
],
),
body: Form(
key: _formKey,
child: Scrollbar(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
// A text field that validates that the text is an adjective.
TextFormField(
autofocus: true,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter an adjective.';
}
if (english_words.adjectives.contains(value)) {
return null;
}
return 'Not a valid adjective.';
},
decoration: const InputDecoration(
filled: true,
hintText: 'e.g. quick, beautiful, interesting',
labelText: 'Enter an adjective',
),
onChanged: (value) {
adjective = value;
},
),
const SizedBox(
height: 24,
),
// A text field that validates that the text is a noun.
TextFormField(
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a noun.';
}
if (english_words.nouns.contains(value)) {
return null;
}
return 'Not a valid noun.';
},
decoration: const InputDecoration(
filled: true,
hintText: 'i.e. a person, place or thing',
labelText: 'Enter a noun',
),
onChanged: (value) {
noun = value;
},
),
const SizedBox(
height: 24,
),
// A custom form field that requires the user to check a
// checkbox.
FormField<bool>(
initialValue: false,
validator: (value) {
if (value == false) {
return 'You must agree to the terms of service.';
}
return null;
},
builder: (formFieldState) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Checkbox(
value: agreedToTerms,
onChanged: (value) {
// When the value of the checkbox changes,
// update the FormFieldState so the form is
// re-validated.
formFieldState.didChange(value);
setState(() {
agreedToTerms = value;
});
},
),
Text(
'I agree to the terms of service.',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
if (!formFieldState.isValid)
Text(
formFieldState.errorText ?? "",
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
color: Theme.of(context).colorScheme.error),
),
],
);
},
),
],
),
),
),
),
);
}
}
| samples/form_app/lib/src/validation.dart/0 | {
"file_path": "samples/form_app/lib/src/validation.dart",
"repo_id": "samples",
"token_count": 3721
} | 1,242 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/form_app/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/form_app/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,243 |
#import "GeneratedPluginRegistrant.h"
| samples/game_template/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/game_template/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,244 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../audio/audio_controller.dart';
import '../audio/sounds.dart';
import '../player_progress/player_progress.dart';
import '../style/palette.dart';
import '../style/responsive_screen.dart';
import 'levels.dart';
class LevelSelectionScreen extends StatelessWidget {
const LevelSelectionScreen({super.key});
@override
Widget build(BuildContext context) {
final palette = context.watch<Palette>();
final playerProgress = context.watch<PlayerProgress>();
return Scaffold(
backgroundColor: palette.backgroundLevelSelection,
body: ResponsiveScreen(
squarishMainArea: Column(
children: [
const Padding(
padding: EdgeInsets.all(16),
child: Center(
child: Text(
'Select level',
style:
TextStyle(fontFamily: 'Permanent Marker', fontSize: 30),
),
),
),
const SizedBox(height: 50),
Expanded(
child: ListView(
children: [
for (final level in gameLevels)
ListTile(
enabled: playerProgress.highestLevelReached >=
level.number - 1,
onTap: () {
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context)
.go('/play/session/${level.number}');
},
leading: Text(level.number.toString()),
title: Text('Level #${level.number}'),
)
],
),
),
],
),
rectangularMenuArea: FilledButton(
onPressed: () {
GoRouter.of(context).go('/');
},
child: const Text('Back'),
),
),
);
}
}
| samples/game_template/lib/src/level_selection/level_selection_screen.dart/0 | {
"file_path": "samples/game_template/lib/src/level_selection/level_selection_screen.dart",
"repo_id": "samples",
"token_count": 1163
} | 1,245 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. 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';
/// A palette of colors to be used in the game.
///
/// The reason we're not going with something like Material Design's
/// `Theme` is simply that this is simpler to work with and yet gives
/// us everything we need for a game.
///
/// Games generally have more radical color palettes than apps. For example,
/// every level of a game can have radically different colors.
/// At the same time, games rarely support dark mode.
///
/// Colors taken from this fun palette:
/// https://lospec.com/palette-list/crayola84
///
/// Colors here are implemented as getters so that hot reloading works.
/// In practice, we could just as easily implement the colors
/// as `static const`. But this way the palette is more malleable:
/// we could allow players to customize colors, for example,
/// or even get the colors from the network.
class Palette {
Color get pen => const Color(0xff1d75fb);
Color get darkPen => const Color(0xFF0050bc);
Color get redPen => const Color(0xFFd10841);
Color get inkFullOpacity => const Color(0xff352b42);
Color get ink => const Color(0xee352b42);
Color get backgroundMain => const Color(0xffffffd1);
Color get backgroundLevelSelection => const Color(0xffa2dcc7);
Color get backgroundPlaySession => const Color(0xffffebb5);
Color get background4 => const Color(0xffffd7ff);
Color get backgroundSettings => const Color(0xffbfc8e3);
Color get trueWhite => const Color(0xffffffff);
}
| samples/game_template/lib/src/style/palette.dart/0 | {
"file_path": "samples/game_template/lib/src/style/palette.dart",
"repo_id": "samples",
"token_count": 465
} | 1,246 |
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import audioplayers_darwin
import firebase_core
import firebase_crashlytics
import games_services
import in_app_purchase_storekit
import path_provider_foundation
import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
FLTFirebaseCrashlyticsPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCrashlyticsPlugin"))
SwiftGamesServicesPlugin.register(with: registry.registrar(forPlugin: "SwiftGamesServicesPlugin"))
InAppPurchasePlugin.register(with: registry.registrar(forPlugin: "InAppPurchasePlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
}
| samples/game_template/macos/Flutter/GeneratedPluginRegistrant.swift/0 | {
"file_path": "samples/game_template/macos/Flutter/GeneratedPluginRegistrant.swift",
"repo_id": "samples",
"token_count": 304
} | 1,247 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Isolate Example rebuild script
steps:
- name: Remove runners
rmdirs:
- android
- ios
- macos
- linux
- windows
- name: Recreate runners
flutter: create --org dev.flutter --platforms android,ios,macos,linux,windows .
- name: Flutter upgrade
flutter: pub upgrade --major-versions
- name: Flutter build macOS
flutter: build macos
- name: Flutter build macOS
flutter: build ios --simulator
| samples/isolate_example/codelab_rebuild.yaml/0 | {
"file_path": "samples/isolate_example/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 200
} | 1,248 |
package com.example.material_3_demo
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/material_3_demo/android/app/src/main/kotlin/com/example/material_3_demo/MainActivity.kt/0 | {
"file_path": "samples/material_3_demo/android/app/src/main/kotlin/com/example/material_3_demo/MainActivity.kt",
"repo_id": "samples",
"token_count": 41
} | 1,249 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. 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';
class Credentials {
final String username;
final String password;
Credentials(this.username, this.password);
}
class SignInScreen extends StatefulWidget {
final ValueChanged<Credentials> onSignIn;
const SignInScreen({
required this.onSignIn,
super.key,
});
@override
State<SignInScreen> createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: Card(
child: Container(
constraints: BoxConstraints.loose(const Size(600, 600)),
padding: const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text('Sign in',
style: Theme.of(context).textTheme.headlineMedium),
TextField(
decoration: const InputDecoration(labelText: 'Username'),
controller: _usernameController,
),
TextField(
decoration: const InputDecoration(labelText: 'Password'),
obscureText: true,
controller: _passwordController,
),
Padding(
padding: const EdgeInsets.all(16),
child: TextButton(
onPressed: () async {
widget.onSignIn(Credentials(
_usernameController.value.text,
_passwordController.value.text));
},
child: const Text('Sign in'),
),
),
],
),
),
),
),
);
}
| samples/navigation_and_routing/lib/src/screens/sign_in.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/screens/sign_in.dart",
"repo_id": "samples",
"token_count": 1096
} | 1,250 |
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import url_launcher_macos
import window_size
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
WindowSizePlugin.register(with: registry.registrar(forPlugin: "WindowSizePlugin"))
}
| samples/navigation_and_routing/macos/Flutter/GeneratedPluginRegistrant.swift/0 | {
"file_path": "samples/navigation_and_routing/macos/Flutter/GeneratedPluginRegistrant.swift",
"repo_id": "samples",
"token_count": 112
} | 1,251 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'place.dart';
class StubData {
static const List<Place> places = [
Place(
id: '1',
latLng: LatLng(45.524676, -122.681922),
name: 'Deschutes Brewery',
description:
'Beers brewed on-site & gourmet pub grub in a converted auto-body shop with a fireplace & wood beams.',
category: PlaceCategory.favorite,
starRating: 5,
),
Place(
id: '2',
latLng: LatLng(45.516887, -122.675417),
name: 'Luc Lac Vietnamese Kitchen',
description:
'Popular counter-serve offering pho, banh mi & other Vietnamese favorites in a stylish setting.',
category: PlaceCategory.favorite,
starRating: 5,
),
Place(
id: '3',
latLng: LatLng(45.528952, -122.698344),
name: 'Salt & Straw',
description:
'Quirky flavors & handmade waffle cones draw crowds to this artisinal ice cream maker\'s 3 parlors.',
category: PlaceCategory.favorite,
starRating: 5,
),
Place(
id: '4',
latLng: LatLng(45.525253, -122.684423),
name: 'TILT',
description:
'This stylish American eatery offers unfussy breakfast fare, cocktails & burgers in industrial-themed digs.',
category: PlaceCategory.favorite,
starRating: 4,
),
Place(
id: '5',
latLng: LatLng(45.513485, -122.657982),
name: 'White Owl Social Club',
description:
'Chill haunt with local beers, burgers & vegan eats, plus live music & an airy patio with a fire pit.',
category: PlaceCategory.favorite,
starRating: 4,
),
Place(
id: '6',
latLng: LatLng(45.487137, -122.799940),
name: 'Buffalo Wild Wings',
description:
'Lively sports-bar chain dishing up wings & other American pub grub amid lots of large-screen TVs.',
category: PlaceCategory.visited,
starRating: 5,
),
Place(
id: '7',
latLng: LatLng(45.416986, -122.743171),
name: 'Chevys',
description:
'Lively, informal Mexican chain with a colorful, family-friendly setting plus tequilas & margaritas.',
category: PlaceCategory.visited,
starRating: 4,
),
Place(
id: '8',
latLng: LatLng(45.430489, -122.831802),
name: 'Cinetopia',
description:
'Moviegoers can take food from the on-site eatery to their seats, with table service in 21+ theaters.',
category: PlaceCategory.visited,
starRating: 4,
),
Place(
id: '9',
latLng: LatLng(45.383030, -122.758372),
name: 'Thai Cuisine',
description:
'Informal restaurant offering Thai standards in a modest setting, plus takeout & delivery.',
category: PlaceCategory.visited,
starRating: 4,
),
Place(
id: '10',
latLng: LatLng(45.493321, -122.669330),
name: 'The Old Spaghetti Factory',
description:
'Family-friendly chain eatery featuring traditional Italian entrees amid turn-of-the-century decor.',
category: PlaceCategory.visited,
starRating: 4,
),
Place(
id: '11',
latLng: LatLng(45.548606, -122.675286),
name: 'Mississippi Pizza',
description:
'Music, trivia & other all-ages events featured at pizzeria with lounge & vegan & gluten-free pies.',
category: PlaceCategory.wantToGo,
starRating: 4,
),
Place(
id: '12',
latLng: LatLng(45.420226, -122.740347),
name: 'Oswego Grill',
description:
'Wood-grilled steakhouse favorites served in a casual, romantic restaurant with a popular happy hour.',
category: PlaceCategory.wantToGo,
starRating: 4,
),
Place(
id: '13',
latLng: LatLng(45.541202, -122.676432),
name: 'The Widmer Brothers Brewery',
description:
'Popular, enduring gastropub serving craft beers, sandwiches & eclectic entrees in a laid-back space.',
category: PlaceCategory.wantToGo,
starRating: 4,
),
Place(
id: '14',
latLng: LatLng(45.559783, -122.924103),
name: 'TopGolf',
description:
'Sprawling entertainment venue with a high-tech driving range & swanky lounge with drinks & games.',
category: PlaceCategory.wantToGo,
starRating: 5,
),
Place(
id: '15',
latLng: LatLng(45.485612, -122.784733),
name: 'Uwajimaya Beaverton',
description:
'Huge Asian grocery outpost stocking meats, produce & prepared foods plus gifts & home goods.',
category: PlaceCategory.wantToGo,
starRating: 5,
),
];
static const reviewStrings = [
'My favorite place in Portland. The employees are wonderful and so is the food. I go here at least once a month!',
'Staff was very friendly. Great atmosphere and good music. Would recommend.',
'Best. Place. In. Town. Period.'
];
}
| samples/place_tracker/lib/stub_data.dart/0 | {
"file_path": "samples/place_tracker/lib/stub_data.dart",
"repo_id": "samples",
"token_count": 2113
} | 1,252 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/platform_channels/android/gradle.properties/0 | {
"file_path": "samples/platform_channels/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,253 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:platform_channels/src/add_pet_details.dart';
import 'package:platform_channels/src/event_channel_demo.dart';
import 'package:platform_channels/src/method_channel_demo.dart';
import 'package:platform_channels/src/pet_list_screen.dart';
import 'package:platform_channels/src/platform_image_demo.dart';
void main() {
runApp(const PlatformChannelSample());
}
class PlatformChannelSample extends StatelessWidget {
const PlatformChannelSample({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Platform Channel Sample',
theme: ThemeData(
snackBarTheme: SnackBarThemeData(
backgroundColor: Colors.blue[500],
),
),
routerConfig: router(),
);
}
}
GoRouter router([String? initialLocation]) {
return GoRouter(
initialLocation: initialLocation ?? '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: 'methodChannelDemo',
builder: (context, state) => const MethodChannelDemo(),
),
GoRoute(
path: 'eventChannelDemo',
builder: (context, state) => const EventChannelDemo(),
),
GoRoute(
path: 'platformImageDemo',
builder: (context, state) => const PlatformImageDemo(),
),
GoRoute(
path: 'petListScreen',
builder: (context, state) => const PetListScreen(),
routes: [
GoRoute(
path: 'addPetDetails',
builder: (context, state) => const AddPetDetails(),
),
],
),
],
),
],
);
}
class DemoInfo {
final String demoTitle;
final String demoRoute;
DemoInfo(this.demoTitle, this.demoRoute);
}
List<DemoInfo> demoList = [
DemoInfo(
'MethodChannel Demo',
'/methodChannelDemo',
),
DemoInfo(
'EventChannel Demo',
'/eventChannelDemo',
),
DemoInfo(
'Platform Image Demo',
'/platformImageDemo',
),
DemoInfo(
'BasicMessageChannel Demo',
'/petListScreen',
)
];
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Platform Channel Sample'),
),
body: ListView(
children: demoList.map((demoInfo) => DemoTile(demoInfo)).toList(),
),
);
}
}
/// This widget is responsible for displaying the [ListTile] on [HomePage].
class DemoTile extends StatelessWidget {
final DemoInfo demoInfo;
const DemoTile(this.demoInfo, {super.key});
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(demoInfo.demoTitle),
onTap: () {
context.go(demoInfo.demoRoute);
},
);
}
}
| samples/platform_channels/lib/main.dart/0 | {
"file_path": "samples/platform_channels/lib/main.dart",
"repo_id": "samples",
"token_count": 1296
} | 1,254 |
// Copyright 2020 The Flutter team. 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_channels/src/platform_image_demo.dart';
void main() {
group('Platform Image Demo tests', () {
testWidgets('Platform Image test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(
const BasicMessageChannel<dynamic>(
'platformImageDemo', StandardMessageCodec()),
(dynamic message) async {
var byteData = await rootBundle.load('assets/eat_new_orleans.jpg');
return byteData.buffer.asUint8List();
},
);
await tester.pumpWidget(const MaterialApp(
home: PlatformImageDemo(),
));
// Initially a PlaceHolder is displayed when imageData is null.
expect(find.byType(Placeholder), findsOneWidget);
expect(find.byType(Image), findsNothing);
// Tap on ElevatedButton to get Image.
await tester.tap(find.byType(FilledButton));
await tester.pumpAndSettle();
expect(find.byType(Placeholder), findsNothing);
expect(find.byType(Image), findsOneWidget);
});
});
}
| samples/platform_channels/test/src/platform_image_demo_test.dart/0 | {
"file_path": "samples/platform_channels/test/src/platform_image_demo_test.dart",
"repo_id": "samples",
"token_count": 493
} | 1,255 |
# Provider Counter
The starter Flutter application, but using Provider to manage state.
This app is a direct counterpart to the
[simple counter application](https://flutter.io/docs/development/ui/widgets-intro#changing-widgets-in-response-to-input)
that you get when you create a new Flutter project. That one uses a `StatefulWidget` to manage
application state. The version in this repository uses a simple app state management approach,
`Provider`.
It shows how you might deal with state that is modified from outside the app (for example,
state synchronized over network) and which needs to be accessed and changed
from different parts of your app.
## Getting Started
The only important part of the app is the `lib/main.dart` file. It has comments that will walk you
through it.
For more information on the `provider` package (where `Provider` comes from), please
[see the package documentation](https://pub.dartlang.org/packages/provider).
For more information on state management in Flutter, and a list of other approaches,
head over to the
[State management page at flutter.dev](https://flutter.dev/docs/development/data-and-backend/state-mgmt).
| samples/provider_counter/README.md/0 | {
"file_path": "samples/provider_counter/README.md",
"repo_id": "samples",
"token_count": 293
} | 1,256 |
// Copyright 2020 The Flutter team. 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:provider/provider.dart';
import 'package:provider_shopper/models/cart.dart';
import 'package:provider_shopper/models/catalog.dart';
import 'package:provider_shopper/screens/catalog.dart';
Widget createCatalogScreen() => MultiProvider(
providers: [
Provider(create: (context) => CatalogModel()),
ChangeNotifierProxyProvider<CatalogModel, CartModel>(
create: (context) => CartModel(),
update: (context, catalog, cart) {
cart!.catalog = catalog;
return cart;
},
),
],
child: const MaterialApp(
home: MyCatalog(),
),
);
void main() {
final catalogListItems = CatalogModel.itemNames.sublist(0, 3);
group('CatalogScreen Widget Tests', () {
testWidgets('Testing item row counts and text', (tester) async {
await tester.pumpWidget(createCatalogScreen());
// Testing for the items on the screen after modifying
// the model for a fixed number of items.
for (var item in catalogListItems) {
expect(find.text(item), findsWidgets);
}
});
testWidgets('Testing the ADD buttons and check after clicking',
(tester) async {
await tester.pumpWidget(createCatalogScreen());
// Should find ADD buttons on the screen.
expect(find.text('ADD'), findsWidgets);
// Performing the click on the ADD button of the first item in the list.
await tester.tap(find.widgetWithText(TextButton, 'ADD').first);
await tester.pumpAndSettle();
// Verifying if the tapped ADD button has changed to the check icon.
expect(find.byIcon(Icons.check), findsOneWidget);
});
});
}
| samples/provider_shopper/test/catalog_widget_test.dart/0 | {
"file_path": "samples/provider_shopper/test/catalog_widget_test.dart",
"repo_id": "samples",
"token_count": 705
} | 1,257 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/simple_shader/android/gradle.properties/0 | {
"file_path": "samples/simple_shader/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,258 |
name: simple_shader
description: Using a shader, simply.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
flutter_shaders: ^0.1.0
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
shaders:
- shaders/simple.frag
| samples/simple_shader/pubspec.yaml/0 | {
"file_path": "samples/simple_shader/pubspec.yaml",
"repo_id": "samples",
"token_count": 156
} | 1,259 |
include: package:analysis_defaults/flutter.yaml
# Files under typer/ are partially completed files, and often invalid
analyzer:
exclude:
- typer/**
| samples/simplistic_calculator/analysis_options.yaml/0 | {
"file_path": "samples/simplistic_calculator/analysis_options.yaml",
"repo_id": "samples",
"token_count": 47
} | 1,260 |
# Simplistic Editor
This sample text editor showcases the use of TextEditingDeltas and a DeltaTextInputClient to expand
and contract styled ranges of text. For more information visit https://api.flutter.dev/flutter/services/TextEditingDelta-class.html.
https://user-images.githubusercontent.com/948037/166981868-0529e328-18e7-48de-9245-524b91c63c0c.mov
# Structure
## Visualization Layer
The layer that showcases the `TextEditingDelta` history in a ListView. These widgets are all unique to this sample
and are unlikely to contain much logic the typical user will need.
<img width="710" alt="Screen Shot 2022-05-05 at 9 53 50 AM" src="https://user-images.githubusercontent.com/948037/166977349-3924f1e0-a549-40bc-9041-dbd18510ae3f.png">
### `TextEditingDeltaHistoryManager`
An inherited widget that handles the state of the text editing delta history that sits below the input field
in a `ListView`. This widget contains the list of `TextEditingDelta`s, and the callback needed to update the list
when a delta is received from the platform, as well as when the framework reports a delta. Deltas
can be reported by the framework when the selection is changed as a result of a gesture such as tapping or dragging,
when the `TextEditingValue` is updated as a result of a copy/paste, and when the `TextEditingValue` is updated by an `Intent` -> `Action`.
This widget is primarily used to wrap the `BasicTextField`, so the `BasicTextInputClient`, which is lower in the tree, can
update the history of `TextEditingDelta`s as they are reported by the platform and framework.
### `TextEditingDeltaView`
A widget that represents the content of a `TextEditingDelta`. A list of `TextEditingDeltaView`s sits below
the input field showcasing a history of `TextEditingDelta`s that have occurred on that input field. A
`TextEditingDeltaView` varies in color depending on the type of `TextEditingDelta`. `TextEditingDeltaInsertion`s
are green, `TextEditingDeltaDeletion`s are red, `TextEditingDeltaReplacement`s are yellow, and `TextEditingDeltaNonTextUpdate`s are blue.
## Replacements Layer
The layer that handles the styling of the input field, including expanding and contracting the styled ranges based
on the deltas that are received from the platform, and the handling of the state of the styling toggle button toolbar.
This layer contains a mixture of logic unique to this sample and helpful for developers expecting to consume the
`TextEditingDelta` APIs.
<img width="168" alt="Screen Shot 2022-05-05 at 10 22 27 AM" src="https://user-images.githubusercontent.com/948037/166978414-0db1a76b-1104-48e9-a92e-aa8fd0d493dd.png">
### `ToggleButtonsStateManager`
An inherited widget that handles the state of the styling toggle button toolbar that sits on the top
of the input field. This toolbar includes three buttons: Bold, Italic, and Underline. This widget contains
the state of the `ToggleButtons`, and the callbacks needed to update the state when the selection has changed
or when the toggle buttons have been pressed.
This widget wraps the `ToggleButtons` so it may access the state of the toggle buttons and update that state
when they have been pressed. It also wraps the `BasicTextField`, so that the `BasicTextInputClient`, which is lower
in the tree may access the callback necessary to update the toggle button state when the selection has changed.
### `TextEditingInlineSpanReplacement`
A data structure that represents a replacement, with a range, and a generator that produces
the desired `InlineSpan`. The generator should return a `TextSpan` with the desired styling, and the
range should be the target range for that styling in the current `TextEditingValue`. This structure also
contains an expand property which dictates if the replacement should continue to expand from the back edge.
For example say we have "Hello |world|", where "world" is covered by a replacement that bolds the text. If
the expand property is true, typing text at the back edge of "world|" will expand the range and make any text
typed also bold. If it is false then the text typed would not be bold. Additionally, this structure contains
methods to update the replacement for each subclass of `TextEditingDelta` and a method to remove a section of
the replacement range.
### `ReplacementTextEditingController`
A `TextEditingController` that manages a list of `TextEditingInlineSpanReplacement`s, that insert custom `InlineSpan`s
in place of matched `TextRange`s. The controller syncs the replacement ranges based on the type of `TextEditingDelta`
it receives from the `BasicTextInputClient`, managing any overlapping ranges accordingly.
This controller also contains convenience methods used by the styling toggle buttons toolbar to un-style
certain ranges, disable the expand property of a replacement, and get the common replacements at a selection
to determine the current toggle button state.
## Text Input Layer
The layer that defines the appearance of a text input field, handles the text input received from
the platform, and mutations done by the framework through gestures and keyboard shortcuts. These classes begin to
demonstrate the types of logic developers may need if they wish to interact with `TextEditingDelta`s.
<img width="710" alt="Screen Shot 2022-05-05 at 9 57 56 AM" src="https://user-images.githubusercontent.com/948037/166977553-55eec6ef-49bb-43d9-8e2a-91a1b5a3cbca.png">
### `BasicTextField`
A basic text field that defines the appearance, and the selection gestures of a basic text input client.
These gestures call on methods in `RenderEditable` to mutate the `TextEditingValue` through the `TextSelectionDelegate`,
which, in this case, is a the `BasicTextInputClient`.
This widget wraps the `BasicTextInputClient` to define its appearance such as borders, and selection overlay
appearance based on the platform.
### `BasicTextInputClient`
A `DeltaTextInputClient`, a `TextInputClient` that receives `TextEditingDelta`s from the platform instead of the
entire `TextEditingValue`. It is responsible for sending/receiving information from the framework to the platforms text input
plugin, and vice-versa. A list of `TextEditingDelta`s is received from the platform and can be handled through
the method `updateEditingValueWithDeltas`. When the framework makes a change to the `TextEditingValue`, the updated value
is sent through the `TextInputConnection.setEditingState` method.
A `TextSelectionDelegate` that handles the manipulation of selection through toolbar or shortcut keys.
An `Actions` widget is used to handle certain hardware keyboard shortcuts, such as the backspace key to delete text, and
the left and right arrows keys to move the selection.
The `RenderObject`, `RenderEditable` (`_Editable`), is used at the leaf node of the `BasicTextInputClient` to render the `TextSpan`s given
by the `ReplacementTextEditingController`.
| samples/simplistic_editor/README.md/0 | {
"file_path": "samples/simplistic_editor/README.md",
"repo_id": "samples",
"token_count": 1743
} | 1,261 |
import 'package:flutter/material.dart';
import 'app_state.dart';
import 'app_state_manager.dart';
/// The toggle buttons that can be selected.
enum ToggleButtonsState {
bold,
italic,
underline,
}
class FormattingToolbar extends StatelessWidget {
const FormattingToolbar({super.key});
@override
Widget build(BuildContext context) {
final AppStateManager manager = AppStateManager.of(context);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ToggleButtons(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
isSelected: [
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.bold),
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.italic),
manager.appState.toggleButtonsState
.contains(ToggleButtonsState.underline),
],
onPressed: (index) => AppStateWidget.of(context)
.updateToggleButtonsStateOnButtonPressed(index),
children: const [
Icon(Icons.format_bold),
Icon(Icons.format_italic),
Icon(Icons.format_underline),
],
),
],
),
);
}
}
| samples/simplistic_editor/lib/formatting_toolbar.dart/0 | {
"file_path": "samples/simplistic_editor/lib/formatting_toolbar.dart",
"repo_id": "samples",
"token_count": 636
} | 1,262 |
#!/bin/bash
set -e
DIR="${BASH_SOURCE%/*}"
source "$DIR/flutter_ci_script_shared.sh"
flutter doctor -v
declare -ar PROJECT_NAMES=(
"add_to_app/android_view/flutter_module_using_plugin"
"add_to_app/books/flutter_module_books"
"add_to_app/fullscreen/flutter_module"
"add_to_app/multiple_flutters/multiple_flutters_module"
"add_to_app/plugin/flutter_module_using_plugin"
"add_to_app/prebuilt_module/flutter_module"
"analysis_defaults"
"android_splash_screen"
"animations"
"background_isolate_channels"
"code_sharing/client"
"code_sharing/server"
"code_sharing/shared"
"context_menus"
"deeplink_store_example"
"desktop_photo_search/fluent_ui"
"desktop_photo_search/material"
"experimental/federated_plugin/federated_plugin"
"experimental/federated_plugin/federated_plugin/example"
"experimental/federated_plugin/federated_plugin_macos"
"experimental/federated_plugin/federated_plugin_platform_interface"
"experimental/federated_plugin/federated_plugin_web"
"experimental/federated_plugin/federated_plugin_windows"
# TODO: 'onBackground' is deprecated and shouldn't be used.
# "experimental/linting_tool"
"experimental/pedometer"
"experimental/pedometer/example"
"experimental/varfont_shader_puzzle"
"experimental/web_dashboard"
"flutter_maps_firestore"
"form_app"
# TODO: 'onBackground' is deprecated and shouldn't be used.
# "game_template"
"google_maps"
"infinite_list"
"ios_app_clip"
"isolate_example"
# TODO(ewindmill): Add back when deps allow
# "material_3_demo"
"navigation_and_routing"
"place_tracker"
"platform_channels"
"platform_design"
"platform_view_swift"
"provider_counter"
"provider_shopper"
"simple_shader"
"simplistic_calculator"
# TODO(DomesticMouse): The method 'isSelectionWithinTextBounds' isn't defined for the type 'TextEditingController'
# "simplistic_editor"
"testing_app"
"veggieseasons"
"web_embedding/element_embedding_demo"
"web/_tool"
"web/samples_index"
)
ci_projects "beta" "${PROJECT_NAMES[@]}"
echo "-- Success --"
| samples/tool/flutter_ci_script_beta.sh/0 | {
"file_path": "samples/tool/flutter_ci_script_beta.sh",
"repo_id": "samples",
"token_count": 896
} | 1,263 |
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
| samples/veggieseasons/ios/Flutter/Release.xcconfig/0 | {
"file_path": "samples/veggieseasons/ios/Flutter/Release.xcconfig",
"repo_id": "samples",
"token_count": 69
} | 1,264 |
#import "GeneratedPluginRegistrant.h"
| samples/veggieseasons/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/veggieseasons/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,265 |
// Copyright 2018 The Flutter team. 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/cupertino.dart';
import 'package:veggieseasons/styles.dart';
// The widgets in this file present a Cupertino-style settings item to the user.
// In the future, the Cupertino package in the Flutter SDK will include
// dedicated widgets for this purpose, but for now they're done here.
//
// See https://github.com/flutter/flutter/projects/29 for more info.
typedef SettingsItemCallback = FutureOr<void> Function();
class SettingsNavigationIndicator extends StatelessWidget {
const SettingsNavigationIndicator({super.key});
@override
Widget build(BuildContext context) {
return const Icon(
CupertinoIcons.forward,
color: Styles.settingsMediumGray,
size: 21,
);
}
}
class SettingsIcon extends StatelessWidget {
const SettingsIcon({
required this.icon,
this.foregroundColor = CupertinoColors.white,
this.backgroundColor = CupertinoColors.black,
super.key,
});
final Color backgroundColor;
final Color foregroundColor;
final IconData icon;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: backgroundColor,
),
child: Center(
child: Icon(
icon,
color: foregroundColor,
size: 20,
),
),
);
}
}
class SettingsItem extends StatefulWidget {
const SettingsItem({
required this.label,
this.icon,
this.content,
this.subtitle,
this.onPress,
super.key,
});
final String label;
final Widget? icon;
final Widget? content;
final String? subtitle;
final SettingsItemCallback? onPress;
@override
State<SettingsItem> createState() => _SettingsItemState();
}
class _SettingsItemState extends State<SettingsItem> {
bool pressed = false;
@override
Widget build(BuildContext context) {
var themeData = CupertinoTheme.of(context);
var brightness = CupertinoTheme.brightnessOf(context);
return AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: Styles.settingsItemColor(brightness),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () async {
if (widget.onPress != null) {
setState(() {
pressed = true;
});
await widget.onPress!();
Future.delayed(
const Duration(milliseconds: 150),
() {
setState(() {
pressed = false;
});
},
);
}
},
child: SizedBox(
height: widget.subtitle == null ? 44 : 57,
child: Row(
children: [
if (widget.icon != null)
Padding(
padding: const EdgeInsets.only(
left: 15,
bottom: 2,
),
child: SizedBox(
height: 29,
width: 29,
child: widget.icon,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 15,
),
child: widget.subtitle != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 8.5),
Text(widget.label,
style: themeData.textTheme.textStyle),
const SizedBox(height: 4),
Text(
widget.subtitle!,
style: Styles.settingsItemSubtitleText(themeData),
),
],
)
: Padding(
padding: const EdgeInsets.only(top: 1.5),
child: Text(widget.label,
style: themeData.textTheme.textStyle),
),
),
),
Padding(
padding: const EdgeInsets.only(right: 11),
child: widget.content ?? Container(),
),
],
),
),
),
);
}
}
| samples/veggieseasons/lib/widgets/settings_item.dart/0 | {
"file_path": "samples/veggieseasons/lib/widgets/settings_item.dart",
"repo_id": "samples",
"token_count": 2313
} | 1,266 |
name: example
description: "flutter_web_startup_analyzer example"
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ^3.2.0
flutter: ^3.16.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
web_startup_analyzer:
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
| samples/web/_packages/web_startup_analyzer/example/pubspec.yaml/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/example/pubspec.yaml",
"repo_id": "samples",
"token_count": 176
} | 1,267 |
# Sample Index and Web Demos
This directory contains the index hosted at [flutter.github.io/samples][samples]
and web demos hosted with it.
## See the demos in action
Compiled versions of the samples are hosted at
https://flutter.github.io/samples/#?platform=web.
## Building samples code
Run the demo using the `chrome` device type:
```console
$ cd charts
$ flutter packages get
$ flutter run -d chrome
```
You should see a message printing the URL to access: `http://localhost:8080`
## Deploying to GitHub Pages
This project uses a GitHub action to deploy update the `gh-pages` branch. To
do this manually, you can also use `package:peanut`:
```console
$ flutter pub global activate peanut
```
Verify `pub get` has been run on each demo:
```console
$ dart run _tool/verify_packages.dart
```
Build all demos, along with the sample index:
```console
$ flutter pub global run peanut
```
Deploy to GitHub Pages:
```console
$ git push origin gh-pages:gh-pages
```
## Building the sample index
See sample_index/README.md for details
[web]: https://flutter.dev/web
[samples]: https://flutter.github.io/samples/
[peanut]: https://github.com/kevmoo/peanut.dart
| samples/web/readme.md/0 | {
"file_path": "samples/web/readme.md",
"repo_id": "samples",
"token_count": 365
} | 1,268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.